diff --git "a/482.jsonl" "b/482.jsonl" new file mode 100644--- /dev/null +++ "b/482.jsonl" @@ -0,0 +1,39 @@ +{"seq_id":"32642470135","text":"from flask import Flask\nfrom flask_wtf.csrf import CSRFProtect\n\nfrom .model import db, login_manager\nfrom .controllers.cart_controller import cart_controller\nfrom .controllers.mobile_controller import mobile_controller\nfrom .controllers import google_controller, github_controller, facebook_controller\nfrom .cli import add_cli_methods\nfrom .config import Config\nfrom .basic_routes import bootstrap_basic_routes\nfrom .oauth import register_oauth\n\n\ndef bootstrap_wtf_csrf(app):\n csrf = CSRFProtect(app)\n csrf.init_app(app)\n\n\ndef bootstrap_blueprints(app):\n app.register_blueprint(mobile_controller, url_prefix='/mobile')\n app.register_blueprint(cart_controller, url_prefix='/cart')\n app.register_blueprint(google_controller, url_prefix='/login')\n app.register_blueprint(github_controller, url_prefix='/login')\n app.register_blueprint(facebook_controller, url_prefix='/login')\n\n\ndef register_oauth_controllers():\n register_oauth(google_controller)\n register_oauth(facebook_controller)\n register_oauth(github_controller)\n\n\ndef create_app():\n \"\"\"\n This method is used to create the flask app and bootstrap it with other\n libraries which are used in the project\n :return: Flask\n \"\"\"\n app = Flask(__name__, template_folder=\"../templates\", static_folder=\"../static\")\n app.config.from_object(Config)\n db.init_app(app)\n bootstrap_wtf_csrf(app)\n login_manager.init_app(app)\n bootstrap_basic_routes(app)\n bootstrap_blueprints(app)\n add_cli_methods(app)\n register_oauth_controllers()\n return app\n","repo_name":"Learn-And-Earn/flask-start","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"74357733213","text":"import os\nimport nrrd\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\nfrom tqdm import tqdm\n\nfrom skimage.exposure import rescale_intensity, equalize_hist\nfrom skimage.segmentation import (morphological_chan_vese,\n morphological_geodesic_active_contour,\n inverse_gaussian_gradient,\n checkerboard_level_set)\nfrom skimage import measure\n\nfrom skimage.exposure import rescale_intensity\nfrom skimage import filters\nfrom skimage.feature import canny\nfrom scipy import ndimage as ndi\n\nfrom pnet_vis import mcubes\nfrom skimage.segmentation import chan_vese,circle_level_set \n\ndef show_bbox_scene(img, contours):\n plt.imshow(img)\n seg = chan_vese(img,mu=0.16)\n #seg = circle_level_set(img)\n plt.imshow(seg) \n for c in contours:\n plt.scatter(c[:,0], c[:,1], c='r')\n \n plt.show()\n return\ndef adapt_bbox(bbox, w, h):\n # ajusto la bbox a tam fijo: w, h\n cw = bbox[2] - bbox[0]\n ch = bbox[3] - bbox[1]\n if cw < w: \n offset = (w - cw)//2\n bbox[0]-= offset\n bbox[2]+= offset\n if ch < h: \n offset = (h - ch)//2\n bbox[1]-= offset\n bbox[3]+= offset\n \n cw = bbox[2] - bbox[0]\n ch = bbox[3] - bbox[1]\n if cw < w: bbox[2]+=1\n if ch < h: bbox[3]+=1\n cw = bbox[2] - bbox[0]\n ch = bbox[3] - bbox[1]\n\n return bbox\n \ndef get_bbox_from_mask(mask, offset=3):\n pixels = np.argwhere(mask > 0)\n bbox = []\n if len(pixels) > 0:\n bbox = [pixels.T[0].min()-offset, pixels.T[1].min()-offset, pixels.T[0].max()+offset, pixels.T[1].max()+offset]\n return bbox\n\ndef get_contours_from_mask(mask, img=[],offset=3):\n\n pixels = np.argwhere(mask > 0)\n lpx = [] \n\n if len(pixels) > 0:\n bbox = [pixels.T[0].min()-offset, pixels.T[1].min()-offset, pixels.T[0].max()+offset, pixels.T[1].max()+offset]\n amask = mask[bbox[0]:bbox[2],bbox[1]:bbox[3]]\n \n contours_gt = measure.find_contours(amask, fully_connected='high')\n\n if len(img)>0:\n aimg = img[bbox[0]:bbox[2],bbox[1]:bbox[3]]\n #show_bbox_scene(aimg.T, contours_gt)\n\n for contour in contours_gt:\n for px in contour:\n lpx.append(px)\n\n return lpx\n\nPTOS3D_RESO = 336512\ndef convert(nfiles, npoints):\n Lr, Lm, npoints, Ln = load_nrrd_data(\"../RL-AtriaSeg/Training Set/\", nfiles, npoints)\n pointsc, masksc = np.array(Lr), np.array(Lm)\n fname = \"atria_cp.\"+str(nfiles)+\".\"+str(npoints)+\".npy\"\n mname = \"atria_mask_cp.\"+str(nfiles)+\".\"+str(npoints)+\".npy\"\n np.save(fname, pointsc)\n np.save(mname, masksc)\n np.savetxt(\"atria_cp.\"+str(nfiles)+\".\"+str(npoints)+\".ids.txt\", np.array(Ln),fmt=\"%s\")\n print(\"Saved: \", fname, mname, pointsc.shape, masksc.shape)\n\ndef get_AtriaContourPoints(reso_, mask_, npoints_per_image=-1, show_images = False):\n \n ax = []\n if show_images:\n fig, ax = plt.subplots(nrows=1, ncols=2, figsize=(8, 8))\n \n Lxyz, Llabels = [],[]\n zmax = reso_.shape[2]\n vol = np.zeros([mask_.shape[0],mask_.shape[1],mask_.shape[2]]).astype(int)\n\n for z in tqdm( range(zmax)):\n img, mask = reso_[:,:,z],mask_[:,:,z]\n \n # Seleccion de los pixels\n pixels = get_contours_from_mask(mask, img)\n \n for i, p in enumerate(pixels):\n x, y = np.copy(int(p[0])), np.copy(int(p[1]))\n Lxyz.append( np.array([x,y,z]) )\n Llabels.append( 1 )\n vol[x,y,z] = 1\n \n print(\"Nptos (MRI): \", len(Lxyz))\n return np.array(Lxyz), np.array(Llabels), vol\n\n\ndef load_nrrd_data(training_path, maxFiles, npoints):\n Lmasks, Lresos, Lnames = [],[], []\n all_points = 0\n nfiles = 0\n\n #tr_ids = open(\"atria_cp.80.128.ids.txt\").read().split('\\n')\n for d in os.listdir(training_path):\n if len(d) > 10 and nfiles < maxFiles:# and (d in tr_ids) == False: \n _mask, mask_header = nrrd.read(training_path+d+'/laendo.nrrd')\n _reso, reso_header = nrrd.read(training_path+d+'/lgemri.nrrd')\n \n #reso, mask = sub_sample(_reso, _mask, 128)\n reso, mask, vol = get_AtriaContourPoints(_reso, _mask)\n print(reso.shape, mask.shape, npoints)\n id_points = np.random.randint(0, reso.shape[0], npoints)\n reso = reso[id_points]\n mask = mask[id_points]\n\n \n #visualize_data(reso, mask)\n Lresos.append(reso)\n Lmasks.append(mask)\n Lnames.append(d)\n all_points+= len(reso)\n nfiles+=1 \n print(d, all_points)\n\n mcubes(_mask)\n\n \n return Lresos,Lmasks, reso.shape[0], Lnames \n\n\ndef load_data_(point_cloud_batch, label_cloud_batch):\n print(\"load_data_: \", point_cloud_batch.shape, label_cloud_batch.shape)\n NUM_SAMPLE_POINTS = point_cloud_batch.shape[0]\n point_cloud_batch.set_shape([NUM_SAMPLE_POINTS, 3])\n label_cloud_batch.set_shape([NUM_SAMPLE_POINTS, 3])\n return point_cloud_batch, label_cloud_batch\n\n\ndef generate_dataset(points, labels, BATCH_SIZE, is_training=True):\n points = np.array(points)\n labels = np.array(labels)\n print(\"gs: \", points.shape, labels.shape)\n input(\".......\")\n dataset = tf.data.Dataset.from_tensor_slices((points, labels))\n dataset = dataset.shuffle(BATCH_SIZE * 100) if is_training else dataset\n dataset = dataset.map(load_data_)\n dataset = dataset.batch(batch_size=BATCH_SIZE)\n #dataset = (\n # dataset.map(augment, num_parallel_calls=tf.data.AUTOTUNE)\n # if is_training\n # else dataset\n #)\n return dataset\n\n \"\"\"\n## PointNet model\n\nThe figure below depicts the internals of the PointNet model family:\n\n![](https://i.imgur.com/qFLNw5L.png)\n\nGiven that PointNet is meant to consume an ***unordered set*** of coordinates as its input data,\nits architecture needs to match the following characteristic properties\nof point cloud data:\n\n### Permutation invariance\n\nGiven the unstructured nature of point cloud data, a scan made up of `n` points has `n!`\npermutations. The subsequent data processing must be invariant to the different\nrepresentations. In order to make PointNet invariant to input permutations, we use a\nsymmetric function (such as max-pooling) once the `n` input points are mapped to\nhigher-dimensional space. The result is a **global feature vector** that aims to capture\nan aggregate signature of the `n` input points. The global feature vector is used alongside\nlocal point features for segmentation.\n\n![](https://i.imgur.com/0mrvvjb.png)\n\n### Transformation invariance\n\nSegmentation outputs should be unchanged if the object undergoes certain transformations,\nsuch as translation or scaling. For a given input point cloud, we apply an appropriate\nrigid or affine transformation to achieve pose normalization. Because each of the `n` input\npoints are represented as a vector and are mapped to the embedding spaces independently,\napplying a geometric transformation simply amounts to matrix multiplying each point with\na transformation matrix. This is motivated by the concept of\n[Spatial Transformer Networks](https://arxiv.org/abs/1506.02025).\n\nThe operations comprising the T-Net are motivated by the higher-level architecture of\nPointNet. MLPs (or fully-connected layers) are used to map the input points independently\nand identically to a higher-dimensional space; max-pooling is used to encode a global\nfeature vector whose dimensionality is then reduced with fully-connected layers. The\ninput-dependent features at the final fully-connected layer are then combined with\nglobally trainable weights and biases, resulting in a 3-by-3 transformation matrix.\n\n![](https://i.imgur.com/aEj3GYi.png)\n\n### Point interactions\n\nThe interaction between neighboring points often carries useful information (i.e., a\nsingle point should not be treated in isolation). Whereas classification need only make\nuse of global features, segmentation must be able to leverage local point features along\nwith global point features.\n\n\n**Note**: The figures presented in this section have been taken from the\n[original paper](https://arxiv.org/abs/1612.00593).\n\"\"\"\n\n\"\"\"\nNow that we know the pieces that compose the PointNet model, we can implement the model.\nWe start by implementing the basic blocks i.e., the convolutional block and the multi-layer\nperceptron block.\n\"\"\"\n\n\ndef conv_block(x: tf.Tensor, filters: int, name: str) -> tf.Tensor:\n x = layers.Conv1D(filters, kernel_size=1, padding=\"valid\", name=f\"{name}_conv\")(x)\n x = layers.BatchNormalization(momentum=0.0, name=f\"{name}_batch_norm\")(x)\n return layers.Activation(\"relu\", name=f\"{name}_relu\")(x)\n\n\ndef mlp_block(x: tf.Tensor, filters: int, name: str) -> tf.Tensor:\n x = layers.Dense(filters, name=f\"{name}_dense\")(x)\n x = layers.BatchNormalization(momentum=0.0, name=f\"{name}_batch_norm\")(x)\n return layers.Activation(\"relu\", name=f\"{name}_relu\")(x)\n\n\n\"\"\"\nWe implement a regularizer (taken from\n[this example](https://keras.io/examples/vision/pointnet/#build-a-model))\nto enforce orthogonality in the feature space. This is needed to ensure\nthat the magnitudes of the transformed features do not vary too much.\n\"\"\"\n\n\nclass OrthogonalRegularizer(keras.regularizers.Regularizer):\n \"\"\"Reference: https://keras.io/examples/vision/pointnet/#build-a-model\"\"\"\n\n def __init__(self, num_features, l2reg=0.001):\n self.num_features = num_features\n self.l2reg = l2reg\n self.identity = tf.eye(num_features)\n\n def __call__(self, x):\n x = tf.reshape(x, (-1, self.num_features, self.num_features))\n xxt = tf.tensordot(x, x, axes=(2, 2))\n xxt = tf.reshape(xxt, (-1, self.num_features, self.num_features))\n return tf.reduce_sum(self.l2reg * tf.square(xxt - self.identity))\n\n def get_config(self):\n config = super(TransformerEncoder, self).get_config()\n config.update({\"num_features\": self.num_features, \"l2reg_strength\": self.l2reg})\n return config\n\n\n\"\"\"\nThe next piece is the transformation network which we explained earlier.\n\"\"\"\n\n\ndef transformation_net(inputs: tf.Tensor, num_features: int, name: str) -> tf.Tensor:\n \"\"\"\n Reference: https://keras.io/examples/vision/pointnet/#build-a-model.\n\n The `filters` values come from the original paper:\n https://arxiv.org/abs/1612.00593.\n \"\"\"\n x = conv_block(inputs, filters=64, name=f\"{name}_1\")\n x = conv_block(x, filters=128, name=f\"{name}_2\")\n x = conv_block(x, filters=1024, name=f\"{name}_3\")\n x = layers.GlobalMaxPooling1D()(x)\n x = mlp_block(x, filters=512, name=f\"{name}_1_1\")\n x = mlp_block(x, filters=256, name=f\"{name}_2_1\")\n return layers.Dense(\n num_features * num_features,\n kernel_initializer=\"zeros\",\n bias_initializer=keras.initializers.Constant(np.eye(num_features).flatten()),\n activity_regularizer=OrthogonalRegularizer(num_features),\n name=f\"{name}_final\",\n )(x)\n\n\ndef transformation_block(inputs: tf.Tensor, num_features: int, name: str) -> tf.Tensor:\n transformed_features = transformation_net(inputs, num_features, name=name)\n transformed_features = layers.Reshape((num_features, num_features))(\n transformed_features\n )\n return layers.Dot(axes=(2, 1), name=f\"{name}_mm\")([inputs, transformed_features])\n\n\n\"\"\"\nFinally, we piece the above blocks together and implement the segmentation model.\n\"\"\"\n\n\ndef get_shape_segmentation_model(num_points: int, num_classes: int) -> keras.Model:\n input_points = keras.Input(shape=(None, 3))\n\n # PointNet Classification Network.\n transformed_inputs = transformation_block(\n input_points, num_features=3, name=\"input_transformation_block\"\n )\n features_64 = conv_block(transformed_inputs, filters=64, name=\"features_64\")\n features_128_1 = conv_block(features_64, filters=128, name=\"features_128_1\")\n features_128_2 = conv_block(features_128_1, filters=128, name=\"features_128_2\")\n transformed_features = transformation_block(\n features_128_2, num_features=128, name=\"transformed_features\"\n )\n features_512 = conv_block(transformed_features, filters=512, name=\"features_512\")\n features_2048 = conv_block(features_512, filters=2048, name=\"pre_maxpool_block\")\n global_features = layers.MaxPool1D(pool_size=num_points, name=\"global_features\")(\n features_2048\n )\n global_features = tf.tile(global_features, [1, num_points, 1])\n\n # Segmentation head.\n segmentation_input = layers.Concatenate(name=\"segmentation_input\")(\n [\n features_64,\n features_128_1,\n features_128_2,\n transformed_features,\n features_512,\n global_features,\n ]\n )\n segmentation_features = conv_block(\n segmentation_input, filters=128, name=\"segmentation_features\"\n )\n outputs = layers.Conv1D(\n num_classes, kernel_size=1, activation=\"softmax\", name=\"segmentation_head\"\n )(segmentation_features)\n return keras.Model(input_points, outputs)\n\n\n\ndef run_experiment(epochs, train_dataset, val_dataset, lr_schedule, num_points, num_classes):\n\n segmentation_model = get_shape_segmentation_model(num_points, num_classes)\n segmentation_model.compile(\n optimizer=keras.optimizers.Adam(learning_rate=lr_schedule),\n loss=keras.losses.CategoricalCrossentropy(),\n metrics=[\"accuracy\"],\n )\n\n checkpoint_filepath = \"/tmp/checkpoint\"\n checkpoint_callback = keras.callbacks.ModelCheckpoint(\n checkpoint_filepath,\n monitor=\"val_loss\",\n save_best_only=True,\n save_weights_only=True,\n )\n\n history = segmentation_model.fit(\n train_dataset,\n validation_data=val_dataset,\n epochs=epochs,\n callbacks=[checkpoint_callback],\n )\n\n segmentation_model.load_weights(checkpoint_filepath)\n return segmentation_model, history\n\n\ndef plot_result(item):\n plt.plot(history.history[item], label=item)\n plt.plot(history.history[\"val_\" + item], label=\"val_\" + item)\n plt.xlabel(\"Epochs\")\n plt.ylabel(item)\n plt.title(\"Train and Validation {} Over Epochs\".format(item), fontsize=14)\n plt.legend()\n plt.grid()\n plt.show()\n\n\ndef visualize_single_point_cloud(point_clouds, label_clouds, idx, LABELS):\n label_map = LABELS + [\"none\"]\n point_cloud = point_clouds[idx]\n label_cloud = label_clouds[idx]\n visualize_data(point_cloud, [label_map[np.argmax(label)] for label in label_cloud], LABELS)\n\n\n","repo_name":"mlozanoUV/PointNet","sub_path":"pnet_aux.py","file_name":"pnet_aux.py","file_ext":"py","file_size_in_byte":14642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"12561259755","text":"import os.path\nfrom dataclasses import dataclass\n\n\n@dataclass(frozen=True)\nclass ReportInfo:\n type: str\n serial_number: int\n\n\n@dataclass(frozen=True)\nclass Report:\n student_id: str\n report_info: ReportInfo\n\n\ndef classify_by_file_name(file_name, config):\n def extract_type(file_name):\n mapping = config.rules\n keys = mapping.keys()\n hit = None\n for k in keys:\n for v in mapping[k]:\n if v in file_name:\n if hit is not None:\n return None\n hit = k\n break\n return hit\n\n def extract_serial_number(file_name):\n mapping = {'1': 1, '一': 1, '壹': 1,\n '2': 2, '二': 2, '贰': 2, '貳': 2,\n '3': 3, '三': 3, '叁': 3, '參': 3,\n '4': 4, '四': 4, '肆': 4,\n '5': 5, '五': 5, '伍': 5,\n '6': 6, '六': 6, '陆': 6, '陸': 6,\n '7': 7, '七': 7, '柒': 7,\n '8': 8, '八': 8, '捌': 8,\n '9': 9, '九': 9, '玖': 9}\n ordinals = [ch for ch in file_name if ch in mapping.keys()]\n if len(ordinals) != 1:\n return None\n return mapping[ordinals[0]]\n\n type = extract_type(file_name)\n serial_number = extract_serial_number(file_name)\n\n if type is None or serial_number is None:\n return None\n return ReportInfo(type=type, serial_number=serial_number)\n\n\ndef is_sender_student(attachment, config):\n return attachment.sender in config.students.keys()\n\n\ndef place_of_belonging(attachment, config):\n report_info = classify_by_file_name(attachment.tmp_file.raw_name, config)\n base_dir = config.paths['reports_dir']\n\n def is_report_valid():\n return report_info is not None \\\n and attachment.sender not in config.exceptions[report_info.type] \\\n and report_info.serial_number <= config.latest_nums[report_info.type]\n\n def directory_name():\n name_mapping = config.names\n # number_mapping = {1: '一', 2: '二', 3: '三', 4: '四', 5: '五',\n # 6: '六', 7: '七', 8: '八', 9: '九'}\n return '{}#{}'.format(name_mapping[report_info.type],\n report_info.serial_number)\n\n def file_name():\n address_mapping = config.students\n student = address_mapping[attachment.sender]\n suffix = os.path.splitext(attachment.tmp_file.raw_name)[1]\n return student.id + student.name + suffix\n\n if not is_report_valid():\n return None, None\n \n report = Report(student_id=config.students[attachment.sender].id,\n report_info=report_info)\n return report, os.path.join(base_dir, directory_name(), file_name())\n","repo_name":"duinomaker/LearningStuff","sub_path":"Other/imap_fetch_reports/reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":2807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"37384985860","text":"from PyQt4 import uic\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtNetwork import *\nfrom util import grayscale_pixmap\n\nfrom chatwidget import ChatWidget\n\n\nclass ChatWindow(QObject):\n def __init__(self, app, cybuddy):\n super().__init__()\n self.widget = uic.loadUi('ui/chatwindow.ui')\n self.app = app\n self.chatwidgets = []\n\n self.widget.setWindowTitle('{0} - Cyuf'.format(cybuddy.display_name))\n self.widget.setWindowIcon(QIcon(cybuddy.avatar.image))\n self.widget.setAttribute(Qt.WA_DeleteOnClose, True)\n self.widget.tabWidget.tabCloseRequested.connect(self.close_tab)\n self.widget.tabWidget.currentChanged.connect(self.change_tab)\n self.widget.viewWebcamMenu.triggered.connect(self.view_webcam)\n\n self.current_buddy = cybuddy\n self.new_chat(cybuddy)\n\n def _setup_tab(self, chat):\n i = self.widget.tabWidget.indexOf(chat.widget)\n self.widget.tabWidget.setTabText(i, chat.cybuddy.display_name)\n if chat.cybuddy.status.online:\n self.widget.tabWidget.setTabIcon(i, QIcon(chat.cybuddy.avatar.scaled(16)))\n else:\n self.widget.tabWidget.setTabIcon(\n i, QIcon(grayscale_pixmap(chat.cybuddy.avatar.scaled(16)))\n )\n\n def _update_tab(self):\n for chat in self.chatwidgets:\n if self.sender() == chat.cybuddy:\n self._setup_tab(chat)\n self.change_tab(self.widget.tabWidget.indexOf(chat.widget))\n return\n\n # cannot find buddy, seems that his tab was closed?\n self.sender().update_all.disconnect(self._update_tab)\n\n def new_chat(self, cybuddy):\n for chat in self.chatwidgets:\n if chat.cybuddy.yahoo_id == cybuddy.yahoo_id:\n self.widget.tabWidget.setCurrentIndex(self.chatwidgets.index(chat))\n chat.widget.textEdit.setFocus(Qt.ActiveWindowFocusReason)\n self.widget.activateWindow()\n return\n\n chat = ChatWidget(self, cybuddy)\n self.chatwidgets.append(chat)\n self.widget.tabWidget.addTab(chat.widget, '')\n self.widget.show()\n self.widget.tabWidget.setCurrentIndex(self.chatwidgets.index(chat))\n chat.widget.textEdit.setFocus(Qt.ActiveWindowFocusReason)\n self.widget.activateWindow()\n cybuddy.update_all.connect(self._update_tab)\n self._setup_tab(chat)\n\n def get_current_chat(self):\n return self.chatwidgets[self.widget.tabWidget.currentIndex()]\n\n def change_tab(self, index):\n if index < len(self.chatwidgets):\n selected = self.chatwidgets[index]\n self.widget.setWindowTitle('{0} - Cyuf'.format(selected.cybuddy.display_name))\n self.widget.setWindowIcon(QIcon(selected.cybuddy.avatar.image))\n self.current_buddy = selected.cybuddy\n\n def close_tab(self, index):\n chat = None\n for _chat in self.chatwidgets:\n if self.widget.tabWidget.widget(index) == _chat.widget:\n chat = _chat\n chat.close()\n self.chatwidgets.remove(chat)\n self.widget.tabWidget.removeTab(index)\n\n if not len(self.chatwidgets):\n self.widget.close()\n\n def close_all_tabs(self):\n index = 0\n for chat in self.chatwidgets:\n self.close_tab(index)\n index += 1\n\n def focus_chat(self, cybuddy):\n for chat in self.chatwidgets:\n if chat.cybuddy.yahoo_id == cybuddy.yahoo_id:\n self.widget.tabWidget.setCurrentIndex(self.chatwidgets.index(chat))\n\n def view_webcam(self):\n self.get_current_chat().view_webcam()\n","repo_name":"ov1d1u/cyuf","sub_path":"chatwindow.py","file_name":"chatwindow.py","file_ext":"py","file_size_in_byte":3686,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"40006060070","text":"import tkinter as tk\n\n# Created classes for each drop down menu with each option and their value in a dictionary\nclass Book: \n def __init__(self,books): \n self.book_s ={'STEM Textbook': 6,'Small Novel':0.75, 'Large Novel':2, 'Notebook':1, 'Books':0, 'None':0}\n self.books=books\n def gettype_of_book(self):\n return self.book_s[self.books]\n \nclass Laptop:\n def __init__(self,model):\n self.model_w={'Computer':0, 'Macbook Pro':3.02,'None':0, 'Dell Inspiron':5.11, 'Lenovo': 4.2, 'Asus':1.87 ,'Acer': 7.5 ,'Microsoft Pro':1.69 ,'Toshiba Radius':4.96, 'Samsung':1.8}\n self.model=model\n def getWeight(self):\n return self.model_w[self.model]\n\nclass Miscellaneous:\n def __init__(self, weight):\n self.weight_m ={'Miscellaneous':0, 'Small':1, 'None':0, 'Medium':1.5,'Large':2}\n self.weight = weight\n def getweight_m(self):\n return self.weight_m[self.weight]\n\n# Created a class for the tkinter window and how it's arranged\nclass program:\n def __init__(self):\n self.book = ' '\n self.laptop = ' '\n self.misc = ' '\n self.bagWeight = 0\n self.userWeight = 0\n self.calculation = ' '\n self.boxcolor = 'white'\n \n self.window= tk.Tk()\n self.window.title(\"Computer Back Reliever\")\n self.window.configure(bg=\"Ivory\")\n self.Width = 500\n self.Height = 300\n self.myCanvas = tk.Canvas(self.window,width = self.Width, height = self.Height, bg=\"MintCream\")\n\n #Set drop down menu default value to the category name\n self.v1 = tk.StringVar(self.window)\n self.v1.set(\"Books\") # default value\n \n self.v2 = tk.StringVar(self.window)\n self.v2.set(\"Computer\") # default value\n\n self.v3 = tk.StringVar(self.window)\n self.v3.set(\"Miscellaneous\") # default value\n\n #Created TK Canvases to allow for easy rearranging of sections of the window, and to allow for multiple lables and entrys next to each other\n \n #This Canvas is the small space we see between the first drop down menu and the top of the window\n self.S = tk.Canvas(self.window)\n self.S.pack()\n self.space1 = tk.Label(self.S, text=\" \", bg=\"Ivory\")\n self.space1.pack()\n\n #Create Canvas for instruction 1\n self.i1 = tk.Canvas(self.window)\n self.i1.pack()\n self.instruct1 = tk.Label(self.i1, text=\"Please input your weight, in pounds, as a whole number\", font=(\"Courier\", 16))\n self.instruct1.pack(side=tk.LEFT)\n\n #Canvas for the User's weight Entry\n self.E = tk.Canvas(self.window)\n self.E.pack()\n\n self.we1 = tk.Label(self.E, text=\"User Weight: \", font=(\"Courier\", 15))\n self.we1.pack(side=tk.LEFT)\n\n self.S2 = tk.Canvas(self.window)\n self.S2.pack()\n self.space2 = tk.Label(self.S2, text=\" \", bg=\"Ivory\")\n self.space2.pack()\n\n self.i2 = tk.Canvas(self.window)\n self.i2.pack()\n self.instruct2 = tk.Label(self.i2, text=\"Select the amount of books in your bag or an equal amount of book weight.\", font=(\"Courier\", 16))\n self.instruct2.pack(side=tk.LEFT)\n \n self.i3 = tk.Canvas(self.window)\n self.i3.pack()\n self.instruct3 = tk.Label(self.i3, text=\"A STEM textbook is 6 pounds, a Small Novel is 0.75, a Large Novel is 2, and a Notebook is 1.\", font=(\"Courier\", 15))\n self.instruct3.pack(side=tk.LEFT)\n \n #Use StringVar throughout the code so the label is dynamic depending on the calculations\n self.we2var = tk.StringVar()\n self.we2var.set(\"0\")\n self.we2 = tk.Entry(self.E, textvariable=self.we2var, width=3)\n self.we2.pack(side=tk.LEFT)\n\n #Canvases for each drop down menu, labels and entry multipliers\n self.A1 = tk.Canvas(self.window)\n self.S3 = tk.Canvas(self.window)\n self.i5 = tk.Canvas(self.window)\n self.A2 = tk.Canvas(self.window)\n self.S4 = tk.Canvas(self.window)\n self.i4 = tk.Canvas(self.window)\n self.i6 = tk.Canvas(self.window)\n self.A3 = tk.Canvas(self.window)\n self.S5 = tk.Canvas(self.window)\n\n self.A1.pack()\n self.S3.pack()\n self.i5.pack()\n self.A2.pack()\n self.S4.pack()\n self.i4.pack()\n self.i6.pack()\n self.A3.pack()\n self.S5.pack()\n\n self.entry1var = tk.StringVar()\n self.entry2var = tk.StringVar()\n self.entry3var = tk.StringVar()\n\n #Default multiplier to 1\n self.entry1var.set(\"1\")\n self.entry2var.set(\"1\")\n self.entry3var.set(\"1\")\n \n #Made sure to add each multiplier to their respective Canvas\n self.entry1 = tk.Entry(self.A1, width=3, textvariable=self.entry1var)\n self.space3 = tk.Label(self.S3, text=\" \", bg=\"Ivory\")\n self.instruct5 = tk.Label(self.i5, text=\"Select the type of computer in your bag.\", font=(\"Courier\", 16))\n self.entry2 = tk.Entry(self.A2, width=3, textvariable=self.entry2var)\n self.space4 = tk.Label(self.S4, text=\" \", bg=\"Ivory\")\n self.instruct4 = tk.Label(self.i4, text=\"Select the amount of miscellaneous items, or an equal weight.\", font=(\"Courier\", 16))\n self.instruct6 = tk.Label(self.i6, text=\"Small items are 1 pound, Medium are 1.5, and Large are 2.\", font=(\"Courier\", 15))\n self.entry3 = tk.Entry(self.A3, width=3, textvariable=self.entry3var)\n self.space5 = tk.Label(self.S5, text=\" \", bg=\"Ivory\")\n\n #Pack each part of the Canvas to the left so that they appear in order from left to right\n self.entry1.pack(side=tk.LEFT)\n self.space3.pack()\n self.instruct5.pack(side=tk.LEFT)\n self.entry2.pack(side=tk.LEFT)\n self.space4.pack()\n self.instruct4.pack(side=tk.LEFT)\n self.instruct6.pack(side=tk.LEFT)\n self.entry3.pack(side=tk.LEFT)\n self.space5.pack()\n\n self.multsym1 = tk.Label(self.A1, text=\" X \", font=\"Courier\")\n self.multsym2 = tk.Label(self.A2, text=\" X \", font=\"Courier\")\n self.multsym3 = tk.Label(self.A3, text=\" X \", font=\"Courier\")\n\n self.multsym1.pack(side=tk.LEFT)\n self.multsym2.pack(side=tk.LEFT)\n self.multsym3.pack(side=tk.LEFT)\n\n #Add each drop down menu to their respective Canvas\n self.w = tk.OptionMenu(self.A1, self.v1, \"Books\", \"STEM Textbook\", \"Small Novel\", \"Large Novel\", \"Notebook\", \"None\")\n self.w.config(font=(\"Courier\", 15))\n self.ww = tk.OptionMenu(self.A2, self.v2, \"Computer\", \"Macbook Pro\", \"Dell Inspiron\",\"Lenovo\",\"Asus\",\"Acer\",\"Microsoft Pro\",\"Toshiba Radius\",\"Samsung\", \"None\")\n self.ww.config(font=(\"Courier\", 15))\n self.www = tk.OptionMenu(self.A3, self.v3, \"Miscellaneous\", \"Small\", \"Medium\", \"Large\", \"None\")\n self.www.config(font=(\"Courier\", 15))\n\n self.w.pack(side=tk.LEFT)\n self.ww.pack(side=tk.LEFT)\n self.www.pack(side=tk.LEFT)\n\n self.eq1 = tk.Label(self.A1, text=\" = \", font=\"Courier\")\n self.eq2 = tk.Label(self.A2, text=\" = \", font=\"Courier\")\n self.eq3 = tk.Label(self.A3, text=\" = \", font=\"Courier\")\n\n self.eq1.pack(side=tk.LEFT)\n self.eq2.pack(side=tk.LEFT)\n self.eq3.pack(side=tk.LEFT)\n \n #Create another StringVar to make the Total calculation dynamic\n self.totaldis1var = tk.StringVar()\n self.totaldis2var = tk.StringVar()\n self.totaldis3var = tk.StringVar()\n\n self.totaldis1 = tk.Label(self.A1, textvariable=self.totaldis1var)\n self.totaldis2 = tk.Label(self.A2, textvariable=self.totaldis2var)\n self.totaldis3 = tk.Label(self.A3, textvariable=self.totaldis3var)\n\n self.totaldis1.pack(side=tk.LEFT)\n self.totaldis2.pack(side=tk.LEFT)\n self.totaldis3.pack(side=tk.LEFT)\n \n #Create another Canvas for the total compute button and the display of the total bag weight\n self.B = tk.Canvas(self.window)\n self.B.pack()\n\n self.calculateButton = tk.Button(self.B,text = \"Compute\",command = self.bagCalc, width=12, font=(\"Courier\", 22))\n self.calculateButton.pack(side=tk.LEFT)\n\n self.TOTlabel1 = tk.Label(self.B, text=\" Total: \", font=(\"Courier\", 16))\n self.TOTlabel1.pack(side=tk.LEFT)\n\n self.TOTlabel2var = tk.StringVar()\n self.TOTlabel2 = tk.Label(self.B, textvariable=self.TOTlabel2var)\n self.TOTlabel2.pack(side=tk.LEFT)\n\n #Create rectangle with dynamic color background\n self.rectangle = self.myCanvas.create_rectangle(self.Width//2 - 150, self.Height//2 -50, self.Width//2 + 150, self.Height//2 + 50, fill = self.boxcolor,width=1,outline = \"black\")\n self.myCanvas.pack()\n\n #Create a second rectangle to overlay to display text relating to the color\n self.rectangle2var = tk.StringVar()\n self.rectangle2 = tk.Label(self.myCanvas, textvariable=self.rectangle2var, bg=\"DarkSlateGray\", fg=\"white\", font=(\"Courier\", 15))\n self.rectangle2.place(x=(self.Width//2 - 150), y=(self.Height//2 -50))\n self.myCanvas.pack()\n\n #Configure width of drop down menu size\n self.w.configure(width=14)\n self.ww.configure(width=14)\n self.www.configure(width=14)\n\n self.quitButton=tk.Button(self.window,text=\"Quit\", font=(\"Courier\", 20))\n self.quitButton.pack()\n self.quitButton['command'] = self.window.destroy\n\n #Calculate the bag weight in relation to the User's weight\n def bagCalc(self):\n self.book = Book(self.v1.get())\n self.laptop = Laptop(self.v2.get())\n self.misc = Miscellaneous(self.v3.get())\n\n self.mul1 = 1\n self.mul2 = 1\n self.mul3 = 1\n\n #Make the multipliers bug-proof and prevent anything besides an integer from working in the code, allowing the program to still pass\n try: self.mul1 = int(self.entry1var.get())\n except: pass\n try: self.mul2 = int(self.entry2var.get())\n except: pass\n try: self.mul3 = int(self.entry3var.get())\n except: pass\n\n #Calculate the multipliers for each category and edit the labels using StringVar\n self.weight1 = (self.book.gettype_of_book() * self.mul1)\n self.weight2 = (self.laptop.getWeight() * self.mul2)\n self.weight3 = (self.misc.getweight_m() * self.mul3)\n\n self.totaldis1var.set(str(self.weight1))\n self.totaldis2var.set(str(self.weight2))\n self.totaldis3var.set(str(self.weight3))\n\n #Calculate total weight and edit the Total weight label using StringVar\n self.bagWeight = self.weight1 + self.weight2 + self.weight3\n\n self.TOTlabel2var.set(str(self.bagWeight))\n\n #Bug proof the User weight input as well\n try: self.userWeight = int(self.we2var.get())\n except: pass\n self.limit = self.userWeight * 0.2\n\n #Create if statements for the bag weight total color and text\n if self.bagWeight < self.limit/2:\n self.boxcolor = \"MediumSeaGreen\"\n self.rectangle2var.set(\"Good bag weight!\")\n elif self.bagWeight < self.limit:\n self.boxcolor = \"Peru\"\n self.rectangle2var.set(\"A little on the heavier side.\")\n else:\n self.boxcolor = \"IndianRed\"\n self.rectangle2var.set(\"Too heavy!\")\n \n self.myCanvas.itemconfigure(self.rectangle,fill = self.boxcolor) # change color of rectangle\n\n\nprogram = program()\n\nprogram.window.mainloop()\n\n \n","repo_name":"Rat-a-tail/Computer-Back-Reliever-","sub_path":"Computer Back Reliever(3).pyw","file_name":"Computer Back Reliever(3).pyw","file_ext":"pyw","file_size_in_byte":11520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"38261403999","text":"from collections import namedtuple\r\nfrom ctypes import wintypes, byref\r\nimport ctypes\r\nfrom ctypes import WinDLL\r\n\r\nwindll = ctypes.LibraryLoader(WinDLL)\r\nuser32 = windll.user32\r\nkernel32 = windll.kernel32\r\n\r\nGetWindowRect = windll.user32.GetWindowRect\r\nGetClientRect = windll.user32.GetClientRect\r\n\r\n\r\ndef get_window_text(hWnd):\r\n length = windll.user32.GetWindowTextLengthW(hWnd)\r\n buf = ctypes.create_unicode_buffer(length + 1)\r\n windll.user32.GetWindowTextW(hWnd, buf, length + 1)\r\n return buf.value\r\n\r\n\r\nclass RECT(ctypes.Structure):\r\n _fields_ = [\r\n (\"left\", ctypes.c_long),\r\n (\"top\", ctypes.c_long),\r\n (\"right\", ctypes.c_long),\r\n (\"bottom\", ctypes.c_long),\r\n ]\r\n\r\n\r\nWNDENUMPROC = ctypes.WINFUNCTYPE(\r\n wintypes.BOOL,\r\n wintypes.HWND,\r\n wintypes.LPARAM,\r\n)\r\nWindowInfo = namedtuple(\r\n \"WindowInfo\",\r\n \"pid title windowtext hwnd length tid status coords_client dim_client coords_win dim_win class_name path\",\r\n)\r\n\r\n\r\ndef get_window_infos(hwnd=None):\r\n r\"\"\"\r\n This function utilizes the Windows API to retrieve information about windows.\r\n\r\n Args:\r\n hwnd (int or None): The handle of the window for which to retrieve the text, defaults to None (all windows).\r\n\r\n Returns:\r\n namedtuple: A named tuples with - pid title windowtext hwnd length tid status coords_client dim_client coords_win dim_win class_name path\r\n\r\n Note:\r\n This function uses the `GetWindowTextW` function from the `user32` library to retrieve the window text.\r\n It is intended for use on Windows operating systems and relies on the ctypes library to interface with the Windows API.\r\n\r\n Examples:\r\n from ctypes_window_info import get_window_infos\r\n\r\n get_window_infos()\r\n\r\n [[WindowInfo(pid=88, title='Base_PowerMessageWindow', windowtext='', hwnd=197614, length=1, tid=9668, status='invisible', coords_client=(0, 0, 0, 0), dim_client=(0, 0), coords_win=(0, 0, 0, 0), dim_win=(0, 0), class_name='Base_PowerMessageWindow', path='C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe'),\r\n WindowInfo(pid=88, title='Chrome_StatusTrayWindow', windowtext='', hwnd=197592, length=1, tid=9668, status='invisible', coords_client=(0, 0, 0, 0), dim_client=(0, 0), coords_win=(0, 0, 0, 0), dim_win=(0, 0), class_name='Chrome_StatusTrayWindow', path='C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe'),\r\n WindowInfo(pid=88, title='Chrome_SystemMessageWindow', windowtext='', hwnd=197600, length=1, tid=9668, status='invisible', coords_client=(0, 130, 0, 10), dim_client=(130, 10), coords_win=(0, 136, 0, 39), dim_win=(136, 39), class_name='Chrome_SystemMessageWindow', path='C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe'),\r\n WindowInfo(pid=88, title='Chrome_WidgetWin_0', windowtext='', hwnd=197580, length=1, tid=9668, status='invisible', coords_client=(0, 0, 0, 0), dim_client=(0, 0), coords_win=(0, 0, 0, 0), dim_win=(0, 0), class_name='Chrome_WidgetWin_0', path='C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe'),\r\n WindowInfo(pid=88, title='Chrome_WidgetWin_0', windowtext='', hwnd=197606, length=1, tid=9668, status='invisible', coords_client=(0, 1424, 0, 728), dim_client=(1424, 728), coords_win=(182, 1622, 182, 949), dim_win=(1440, 767), class_name='Chrome_WidgetWin_0', path='C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe'),\r\n WindowInfo(pid=88, title='Chrome_WidgetWin_1', windowtext='', hwnd=2492886, length=1, tid=9668, status='invisible', coords_client=(0, 64, 0, 64), dim_client=(64, 64), coords_win=(-1, 63, 1028, 1092), dim_win=(64, 64), class_name='Chrome_WidgetWin_1', path='C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe'),\r\n ....\r\n\r\n get_window_infos(197614)\r\n [WindowInfo(pid=88, title='Base_PowerMessageWindow', windowtext='', hwnd=197614, length=1, tid=9668, status='invisible', coords_client=(0, 0, 0, 0), dim_client=(0, 0), coords_win=(0, 0, 0, 0), dim_win=(0, 0), class_name='Base_PowerMessageWindow', path='C:\\\\Program Files (x86)\\\\Google\\\\Chrome\\\\Application\\\\chrome.exe')]\r\n\r\n \"\"\"\r\n\r\n result = []\r\n\r\n @WNDENUMPROC\r\n def enum_proc(hWnd, lParam):\r\n if hwnd is not None:\r\n if hWnd != hwnd:\r\n return True\r\n status = \"invisible\"\r\n if user32.IsWindowVisible(hWnd):\r\n status = \"visible\"\r\n\r\n pid = wintypes.DWORD()\r\n tid = user32.GetWindowThreadProcessId(hWnd, ctypes.byref(pid))\r\n length = user32.GetWindowTextLengthW(hWnd) + 1\r\n title = ctypes.create_unicode_buffer(length)\r\n user32.GetWindowTextW(hWnd, title, length)\r\n\r\n rect = RECT()\r\n GetClientRect(hWnd, ctypes.byref(rect))\r\n left, right, top, bottom = rect.left, rect.right, rect.top, rect.bottom\r\n w, h = right - left, bottom - top\r\n coords_client = left, right, top, bottom\r\n dim_client = w, h\r\n rect = RECT()\r\n GetWindowRect(hWnd, ctypes.byref(rect))\r\n left, right, top, bottom = rect.left, rect.right, rect.top, rect.bottom\r\n w, h = right - left, bottom - top\r\n coords_win = left, right, top, bottom\r\n dim_win = w, h\r\n\r\n length_ = 257\r\n title = ctypes.create_unicode_buffer(length_)\r\n user32.GetClassNameW(hWnd, title, length_)\r\n classname = title.value\r\n try:\r\n windowtext = get_window_text(hWnd)\r\n except Exception:\r\n windowtext = \"\"\r\n\r\n try:\r\n coa = kernel32.OpenProcess(0x1000, 0, pid.value)\r\n path = (ctypes.c_wchar * 260)()\r\n size = ctypes.c_uint(260)\r\n kernel32.QueryFullProcessImageNameW(coa, 0, path, byref(size))\r\n filepath = path.value\r\n kernel32.CloseHandle(coa)\r\n except Exception as fe:\r\n filepath = \"\"\r\n\r\n result.append(\r\n (\r\n WindowInfo(\r\n pid.value,\r\n title.value,\r\n windowtext,\r\n hWnd,\r\n length,\r\n tid,\r\n status,\r\n coords_client,\r\n dim_client,\r\n coords_win,\r\n dim_win,\r\n classname,\r\n filepath,\r\n )\r\n )\r\n )\r\n return True\r\n\r\n user32.EnumWindows(enum_proc, 0)\r\n return sorted(result)\r\n\r\n\r\n","repo_name":"hansalemaos/ctypes_window_info","sub_path":"__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"13950806069","text":"import string\n\nshift = 0\nwords = [\"was\", \"that\", \"with\", \"this\", \"cipher\", \"hello\", \"and\", \"test\", ] # Common words for the program to look out for \n\ntext = input(\"Enter your cipher: \")\ntext = text.lower()\nprint(\"\\n\")\nfor i in range(26):\n alphabet = string.ascii_lowercase\n shifted = alphabet[shift:] + alphabet[:shift]\n table = str.maketrans(alphabet, shifted)\n encrypted = text.translate(table)\n if any(word in encrypted.lower() for word in words):\n print(shift, \" \", encrypted, \" POSSIBLE ANSWER\")\n shift += 1\n else:\n print(shift, \" \", encrypted)\n shift += 1\n","repo_name":"scriptoverride/caeser-cipher-solver","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"17487575035","text":"import os\n\n\ndef changeNameFile(path):\n for dirLetters in os.listdir(fr'../{path}'):\n i = 1\n for image in os.listdir(fr'../{path}/{dirLetters}'):\n imageEnd = '.png'\n imageName = 'image'+str(i)\n newName = fr'{imageName}{imageEnd}'\n os.renames(fr'../{path}/{dirLetters}/{image}',\n fr'../{path}/{dirLetters}/{newName}')\n i += 1\n\n\ndef changeNameFile1(path, i):\n imageEnd = '.png'\n imageName = 'image' + str(i)\n newName = fr'{imageName}{imageEnd}'\n os.renames(fr'../{path}', fr'../{path}')\n","repo_name":"tamar-gigi/change-profile-in-rav-kav","sub_path":"backend/myProject/model/function/renameFile.py","file_name":"renameFile.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"6787252587","text":"\"\"\" Model_case_static\r\n\r\nThis is the static model for the HSCN case study.\r\n\r\nThis file contains the following components:\r\n- Variable declaration + variables to 0;\r\n- Exact model - operational part;\r\n- Exact model - cost part;\r\n- Exact model - linear CO2 part;\r\n- Exact model - nonlinear CI part;\r\n- Calculate carbon intensity post-optimization.\r\n\r\nThesis OR&QL - EUR 2022\r\n@author: Erik van der Heide\r\n\r\n\"\"\"\r\n\r\n\"\"\" Import packages & data \"\"\"\r\nimport gurobipy as gp\r\nfrom gurobipy import GRB\r\nimport time\r\nimport math\r\nfrom itertools import product\r\n\r\n# Import the data and the parameters\r\nfrom Data_HSCN import *\r\n\r\n############################## Set up model & decision variables ######################################################\r\n\r\n\"\"\" Initiate model \"\"\"\r\nModel = gp.Model()\r\nif optimizeCI:\r\n Model.params.nonConvex = 2\r\nModel.params.timelimit = timeLimit\r\nif not printStatus:\r\n Model.Params.LogToConsole = 0\r\n\r\n\"\"\" Decision variables \"\"\"\r\n\r\n# Demand locally satisfied\r\nDL_ig = Model.addMVar(shape=(len(I), len(G)), lb=0.0)\r\n\r\n# Demand imported\r\nDI_ig = Model.addMVar(shape=(len(I), len(G)), lb=0.0)\r\n\r\n# Amount produced\r\nP_pig = Model.addMVar(shape=(len(P), len(I), len(G)), lb=0.0)\r\n\r\n# Total production\r\nPT_ig = Model.addMVar(shape=(len(I), len(G)), lb=0.0)\r\n\r\n# Flows between grids\r\nQ_ilgg = Model.addMVar(shape=(len(I), len(L), len(G), len(G)), lb=0.0)\r\n\r\n# Cost variables\r\nFC = Model.addVar(lb=0.0)\r\nFCC = Model.addVar(lb=0.0)\r\nFOC = Model.addVar(lb=0.0)\r\nFSC = Model.addVar(lb=0.0)\r\nGC = Model.addVar(lb=0.0)\r\nLC = Model.addVar(lb=0.0)\r\nMC = Model.addVar(lb=0.0)\r\nTCC = Model.addVar(lb=0.0)\r\nTCE = Model.addVar(lb=-10e6)\r\nTCEFeed = Model.addVar(lb=0.0)\r\nTCEProd = Model.addVar(lb=-10e6)\r\nTCETrans = Model.addVar(lb=0.0)\r\nTDC = Model.addVar(lb=0.0)\r\nTOC = Model.addVar(lb=0.0)\r\n\r\n# Number of trips daily (not rounded)\r\nNOT_ilgg = Model.addMVar(shape=(len(I), len(L), len(G), len(G)))\r\n\r\n# Number of plants\r\nNP_pig = Model.addMVar(shape=(len(P), len(I), len(G)), vtype=GRB.INTEGER)\r\n\r\nif overEstimateNTU:\r\n # Number of transport units from grid to grid\r\n NTU_ilgg = Model.addMVar(shape=(len(I), len(L), len(G), len(G)), vtype=GRB.INTEGER)\r\n\r\n# Number of transport units total\r\nNTU_il = Model.addMVar(shape=(len(I), len(L)), vtype=GRB.INTEGER)\r\n\r\n# Binary for some transport\r\nX_ilgg = Model.addMVar(shape=(len(I), len(L), len(G), len(G)), vtype=GRB.BINARY)\r\n\r\n# Binary for export\r\nY_ig = Model.addMVar(shape=(len(I), len(G)), vtype=GRB.BINARY)\r\n\r\n# Binary for import\r\nZ_ig = Model.addMVar(shape=(len(I), len(G)), vtype=GRB.BINARY)\r\n\r\nif optimizeCI:\r\n # Intensity of product i produced at grid g\r\n CIPlants_ig = Model.addMVar(shape=(len(I), len(G)), lb=-10e6)\r\n\r\n # Intensity of product i satisfied at grid g from production\r\n CIProd_ig = Model.addMVar(shape=(len(I), len(G)), lb=-10e6)\r\n\r\n # Intensity of product i satisfied at grid g from transport\r\n CITrans_ig = Model.addMVar(shape=(len(I), len(G)), lb=-10e6)\r\n\r\n # Total intensity of product i at grid g (ton CO2/ton H2)\r\n CI_ig = Model.addMVar(shape=(len(I), len(G)), lb=-10e6)\r\n\r\n # Total intensity at grid g (ton CO2/ton H2)\r\n CI_g = Model.addMVar(shape=(len(G)), lb=-10e6)\r\n\r\n############################## Model objective & constraints ##########################################################\r\n\r\n\"\"\" Set some variables to 0 (ig, il and gg options) \"\"\"\r\n\r\n# (B.15)-1 No local production if no feasible location (ig)\r\nModel.addConstrs(DL_ig[(i, g)] == 0 for i in I for g in G if A_ig[(i, g)] == 0)\r\n\r\n# (B.15)-2 No production by a plant if no feasible location (ig)\r\nModel.addConstrs(P_pig[(p, i, g)] == 0 for p in P for i in I for g in G if A_ig[(i, g)] == 0)\r\n\r\n# (B.15)-3 No total production in a grid plant ino feasible location (ig)\r\nModel.addConstrs(PT_ig[(i, g)] == 0 for i in I for g in G if A_ig[(i, g)] == 0)\r\n\r\n# (B.15)-4 No transport if: product cannot go with the mode of transport (il), product cannot be produced in the grid (ig)\r\nModel.addConstrs(Q_ilgg[(i, l, g, g_prime)] == 0 for i in I for l in L for g in G for g_prime in G if A_il[(i, l)] == 0 or A_ig[(i, g)] == 0)\r\n\r\n# (B.15)-5 No plants can be build on locations where plants are not feasible (ig)\r\nModel.addConstrs(NP_pig[(p, i, g)] == 0 for p in P for i in I for g in G if A_ig[(i, g)] == 0)\r\n\r\n# (B.15)-6 No transport if: product cannot go with the mode of transport (il), product cannot be produced in the grid (ig)\r\nModel.addConstrs(X_ilgg[(i, l, g, g_prime)] == 0 for i in I for l in L for g in G for g_prime in G if A_il[(i, l)] == 0 or A_ig[(i, g)] == 0)\r\n\r\n# (B.15)-7 No export if you cannot produce the product at the location (ig)\r\nModel.addConstrs(Y_ig[(i, g)] == 0 for i in I for l in L for g in G for g_prime in G if A_ig[(i, g)] == 0)\r\n\r\n# (il)-1 No transport units if product-mode combination does not exist (il)\r\nModel.addConstrs(NTU_il[(i, l)] == 0 for i in I for l in L if A_il[(i, l)] == 0)\r\n\r\n# (il)-2 No trips if production-mode combination does not exist (il)\r\nModel.addConstrs(NOT_ilgg[(i, l, g, g_prime)] == 0 for i in I for l in L for g in G for g_prime in G if A_il[(i, l)] == 0)\r\n\r\nif overEstimateNTU:\r\n # EXTRA No transport units if product-mode combination does not exist (il)\r\n Model.addConstrs(NTU_ilgg[(i, l, g, g_prime)] == 0 for i in I for l in L for g in G for g_prime in G if A_il[(i, l)] == 0)\r\n\r\nif optimizeCI:\r\n # (B.50) Only where you can actually build a plant you can have a carbon intensity of the plants in that grid\r\n Model.addConstrs(CIPlants_ig[(i, g)] == 0 for i in I for g in G if A_ig[(i, g)] == 0)\r\n\r\n # (B.51) CI is 0 if there is also no demand\r\n for g in G:\r\n if DT_g[g] == 0:\r\n Model.addConstr(CI_g[g] == 0)\r\n for i in I:\r\n Model.addConstr(CI_ig[(i, g)] == 0)\r\n\r\n\"\"\" Operational part \"\"\"\r\n\r\n# (B.1) Not more demand satisfied locally than totally produced in that grid\r\nModel.addConstrs(DL_ig[(i, g)] <= PT_ig[(i, g)] for i in I for g in G if A_ig[(i, g)] == 1)\r\n\r\n# (B.2) local demand satisfied are the \"diagonals\" on the Q matrix (NEW)\r\nModel.addConstrs(DL_ig[(i, g)] == gp.quicksum(Q_ilgg[(i, l, g, g)] for l in L if A_il[(i, l)] == 1) for i in I for g in G)\r\n\r\n# (B.3) Imported hydrogen (has NO constraint on location)\r\nModel.addConstrs(DI_ig[(i, g)] == gp.quicksum(Q_ilgg[(i, l, g_prime, g)] for l in L for g_prime in G if g_prime != g) for i in I for g in G)\r\n\r\n# (B.4) Total demand satisfied\r\nModel.addConstrs(DT_g[g] == gp.quicksum(DL_ig[(i, g)] + DI_ig[(i, g)] for i in I) for g in G)\r\n\r\n# (B.5) Balance constraints\r\nModel.addConstrs(DL_ig[(i, g)] == PT_ig[(i, g)] - gp.quicksum(Q_ilgg[(i, l, g, g_prime)] for l in L for g_prime in G if g_prime != g) for i in I for g in G)\r\n\r\n# (B.6) Total production\r\nModel.addConstrs(PT_ig[(i, g)] == gp.quicksum(P_pig[(p, i, g)] for p in P) for i in I for g in G if A_ig[(i, g)] == 1)\r\n\r\n# (B.7) Bounding production\r\nModel.addConstrs(P_pig[(p, i, g)] >= PCapMin_pi[(p, i)] * NP_pig[(p, i, g)] for p in P for i in I for g in G if A_ig[(i, g)] == 1)\r\nModel.addConstrs(P_pig[(p, i, g)] <= PCapMax_pi[(p, i)] * NP_pig[(p, i, g)] for p in P for i in I for g in G if A_ig[(i, g)] == 1)\r\n\r\n# (B.8) Bounding total production\r\nModel.addConstrs(PT_ig[(i, g)] >= gp.quicksum(PCapMin_pi[(p, i)] * NP_pig[(p, i, g)] for p in P) for i in I for g in G if A_ig[(i, g)] == 1)\r\nModel.addConstrs(PT_ig[(i, g)] <= gp.quicksum(PCapMax_pi[(p, i)] * NP_pig[(p, i, g)] for p in P) for i in I for g in G if A_ig[(i, g)] == 1)\r\n\r\n# (B.9) Bounding transportation\r\nModel.addConstrs(Q_ilgg[(i, l, g, g_prime)] >= QMin_il[(i, l)] * X_ilgg[(i, l, g, g_prime)] for i in I for l in L for g in G for g_prime in G\r\n if A_il[(i, l)] == 1 and A_ig[(i, g)] == 1)\r\nModel.addConstrs(Q_ilgg[(i, l, g, g_prime)] <= QMax_il[(i, l)] * X_ilgg[(i, l, g, g_prime)] for i in I for l in L for g in G for g_prime in G\r\n if A_il[(i, l)] == 1 and A_ig[(i, g)] == 1)\r\n\r\n# (B.10) Import or export, not both\r\nModel.addConstrs(X_ilgg[(i, l, g, g_prime)] + X_ilgg[(i, l, g_prime, g)] <= 1 for i in I for l in L for g in G for g_prime in G if g != g_prime)\r\n\r\n# (B.11) Import or export, not both\r\nModel.addConstrs(Y_ig[(i, g)] >= X_ilgg[(i, l, g, g_prime)] for i in I for l in L for g in G for g_prime in G if g != g_prime if A_ig[(i, g)] == 1)\r\n\r\n# (B.12) Import or export, not both\r\nModel.addConstrs(Z_ig[(i, g)] >= X_ilgg[(i, l, g_prime, g)] for i in I for l in L for g_prime in G for g in G if g != g_prime)\r\n\r\n# (B.13) Import or export, not both\r\nModel.addConstrs(Y_ig[(i, g)] + Z_ig[(i, g)] <= 1 for i in I for g in G)\r\n\r\n# (B.14) cannot import both products (though production grids can still have both) (NEW)\r\nif onlyOneImportProduct:\r\n Model.addConstrs(gp.quicksum(Z_ig[(i, g)] for i in I) <= 1 for g in G)\r\n\r\n# (Extra) fix some plants in static case!\r\nif groupByTechnology:\r\n # Group by technology (only for the full size model)\r\n P_SMR = [1, 2, 13, 14] # a bit manually made sure that again a medium plant is build\r\n P_CG = [3, 4, 5, 15, 16, 17]\r\n P_BG = [6, 7, 8, 18, 19, 20]\r\n P_WE = [9, 10, 11, 21, 22, 23]\r\n Model.addConstrs(gp.quicksum(NP_pig[(p, i, g)] for p in P_SMR) >= gp.quicksum(NPFix_pig[(p, i, g)] for p in P_SMR) for i in I for g in G)\r\n Model.addConstrs(gp.quicksum(NP_pig[(p, i, g)] for p in P_CG) >= gp.quicksum(NPFix_pig[(p, i, g)] for p in P_CG) for i in I for g in G)\r\n Model.addConstrs(gp.quicksum(NP_pig[(p, i, g)] for p in P_BG) >= gp.quicksum(NPFix_pig[(p, i, g)] for p in P_BG) for i in I for g in G)\r\n Model.addConstrs(gp.quicksum(NP_pig[(p, i, g)] for p in P_WE) >= gp.quicksum(NPFix_pig[(p, i, g)] for p in P_WE) for i in I for g in G)\r\nelse:\r\n Model.addConstrs(NP_pig[(p, i, g)] >= NPFix_pig[(p, i, g)] for p in P for i in I for g in G) # if NPFix_pig[(p, i, g)] > 0)\r\n\r\n\"\"\" Cost part \"\"\"\r\n\r\n# (B.16) Facility Capital Cost (FCC)\r\nModel.addConstr(FCC == gp.quicksum(PCC_pi[(p, i)] * NP_pig[(p, i, g)] - PCC_pi[(p, i)] * NPFix_pig[(p, i, g)] for p in P for i in I for g in G))\r\n\r\n# (B.17) Define the number of trips (NOT_ilgg)\r\nModel.addConstrs(NOT_ilgg[(i, l, g, g_prime)] == Q_ilgg[(i, l, g, g_prime)] * (1 / TCap_il[(i, l)]) for i in I for l in L for g in G for g_prime in G if A_il[(i, l)] == 1)\r\n\r\n# UNDERestimate NTU: Assume other vehicles can take over work from partly trips. As this is not a VRP, it underestimates the number of units needed\r\nif underEstimateNTU:\r\n # (B.18) Number Transport Units between and withing grids (NTU_il)\r\n Model.addConstrs(NTU_il[(i, l)] >= gp.quicksum(Q_ilgg[(i, l, g, g_prime)] * (1 / TMA_l[l]) * (1 / TCap_il[(i, l)]) * (2 * L_lgg[(l, g, g_prime)] * (1 / SPbetween_l[l]) + LUT_l[l])\r\n for g in G for g_prime in G if g_prime != g)\r\n + gp.quicksum(Q_ilgg[(i, l, g, g)] * (1 / TMA_l[l]) * (1 / TCap_il[(i, l)]) * (2 * L_lgg[(l, g, g)] * (1 / SPwithin_l[l]) + LUT_l[l])\r\n for g in G)\r\n for i in I for l in L if A_il[(i, l)] == 1)\r\n\r\n# OVERestimate NTU: say that for each (g, g') pair, there need to be separate vehicles (Which is in practice not always needed, so over-estimation)\r\nif overEstimateNTU:\r\n # EXTRA-(B.18)-1 Number Transport Units between grids (NTU_ilgg')\r\n Model.addConstrs(NTU_ilgg[(i, l, g, g_prime)] >= Q_ilgg[(i, l, g, g_prime)] * (1 / TMA_l[l]) * (1 / TCap_il[(i, l)]) * (2 * L_lgg[(l, g, g_prime)] * (1 / SPbetween_l[l]) + LUT_l[l])\r\n for g in G for g_prime in G for i in I for l in L if g_prime != g if A_il[(i, l)] == 1)\r\n\r\n # EXTRA-(B.18)-2 Number Transport Units within grids (NTU_ilgg)\r\n Model.addConstrs(NTU_ilgg[(i, l, g, g)] >= Q_ilgg[(i, l, g, g)] * (1 / TMA_l[l]) * (1 / TCap_il[(i, l)]) * (2 * L_lgg[(l, g, g)] * (1 / SPwithin_l[l]) + LUT_l[l])\r\n for i in I for l in L for g in G if A_il[(i, l)] == 1)\r\n\r\n # EXTRA-(B.18)-3 Number Transport Units per product and mode (NTU_il)\r\n Model.addConstrs(NTU_il[(i, l)] == gp.quicksum(NTU_ilgg[(i, l, g, g_prime)] for g in G for g_prime in G) for i in I for l in L if A_il[(i, l)] == 1)\r\n\r\n# (B.19) Transportation Capital Cost (TCC)\r\nModel.addConstr(TCC == gp.quicksum(TMC_il[(i, l)] * NTU_il[(i, l)] for i in I for l in L))\r\n\r\n# (B.20) Facility Operating Cost (FOC)\r\nif includeCCS:\r\n Model.addConstr(FOC == gp.quicksum((UPC_pi[(p, i)] + A_CCS_p[p] * CCSCost * CO2Prod_pi[(p, i)]) * P_pig[(p, i, g)] for p in P for i in I for g in G))\r\nelse:\r\n Model.addConstr(FOC == gp.quicksum(UPC_pi[(p, i)] * P_pig[(p, i, g)] for p in P for i in I for g in G))\r\n\r\n# (B.21) Fuel Cost (FC)\r\nModel.addConstr(FC == gp.quicksum(FP_l[l] * (2 * L_lgg[(l, g, g_prime)] * Q_ilgg[(i, l, g, g_prime)] * (1 / FEbetween_l[l]) * (1 / TCap_il[(i, l)]))\r\n for i in I for l in L for g in G for g_prime in G if A_il[(i, l)] == 1 if g_prime != g)\r\n + gp.quicksum(FP_l[l] * (2 * L_lgg[(l, g, g)] * Q_ilgg[(i, l, g, g)] * (1 / FEwithin_l[l]) * (1 / TCap_il[(i, l)]))\r\n for i in I for l in L for g in G if A_il[(i, l)] == 1))\r\n\r\n# (B.22) Labour Cost (LC)\r\nModel.addConstr(LC == gp.quicksum(DW_l[l] * (Q_ilgg[(i, l, g, g_prime)] * (1 / TCap_il[(i, l)]) * (2 * L_lgg[(l, g, g_prime)] * (1 / SPbetween_l[l]) + LUT_l[l]))\r\n for i in I for l in L for g in G for g_prime in G if A_il[(i, l)] == 1 if g_prime != g)\r\n + gp.quicksum(DW_l[l] * (Q_ilgg[(i, l, g, g)] * (1 / TCap_il[(i, l)]) * (2 * L_lgg[(l, g, g)] * (1 / SPwithin_l[l]) + LUT_l[l]))\r\n for i in I for l in L for g in G if A_il[(i, l)] == 1))\r\n\r\n# (B.23) Maintenance Cost (MC)\r\nModel.addConstr(MC == gp.quicksum(ME_l[l] * (2 * L_lgg[(l, g, g_prime)] * Q_ilgg[(i, l, g, g_prime)] * (1 / TCap_il[(i, l)]))\r\n for i in I for l in L for g in G for g_prime in G if A_il[(i, l)] == 1))\r\n\r\n# (B.24) General Cost (GC)\r\nModel.addConstr(GC == gp.quicksum(GE_l[l] * NTU_il[(i, l)] for i in I for l in L))\r\n\r\n# (B.25) - NEW - FeedStock Cost (FSC)\r\nModel.addConstr(FSC == gp.quicksum(FSP_p[p] * PCR_p[p] * gp.quicksum(P_pig[(p, i, g)] for i in I for g in G) for p in P))\r\n\r\n# (B.26) Transportation Operating Cost (TOC)\r\nModel.addConstr(TOC == FC + LC + MC + GC)\r\n\r\n# (B.27) Total Daily Cost (TDC)\r\nModel.addConstr(TDC == (1 / (alpha * CCF)) * (FCC + TCC) + FOC + TOC + FSC)\r\n\r\n# (B.28) Minimize TDC or TCE, or both\r\nobjective = costImportance * TDC + CO2Importance * TCE\r\n\r\n\"\"\" CO2 part \"\"\"\r\n\r\n# (B.29) Total feed emissions\r\nModel.addConstr(TCEFeed == gp.quicksum(CO2Feed_p[p] * (gp.quicksum(P_pig[(p, i, g)] for g in G for i in I)) for p in P))\r\n\r\n# (B.30) Total production emissions\r\nif newEmissionData:\r\n Model.addConstr(TCEProd == gp.quicksum(CO2Prod_pi[(p, i)] * (gp.quicksum(P_pig[(p, i, g)] for g in G)) for p in P for i in I))\r\nelse:\r\n if includeCCS:\r\n Model.addConstr(TCEProd == gp.quicksum(((1 - A_CCS_p[p]) * CO2Prod_pi[(p, i)] + A_CCS_p[p] * (1 - CCSEF) * CO2Prod_pi[(p, i)]) * P_pig[(p, i, g)] for p in P for i in I for g in G))\r\n else:\r\n Model.addConstr(TCEProd == gp.quicksum(CO2Prod_pi[(p, i)] * (gp.quicksum(P_pig[(p, i, g)] for g in G)) for p in P for i in I))\r\n\r\n# (B.31) Total transportation emissions\r\nif underEstimateNTU:\r\n Model.addConstr(TCETrans == CO2Trans * gp.quicksum(NOT_ilgg[(i, l, g, g_prime)] * 2 * L_lgg[(l, g, g_prime)] for i in I for l in L for g in G for g_prime in G))\r\nif overEstimateNTU:\r\n Model.addConstr(TCETrans == CO2Trans * gp.quicksum(NTU_ilgg[(i, l, g, g_prime)] * 2 * L_lgg[(l, g, g_prime)] for i in I for l in L for g in G for g_prime in G))\r\n# Model.addConstr(TCETrans == gp.quicksum(CO2Trans * (gp.quicksum(NTU_ilgg[(i, l, g, g_prime)] * 2 * L_lgg[(l, g, g_prime)] for i in I for l in L)) for g in G for g_prime in G))\r\n\r\n# (B.32) Total chain emissions\r\nModel.addConstr(TCE == TCEFeed + TCEProd + TCETrans)\r\n\r\n# (B.33) Linear constraint on total chain emissions\r\nif TotalCO2Max != -1:\r\n Model.addConstr(TCE <= TotalCO2Max)\r\n\r\n##################### Restrict Carbon intensities DURING-optimization ###########################################\r\n\r\n# (B.42)-(B.49) Include CI during-optimization\r\nif optimizeCI:\r\n\r\n # (B.42) Calculate the starting carbon intensity as parameter per plant p per product i\r\n pass # already in data\r\n\r\n # (B.43) CI^{Plants}_{ig}\r\n Model.addConstrs(CIPlants_ig[(i, g)] * PT_ig[(i, g)] == gp.quicksum(P_pig[(p, i, g)] * CIStart_pi[(p, i)] for p in P) for i in I for g in G)\r\n\r\n # (B.44) CI^{Prod}_{ig}\r\n Model.addConstrs(CIProd_ig[(i, g)] * gp.quicksum(Q_ilgg[(i, l_star, g_prime_star, g)] for l_star in L for g_prime_star in G)\r\n == gp.quicksum(Q_ilgg[(i, l, g_prime, g)] * CIPlants_ig[(i, g_prime)] for l in L for g_prime in G) for i in I for g in G)\r\n\r\n # (B.45) CI^{Trans}_{ig}\r\n Model.addConstrs(CITrans_ig[(i, g)] * (DL_ig[(i, g)] + DI_ig[(i, g)])\r\n == CO2Trans * gp.quicksum(NOT_ilgg[(i, l, g_prime, g)] * 2 * L_lgg[(l, g_prime, g)] for l in L for g_prime in G) for i in I for g in G)\r\n\r\n # (B.46) CI_{ig}\r\n Model.addConstrs(CI_ig[(i, g)] == CIProd_ig[(i, g)] + CITrans_ig[(i, g)] for i in I for g in G)\r\n\r\n # (B.47) CI_{g}\r\n Model.addConstrs(CI_g[g] == gp.quicksum(CI_ig[(i, g)] * (DL_ig[(i, g)] + DI_ig[(i, g)]) * (1 / DT_g[g]) for i in I) for g in G if DT_g[g] > 0)\r\n\r\n # (B.48) CI_{ig} restrictions\r\n for i in I:\r\n for g in G:\r\n if maxCIStatic[(i, g)] != -1:\r\n Model.addConstr(CI_ig[(i, g)] <= maxCIStatic[(i, g)])\r\n\r\n # (B.49) CI_{g} restrictions\r\n for g in G:\r\n if maxCIStatic[(len(I), g)] != -1:\r\n Model.addConstr(CI_g[g] <= maxCIStatic[(len(I), g)])\r\n\r\n############################## Execute ########################################################################\r\n\r\n\"\"\" Execute the model as specified in Params. \"\"\"\r\nstart_time = time.time()\r\nModel.setObjective(objective, GRB.MINIMIZE)\r\nModel.optimize()\r\nend_time = time.time()\r\ntotal_time = end_time - start_time\r\n\r\n####################### Calculate Carbon intensities POST-optimization ##########################################\r\n\r\n\"\"\" Options: \"\"\"\r\n# Carbon_ig_post : total daily CO2 emissions for product i in grid g (per day)\r\n# Carbon_g_post : total daily CO2 emissions for grid g (per day)\r\n# CI_ig_post : carbon intensity of product i in grid g (at a day)\r\n# CI_g_post : avg. carbon intensity of utilized products in grid g\r\n\r\n# (B.34) Calculate the starting carbon intensity as parameter per plant p per product i\r\npass # already in data\r\n\r\n# (B.35) Calculate the carbon intensities of the all the plants producing product i in plant g\r\n# Note that the simplifying assumption here is that what is produced totally in a grid is distributed equally over the other grids.\r\n# ..in other words, if you have one CG plant in a grid and one SMR plant in the same grid, you average the emissions of those grids for the\r\n# ..outgoing products, while in fact you could connect some cities with the CG plant and some cities with the SMR plant\r\n# ..BUT this only holds for the same product i! Depends whether you take g, (i, g) or (p, i, g)\r\nCIPlants_ig_post = np.zeros(shape=(len(I), len(G)))\r\nfor i in I:\r\n for g in G:\r\n if PT_ig[(i, g)].X > 0.0000001:\r\n CIPlants_ig_post[(i, g)] = gp.quicksum(P_pig[(p, i, g)] / PT_ig[(i, g)].X * CIStart_pi[(p, i)] for p in P).getValue()\r\n\r\n# (B.36) Carbon intensities from production units for product i at customer location g\r\nCIProd_ig_post = np.zeros(shape=(len(I), len(G)))\r\nCIProd_denominator_ig = np.zeros(shape=(len(I), len(G)))\r\nfor i in I:\r\n for g in G:\r\n CIProd_denominator_ig[(i, g)] = gp.quicksum(Q_ilgg[(i, l_star, g_prime_star, g)] for l_star in L for g_prime_star in G).getValue()\r\nfor i in I:\r\n for g in G:\r\n if CIProd_denominator_ig[(i, g)] > 0.0000001:\r\n CIProd_ig_post[(i, g)] = gp.quicksum(Q_ilgg[(i, l, g_prime, g)] / CIProd_denominator_ig[(i, g)] * CIPlants_ig_post[(i, g_prime)] for l in L for g_prime in G).getValue()\r\n\r\n# (B.37) Carbon intensity from transportation TODO\r\nCITrans_ig_post = np.zeros(shape=(len(I), len(G)))\r\nfor i in I:\r\n for g in G:\r\n if (DL_ig[(i, g)].X + DI_ig[(i, g)].X) > 0.0000001:\r\n CITrans_ig_post[(i, g)] = ((CO2Trans * gp.quicksum(NOT_ilgg[(i, l, g_prime, g)] * 2 * L_lgg[(l, g_prime, g)] for l in L for g_prime in G)) / (DL_ig[(i, g)].X + DI_ig[(i, g)].X)).getValue()\r\n\r\n# (B.38) Total carbon intensity is part from production and part from transportation\r\nCI_ig_post = np.zeros(shape=(len(I), len(G)))\r\nfor i in I:\r\n for g in G:\r\n CI_ig_post[(i, g)] = CIProd_ig_post[(i, g)] + CITrans_ig_post[(i, g)]\r\n\r\n# (B.39) Carbon intensity at a location is the resource-weighted average of both products\r\nCI_g_post = np.zeros(shape=len(G))\r\nfor g in G:\r\n if DT_g[g] > 0:\r\n CI_g_post[g] = gp.quicksum(CI_ig_post[(i, g)] * (DL_ig[(i, g)] + DI_ig[(i, g)]) / DT_g[g] for i in I).getValue()\r\n\r\n# (B.40) Total carbon emissions for which grid g is responsible, per product\r\nCarbon_ig_post = np.zeros(shape=(len(I), len(G)))\r\nfor i in I:\r\n for g in G:\r\n Carbon_ig_post[(i, g)] = CI_ig_post[(i, g)] * (DL_ig[(i, g)].X + DI_ig[(i, g)].X)\r\n\r\n# (B.41) Total carbon emissions for which grid g is responsible, all products combined\r\nCarbon_g_post = np.zeros(shape=(len(G)))\r\nfor g in G:\r\n Carbon_g_post[g] = CI_g_post[g] * DT_g[g]\r\n\r\n\r\n############################## Print the results #########################################################\r\n\r\ndef deleteZeroMatrix(mat):\r\n # Checks if a data matrix only has 0 elements\r\n for elem in np.nditer(mat):\r\n if elem > 0.0001:\r\n return False\r\n return True\r\n\r\n\r\ndef deleteZeroElements(mat):\r\n mat2 = np.copy(mat).astype('object')\r\n # Remove the elements which are 0.0\r\n if len(mat.shape) == 1:\r\n pass\r\n numElem = mat2.shape[0]\r\n for i in range(numElem):\r\n if -0.0001 < mat2[i] < 0.0001:\r\n mat2[i] = '-'\r\n else:\r\n numRows = mat2.shape[0]\r\n numCols = mat2.shape[1]\r\n for i in range(numRows):\r\n for j in range(numCols):\r\n if -0.0001 < mat2[(i, j)] < 0.0001:\r\n mat2[(i, j)] = '-'\r\n return mat2\r\n\r\n\r\nif printVariables:\r\n print()\r\n print(\"===== VARIABLES =====\")\r\n print(\"Num. variables : \", Model.numVars) # (including those that are by definition 0)\r\n print(\"Num. constraints : \", Model.numConstrs) # (including those that make variables 0 and redundant constraints for 0 variables)\r\n print()\r\n\r\n print(\"=== OPERATIONAL VARIABLES ===\")\r\n print()\r\n\r\n # Continuous variables\r\n matrix = DL_ig.X.round(2)\r\n if not deleteZeroMatrix(matrix): # if it is a zero matrix\r\n test = pd.DataFrame(deleteZeroElements(DL_ig.X.round(2)), index=ISet, columns=GSet).to_string()\r\n print(\"D^L_ig (local demand satisfied): \\n\", test)\r\n print()\r\n\r\n matrix = DI_ig.X.round(2)\r\n if not deleteZeroMatrix(matrix):\r\n print(\"D^I_ig (imported demand satisfied): \\n\", pd.DataFrame(deleteZeroElements(DI_ig.X.round(2)), index=ISet, columns=GSet).to_string())\r\n print()\r\n\r\n for p in P:\r\n matrix = P_pig[p, :, :].X.round(2)\r\n if not deleteZeroMatrix(matrix):\r\n print(f\"P_[{PSet[p]}]ig (production from plant p={PSet[p]}): \\n {pd.DataFrame(deleteZeroElements(P_pig[p, :, :].X.round(2)), index=ISet, columns=GSet).to_string()}\")\r\n print()\r\n\r\n matrix = PT_ig.X.round(2)\r\n if not deleteZeroMatrix(matrix):\r\n print(\"P^T_ig (total production): \\n\", pd.DataFrame(deleteZeroElements(PT_ig.X.round(2)), index=ISet, columns=GSet).to_string())\r\n print()\r\n\r\n for i in I:\r\n for l in L:\r\n if A_il[(i, l)] == 1:\r\n matrix = Q_ilgg[i, l, :, :].X.round(2)\r\n if not deleteZeroMatrix(matrix):\r\n print(f\"Q_[{ISet[i]}][{LSet[l]}]gg' (transport product {ISet[i]} using mode {LSet[l]}): \"\r\n f\"\\n {pd.DataFrame(deleteZeroElements(Q_ilgg[i, l, :, :].X.round(2)), index=GSet, columns=GSet).to_string()}\")\r\n print()\r\n\r\n # Total feedstock needed (ambiguous):\r\n FeedNeeded_p_large = np.zeros(shape=len(P))\r\n for p in P:\r\n FeedNeeded_p_large[p] = (PCR_p[p] * gp.quicksum(P_pig[(p, i, g)] for i in I for g in G)).getValue()\r\n print(\"FeedNeeded_p \\n\", pd.DataFrame(deleteZeroElements(FeedNeeded_p_large), index=PSet, columns=[\"Amount of feed\"]).to_string())\r\n print()\r\n\r\n # Integer variables\r\n for p in P:\r\n matrix = NP_pig[p, :, :].X.round(2)\r\n if not deleteZeroMatrix(matrix):\r\n print(f\"NP_[{PSet[p]}]ig (number of plant {PSet[p]}): \\n {pd.DataFrame(deleteZeroElements(NP_pig[p, :, :].X.round(2)), index=ISet, columns=GSet).to_string()}\")\r\n print()\r\n\r\n for i in I:\r\n for l in L:\r\n if A_il[(i, l)] == 1:\r\n matrix = NOT_ilgg[i, l, :, :].X.round(2)\r\n if not deleteZeroMatrix(matrix):\r\n print(f\"NOT_[{ISet[i]}][{LSet[l]}]gg (#units transport product i={ISet[i]} using mode l={LSet[l]}): \\n\"\r\n f\" {pd.DataFrame(deleteZeroElements(NOT_ilgg[i, l, :, :].X.round(2)), index=GSet, columns=GSet).to_string()}\")\r\n print()\r\n\r\n if overEstimateNTU:\r\n for i in I:\r\n for l in L:\r\n if A_il[(i, l)] == 1:\r\n matrix = NTU_ilgg[i, l, :, :].X.round(2)\r\n if not deleteZeroMatrix(matrix):\r\n print(f\"NTU_[{ISet[i]}][{LSet[l]}]gg (#units transport product i={ISet[i]} using mode l={LSet[l]}): \\n\"\r\n f\" {pd.DataFrame(deleteZeroElements(NTU_ilgg[i, l, :, :].X.round(2)), index=GSet, columns=GSet).to_string()}\")\r\n print()\r\n\r\n print(\"TOTAL NTU_il (number of units): \\n\", pd.DataFrame(deleteZeroElements(NTU_il.X.round(2)), index=ISet, columns=LSet).to_string())\r\n print()\r\n\r\n # Binary variables\r\n if printBinaryVariables:\r\n for i in I:\r\n for l in L:\r\n if A_il[(i, l)] == 1:\r\n matrix = X_ilgg[i, l, :, :].X\r\n if not deleteZeroMatrix(matrix):\r\n print(f\"X_[{ISet[i]}][{LSet[l]}]gg' (binary for transport product {ISet[i]} using mode {LSet[l]}): \"\r\n f\"\\n {pd.DataFrame(deleteZeroElements(X_ilgg[i, l, :, :].X), index=GSet, columns=GSet).to_string()}\")\r\n print()\r\n\r\n print(\"Y_ig (binary export): \\n\", pd.DataFrame(deleteZeroElements(Y_ig.X), index=ISet, columns=GSet).to_string())\r\n print()\r\n\r\n print(\"Z_ig (binary import): \\n\", pd.DataFrame(deleteZeroElements(Z_ig.X), index=ISet, columns=GSet).to_string())\r\n print()\r\n\r\nprint()\r\nprint(\"===== RESULT =====\")\r\nprint(f\"Objective : {round(objective.getValue(), 3)} (costImportance={costImportance}, CO2Importance={CO2Importance})\")\r\nprint(f\"Total time : {round(total_time, 3)} sec\")\r\nprint()\r\n\r\nFCC_daily = (FCC.X / (alpha * CCF))\r\nTCC_daily = (TCC.X / (alpha * CCF))\r\nprint(\"=== COST VARIABLES ===\")\r\nprint(f\"TDC (Total Daily Cost) = {round(TDC.X, 2)} \")\r\nprint(f\" * FSC (FeedStock Cost) = {round(FSC.X, 2)} ({round(100 * (FSC.X / TDC.X), 1)}\\%)\")\r\nprint(f\" * FCC (Facility Capital Cost) = {round(FCC_daily, 2)} ({round(100 * (FCC_daily / TDC.X), 1)}\\%) ({round(FCC.X, 2)} $ in total)\")\r\nprint(f\" * FOC (Facility Operating Cost) = {round(FOC.X, 2)} ({round(100 * (FOC.X / TDC.X), 1)}\\%)\")\r\nprint(f\" * TCC (Transport Capital Cost) = {round(TCC_daily, 2)} ({round(100 * (TCC_daily / TDC.X), 1)}\\%) ({round(TCC.X, 2)} $ in total)\")\r\nprint(f\" * TOC (Transport Operating Cost) = {round(TOC.X, 2)} ({round(100 * (TOC.X / TDC.X), 1)}\\%)\")\r\nprint(f\" - FC (Fueling Cost) = {round(FC.X, 2)} ({round(100 * (FC.X / TOC.X), 1)}\\%), ({round(100 * (FC.X / TDC.X), 1)}% of total)\")\r\nprint(f\" - LC (Labour Cost) = {round(LC.X, 2)} ({round(100 * (LC.X / TOC.X), 1)}\\%), ({round(100 * (LC.X / TDC.X), 1)}% of total)\")\r\nprint(f\" - MC (Maintenance Cost) = {round(MC.X, 2)} ({round(100 * (MC.X / TOC.X), 1)}\\%), ({round(100 * (MC.X / TDC.X), 1)}% of total)\")\r\nprint(f\" - GC (General Cost) = {round(GC.X, 2)} ({round(100 * (GC.X / TOC.X), 1)}\\%), ({round(100 * (GC.X / TDC.X), 1)}% of total)\")\r\nprint()\r\n\r\nprint(\"=== CARBON VARIABLES ===\")\r\nprint(f\"TCE (Total Carbon Emission) = {round(TCE.X, 2)}\")\r\nprint(f\" * TCEFeed (Feedstock Em.) = {round(TCEFeed.X, 1)} ({round(100 * (TCEFeed.X / TCE.X), 1)}\\%)\")\r\nprint(f\" * TCEProd (Production Em.) = {round(TCEProd.X, 2)} ({round(100 * (TCEProd.X / TCE.X), 1)}\\%)\")\r\nprint(f\" * TCETrans (Transport Em.) = {round(TCETrans.X, 2)} ({round(100 * (TCETrans.X / TCE.X), 1)}\\%)\")\r\nprint()\r\nprint(\"POST-optimization Carbon intensities and total carbon emissions per grid: \")\r\nCI_and_Carbon = np.zeros(shape=(len(G), 6))\r\nCI_and_Carbon[:, 0] = CI_ig_post[0, :]\r\nCI_and_Carbon[:, 1] = CI_ig_post[1, :]\r\nCI_and_Carbon[:, 2] = CI_g_post\r\nCI_and_Carbon[:, 3] = Carbon_ig_post[0, :]\r\nCI_and_Carbon[:, 4] = Carbon_ig_post[1, :]\r\nCI_and_Carbon[:, 5] = Carbon_g_post\r\nprint(pd.DataFrame(CI_and_Carbon, index=GSet, columns=[\"CI_[CH2]g\", \"CI_[LH2]g\", \"CI_g\", \"Carbon_[CH2]g\", \"Carbon_[LH2]g\", \"Carbon_g\"]).to_string())\r\nprint()\r\n\r\nif optimizeCI:\r\n\r\n def correctCI(CI_ig_input, DI_ig_input, DL_ig_input):\r\n \"\"\" Function to set CI values to 0 is there is no satisfied demand\r\n :param CI_ig_input: Carbon intensity of product i and grid g\r\n :param DI_ig_input: Satisfied demand imported of product i in grid g\r\n :param DL_ig_input: Satisfied demand locally satisfied of product in in grid g.\"\"\"\r\n for i in I:\r\n for g in G:\r\n if (DI_ig_input[(i, g)] + DL_ig_input[(i, g)] < 0.0001) and (CI_ig_input[(i, g)] > 0):\r\n CI_ig_input[(i, g)] = 0\r\n return CI_ig_input\r\n\r\n\r\n CI_ig_corr = correctCI(CI_ig.X, DI_ig.X, DL_ig.X)\r\n\r\n print(\"DURING-optimization Carbon intensities and total carbon emissions per grid: \")\r\n CI_and_Carbon = np.zeros(shape=(len(G), 6))\r\n CI_and_Carbon[:, 0] = CI_ig_corr[0, :]\r\n CI_and_Carbon[:, 1] = CI_ig_corr[1, :]\r\n CI_and_Carbon[:, 2] = CI_g.X\r\n CI_and_Carbon[:, 3] = CI_ig.X[0, :] * (DL_ig.X[0, :] + DI_ig.X[0, :])\r\n CI_and_Carbon[:, 4] = CI_ig.X[1, :] * (DL_ig.X[1, :] + DI_ig.X[1, :])\r\n CI_and_Carbon[:, 5] = CI_g.X * DT_g\r\n print(pd.DataFrame(CI_and_Carbon, index=GSet, columns=[\"CI_[CH2]g\", \"CI_[LH2]g\", \"CI_g\", \"Carbon_[CH2]g\", \"Carbon_[LH2]g\", \"Carbon_g\"]).to_string())\r\n print()\r\n\r\nprint(\"Validity check: \")\r\nprint(\"TCE =\", round(TCE.X, 3))\r\nprint(\"POST: sum(Carbon_g_post) =\", round(sum(Carbon_g_post), 3))\r\nif optimizeCI:\r\n print(\"DURING: sum(Carbon_g) =\", round(sum(CI_g.X * DT_g), 3))\r\nprint()\r\n\r\nif printTests:\r\n print(\"==================== TEST =============================\")\r\n\r\n print(\"CIStart_pi: \\n\", pd.DataFrame(CIStart_pi, index=PSet, columns=ISet).to_string())\r\n print()\r\n\r\n print(\"CIPlants_ig_post: \\n\", pd.DataFrame(CIPlants_ig_post, index=ISet, columns=GSet).to_string())\r\n print()\r\n\r\n print(\"CIProd_denominator_ig: \\n\", pd.DataFrame(CIProd_denominator_ig, index=ISet, columns=GSet).to_string())\r\n print()\r\n\r\n print(\"CIProd_ig_post: \\n\", pd.DataFrame(CIProd_ig_post, index=ISet, columns=GSet).to_string())\r\n print()\r\n\r\n print(\"CITrans_ig_post: \\n\", pd.DataFrame(CITrans_ig_post, index=ISet, columns=GSet).to_string())\r\n print()\r\n\r\n print(\"CI_ig_post: \\n\", pd.DataFrame(CI_ig_post, index=ISet, columns=GSet).to_string())\r\n print()\r\n\r\n print(\"C_g: \\n\", pd.DataFrame(CI_g_post, index=GSet).T.to_string())\r\n print()\r\n\r\n print(\"Carbon_ig_post: \\n\", pd.DataFrame(Carbon_ig_post, index=ISet, columns=GSet).to_string())\r\n print()\r\n\r\n print(\"Carbon_g_post: \\n\", pd.DataFrame(Carbon_g_post, index=GSet).T.to_string())\r\n print()\r\n","repo_name":"erikvdheide/MSc-Thesis-Operations-Research","sub_path":"Model HSCN/Model_HSCN_static.py","file_name":"Model_HSCN_static.py","file_ext":"py","file_size_in_byte":32110,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"15861346372","text":"cats = []\n\nwhile True:\n print('Enter the name of cat ' + str(len(cats) + 1) +\n ' (Or enter nothig to stop.): ')\n name = input()\n if name == '':\n break\n cats = cats + [name] #list concatenation\nprint('The cat names are; ')\nfor name in cats:\n print(' ' + name)\n","repo_name":"CappeArg/PractiPyRPA","sub_path":"allMyCats2.py","file_name":"allMyCats2.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"19255814160","text":"from monosat import *\nimport functools\nimport math\nfrom monosat import *\nimport os\nfrom random import shuffle\nimport random\nimport random\nimport sys\nimport itertools\n\nfilename=None\nif __name__ == \"__main__\":\n seed = random.randint(1,100000)\n if len(sys.argv)>1:\n filename=sys.argv[1]\n if len(sys.argv)>2:\n seed=int(sys.argv[2])\n\nMonosat().newSolver(filename)\n\nprint(\"begin encode\");\n\nrandom.seed(seed)\nprint(\"RandomSeed=\" + str(seed))\n#\nwidth=4\n\n\nnbvs= 15\nnsubsets=8\n\nselects = []\nfor n in range(nbvs):\n selects.append(true() if random.random()>0.5 else false())\n\nmax_subsets=[]\nmin_subsets=[]\nselecteds=[]\nfor i in range(nsubsets):\n\n max_subset=[]\n min_subset=[]\n selected=[]\n selecteds.append(selected)\n max_subsets.append(max_subset)\n min_subsets.append(min_subset)\n weights = []\n for v in selects:\n weights.append(random.randint(-10,10))\n select = Var()\n selected.append(select)\n max_subset.append(If(select,v,false())) #1<output_num:\n output_num = int(output_list[i])\n print(output_num)\n\n\n","repo_name":"wuchaoml/on-campus-recruitment","sub_path":"校招-2017/zifu.py","file_name":"zifu.py","file_ext":"py","file_size_in_byte":617,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"73159328413","text":"import os\nimport sqlite3\nfrom sqlite3 import Error\n\nimport sqlalchemy\nfrom sqlalchemy import Table,Column\nfrom sqlalchemy import MetaData\n\nimport pandas\n\n\nclass Db_management():\n \"\"\"generic functionality for creation and modification of databases and tables\"\"\"\n def __init__(self,db_file_location):\n self.loc=db_file_location\n\n \n\n def create_empty_sqlite_db(self,name):\n \"\"\" create a database connection to a SQLite database \"\"\"\n conn = None\n full_name=self.loc+'\\\\'+name+'.db'\n try:\n conn = sqlite3.connect(full_name)\n \n except Error as e:\n print(e)\n finally:\n if conn:\n conn.close()\n def delete_sqlite_db(self,name):\n full_name=self.loc+'\\\\'+name+'.db'\n os.remove(full_name)\n\n def create_sqlite_engine(self,name):\n full_name=self.loc+'\\\\'+name+'.db'\n if os.path.exists(full_name):\n engine = sqlalchemy.create_engine('sqlite:///'+full_name)\n return engine\n else:\n \n return None\n \n def create_empty_table(self,db_name,table_name):\n \"\"\"\" useless function, only useful to test get_list_of_tables\"\"\"\n engine=self.create_sqlite_engine(db_name)\n meta=MetaData()\n table=sqlalchemy.Table(table_name,meta,Column('id', sqlalchemy.Integer, primary_key = True))\n meta.create_all(engine) \n def get_list_of_tables(self,db_name):\n engine=self.create_sqlite_engine(db_name)\n return engine.table_names()\n\n\n\n def read_table(self,db_name,table_name):\n engine=self.create_sqlite_engine(db_name)\n self.engine.connect()\n metadata = MetaData()\n tbl_data = db.Table(table_name, metadata, autoload=True, autoload_with=self.engine)\n return tbl_data\n\n\n","repo_name":"j2755/flashcard_aid","sub_path":"flashcard_aid/data_handling/db_handling.py","file_name":"db_handling.py","file_ext":"py","file_size_in_byte":1825,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"1166820566","text":"# Author(s) Mike Elasky\r\n# Date 7/30/2018\r\n# Title ScientificRounding\r\n# Used to round scientifically\r\n# Code version 1.00\r\n# Type (Python Custom Module)\r\n\r\ndef scientific_rounding(num, precision = 0):\r\n numstr = '0' + str(num)\r\n if numstr.count('.') == 0:\r\n return num\r\n \r\n splistprec = numstr.index('.') + 1 + precision\r\n if len(numstr) <= (splistprec + 2):\r\n numstr += '0' * (splistprec + 2 - len(numstr))\r\n \r\n roundnums = numstr[splistprec:splistprec+2]\r\n result = numstr[:splistprec]\r\n \r\n next_sig = result[-1] if result[-1] != '.' else result[-2]\r\n if int(roundnums) >= (51 - (int(next_sig) % 2)):\r\n if result[-1] == '.':\r\n result = str(int(result[:-1]) + 1)\r\n else:\r\n idx = result.index('.')\r\n tmp = result[idx+1:]\r\n dec = str(int(tmp) + 1)\r\n if len(tmp) > len(dec):\r\n dec = '0' * (len(tmp) - len(dec)) + dec\r\n if len(tmp) < len(dec):\r\n result = str(int(result[:idx]) + 1) + '.' + dec[1:]\r\n else:\r\n result = result[:idx] + '.' + dec\r\n \r\n return float(result)","repo_name":"michaelelasky/AP_MnCustomScripts","sub_path":"ScientificRounding.py","file_name":"ScientificRounding.py","file_ext":"py","file_size_in_byte":1088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"152959478","text":"from q5_shape import Shape, Circle, Rhombus, Ellipse\n\n\ndef main(file=None):\n # Get content of file containing shapes and store in file object\n if file is None:\n file = open(\"shapes.txt\", \"r\")\n\n # Read all lines of the file and return list of strings\n s_info = file.readlines()\n\n # Construct shape objects from string and store as list of shapes\n shapes = []\n for line in s_info:\n shapes.append(construct_shape(line))\n\n # For each shape call print method\n # If shape is ellipse or rhombus print linear eccentricity or in-radius, respectively\n # In case of error with shape parameters, error message is displayed\n # q7: count occurence of each shape\n count_names = dict()\n for i in shapes:\n name = type(i).__name__\n # q7: If name of shape is already in dictionary update count\n # else, create new element\n if name in count_names:\n count_names[name] += 1\n else:\n count_names[name] = 1\n\n if name != \"Shape\" and i.area() is None:\n print(\"Error: Invalid \" + name)\n i.print()\n if name == \"Ellipse\" and i.area() is not None:\n print(\" linear eccentricity: %.5f\" % i.eccentricity())\n elif name == \"Rhombus\" and i.area() is not None:\n print(\" in-radius: %.5f\" % i.inradius())\n\n print_statistics(count_names)\n\n\n# Takes dictionary of shape names and it's count & prints the statistics of count\ndef print_statistics(count_names):\n print(\"\\n\\nStatistics:\")\n print(\" Circle(s): \", count_names[\"Circle\"])\n print(\" Ellipse(s): \", count_names[\"Ellipse\"])\n print(\" Rhombus(es): \", count_names[\"Rhombus\"])\n print(\" --\")\n print(\" Shape(s): \", sum(count_names.values()), \"\\n\")\n\n\n# Counstructs a shape object based on shape name and values\ndef construct_shape(str):\n # Convert the string containing the line data into list of shape info\n # e.g. [name, arg1, arg2]\n shape = str.split(\" \")\n\n # Create the shape based on information and return the shape object\n name = shape[0].lower().strip()\n if name == \"shape\":\n return Shape()\n elif name == \"circle\":\n return Circle(float(shape[1]))\n elif name == \"ellipse\":\n return Ellipse(float(shape[1]), float(shape[2]))\n elif name == \"rhombus\":\n return Rhombus(float(shape[1]), float(shape[2]))\n\n\n# TESTS\n\n\ndef test_main():\n class FakeFile:\n def readlines(self):\n return [\"shape\", \"rhombus 10 20\"]\n\n main(FakeFile())\n\n\ndef test_file_process():\n assert type(construct_shape(\"shape\")) is Shape\n assert type(construct_shape(\"rhombus 10 20\")) is Rhombus\n assert type(construct_shape(\"circle 2\")) is Circle\n assert type(construct_shape(\"Ellipse 2 4\")) is Ellipse\n assert construct_shape(\"Ellipse -1 4\").area() is None\n\n\nif __name__ == \"__main__\":\n main()\n # $ python q2_lucas_sequence.py\n # $ coverage run -m pytest q2_lucas_sequence.py\n # $ coverage report\n","repo_name":"huln24/COMP-348","sub_path":"Assignment3/q6_7_file_processing.py","file_name":"q6_7_file_processing.py","file_ext":"py","file_size_in_byte":2986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"22780650274","text":"# -*- coding: utf-8 -*-\nimport pytest\n\n\n@pytest.mark.xfail(reason=\"Blows up with a 500 no matter what\")\ndef test_200_success(petstore):\n pets = petstore.pet.findPetsByTags(tags=['string']).result()\n assert pets\n for pet in pets:\n assert type(pet).__name__ == 'Pet'\n assert pet.status == 'sold'\n\n\n@pytest.mark.xfail(reason=\"Don't know how to cause a 400\")\ndef test_400_invalid_tag_value(petstore):\n assert False\n","repo_name":"sjaensch/aiobravado","sub_path":"tests/petstore/pet/findPetsByTags_test.py","file_name":"findPetsByTags_test.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"33"} +{"seq_id":"22226887051","text":"import time\nfrom multiprocessing import Process\n\nfrom log.logger import get_logger\nfrom service.cookies_store import CookiesStore\nfrom service.pdd_cookies_valid import PddCookieValidator\nfrom service.tb_cookies_valid import TbCookieValidator\n\nlogger = get_logger('cookies_schedule')\n\n\nclass CookiePoolSchedule:\n @staticmethod\n def store_cookie(period=30):\n while True:\n logger.info('cookies store start.')\n try:\n CookiesStore().cookies_store('pdd')\n CookiesStore().cookies_store('tb')\n time.sleep(period)\n except Exception as e:\n logger.exception(f'store cookies e:{e}')\n\n @staticmethod\n def valid_cookie(period=60):\n while True:\n logger.info('cookies valid start.')\n try:\n PddCookieValidator('pdd').do_valid()\n TbCookieValidator('tb').do_valid()\n logger.info('cookies valid finished.')\n time.sleep(period)\n except Exception as e:\n logger.exception(f'valid cookies e:{e}')\n\n def run(self):\n # store cookie\n store_process = Process(target=CookiePoolSchedule.store_cookie)\n store_process.start()\n\n # valid process\n valid_process = Process(target=CookiePoolSchedule.valid_cookie)\n valid_process.start()\n","repo_name":"newlilee/cookies_pool","sub_path":"cookie_task/schedule.py","file_name":"schedule.py","file_ext":"py","file_size_in_byte":1372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"15948798194","text":"import pandas as pd\nimport openai\nimport numpy as np\nimport pickle\nfrom transformers import GPT2TokenizerFast\nfrom transformers import AutoTokenizer\nimport os\n\nos.environ[\"TOKENIZERS_PARALLELISM\"] = \"false\"\n\nMODEL_NAME = \"curie\"\n\nCOMPLETIONS_MODEL = \"text-davinci-003\"\n\n# QUERY_EMBEDDINGS_MODEL = f\"text-search-{MODEL_NAME}-query-001\"\nQUERY_EMBEDDINGS_MODEL = \"text-embedding-ada-002\"\n\nMAX_SECTION_LEN = 3000\nSEPARATOR = \"\\n* \"\n\ntokenizer = GPT2TokenizerFast.from_pretrained(\"gpt2\")\nseparator_len = len(tokenizer.tokenize(SEPARATOR))\n\nCOMPLETIONS_API_PARAMS = {\n # We use temperature of 0.0 because it gives the most predictable, factual answer.\n \"temperature\": 0.0,\n \"max_tokens\": 300,\n \"model\": COMPLETIONS_MODEL,\n}\n\n\ndef load_embeddings(fname: str):\n \"\"\"\n Read the document embeddings and their keys from a CSV.\n \n fname is the path to a CSV with exactly these named columns: \n \"title\", \"heading\", \"0\", \"1\", ... up to the length of the embedding vectors.\n \"\"\"\n \n df = pd.read_csv(fname, header=0)\n max_dim = max([int(c) for c in df.columns if c != \"text\" and c != \"episode_title\" and c != \"author\" and c != \"position\"])\n return {\n (r.episode_title, r.text, r.author, r.position): [r[str(i)] for i in range(max_dim + 1)] for _, r in df.iterrows()\n }\n\ndef get_embedding(text: str, model: str):\n result = openai.Embedding.create(\n model=model,\n input=text\n )\n return result[\"data\"][0][\"embedding\"]\n\ndef get_doc_embedding(text: str):\n return get_embedding(text, DOC_EMBEDDINGS_MODEL)\n\ndef get_query_embedding(text: str):\n return get_embedding(text, QUERY_EMBEDDINGS_MODEL)\n\ndef vector_similarity(x: list[float], y: list[float]) -> float:\n \"\"\"\n We could use cosine similarity or dot product to calculate the similarity between vectors.\n In practice, we have found it makes little difference. \n \"\"\"\n return np.dot(np.array(x), np.array(y))\n\ndef order_document_sections_by_query_similarity(query: str, contexts: dict[(str, str), np.array]) -> list[(float, (str, str))]:\n \"\"\"\n Find the query embedding for the supplied query, and compare it against all of the pre-calculated document embeddings\n to find the most relevant sections. \n \n Return the list of document sections, sorted by relevance in descending order.\n \"\"\"\n query_embedding = get_query_embedding(query)\n \n document_similarities = sorted([\n (vector_similarity(query_embedding, doc_embedding), doc_index) for doc_index, doc_embedding in contexts.items()\n ], reverse=True)\n \n return document_similarities\n\n\ndef construct_prompt(question: str, context_embeddings: dict, df: pd.DataFrame) -> str:\n \"\"\"\n Fetch relevant \n \"\"\"\n most_relevant_document_sections = order_document_sections_by_query_similarity(question, context_embeddings)\n \n chosen_sections = []\n chosen_sections_len = 0\n chosen_sections_indexes = []\n\n tokenizer = AutoTokenizer.from_pretrained(\"bert-base-uncased\")\n\n \n for _, section_index in most_relevant_document_sections:\n # Add contexts until we run out of space. \n # document_section = df.loc[section_index]\n \n document_section = section_index[1]\n title = section_index[0]\n position = section_index[3]\n\n chosen_sections_len += len(tokenizer.tokenize(document_section)) + separator_len\n if chosen_sections_len > MAX_SECTION_LEN:\n break\n \n chosen_sections.append(SEPARATOR + document_section.replace(\"\\n\", \" \") + \"Source:\" + title + \".Position:\" + str(round(position * 100, 0))+\"%\")\n chosen_sections_indexes.append(str(section_index))\n \n # Useful diagnostic information\n # print(f\"Selected {len(chosen_sections)} document sections:\")\n # print(\"\\n\".join(chosen_sections_indexes))\n \n header = \"\"\"Answer the question as truthfully as possible, and if you're unsure of the answer, say \"Sorry, I don't know\". End your response with: 'If you'd like to learn more about this, you can find information here:[source] around [position] of the way through the episode'. Then list the main source and position used from the context to generate the answer.\\n\\nContext:\\n\"\"\"\n \n prompt = header + \"\".join(chosen_sections) + \"\\n\\n Q: \" + question + \"\\n A:\"\n\n print(\"Prompt: \" + prompt)\n return prompt\n\n\ndef answer_query_with_context(\n query: str,\n df: pd.DataFrame,\n document_embeddings: dict[(str, str), np.array],\n show_prompt: bool = False\n) -> str:\n prompt = construct_prompt(\n query,\n document_embeddings,\n df\n )\n \n if show_prompt:\n print(prompt)\n\n response = openai.Completion.create(\n prompt=prompt,\n **COMPLETIONS_API_PARAMS\n )\n\n return response[\"choices\"][0][\"text\"].strip(\" \\n\")\n\n\ndef main():\n df = pd.read_csv('all_transcripts_embeddings.csv')\n df = df.set_index([\"text\", \"episode_title\", \"author\", \"position\"]) \n document_embeddings = load_embeddings('all_transcripts_embeddings.csv')\n\n while True:\n # Prompt the user for input.\n question = input(\"What question do you have for Dr. Huberman? \")\n \n # Call the huberman() function to generate a response.\n response = answer_query_with_context(question, df, document_embeddings)\n \n # Print the response to the console.\n print(response)\n\n\n # response = answer_query_with_context(\"What's the 85% rule?\", df, document_embeddings)\n # print(response)\n # response = answer_query_with_context(\"What is learning?\", df, document_embeddings)\n # print(response)\n # response = answer_query_with_context(\"What is delay discounting?\", df, document_embeddings)\n # print(response)\n\n # example_entry = list(document_embeddings.items())[0]\n # print(f\"{example_entry[0]} : {example_entry[1][:5]}... ({len(example_entry[1])} entries)\")\n # similiarities = order_document_sections_by_query_similarity(\"What's the 85% rule?\", document_embeddings)[:5]\n # print(similiarities)\n # convert_csv_to_embeddings_csv('nothing')\n\n\nif __name__ == \"__main__\":\n main()\n\n\n# {0: [0.009069414809346199, -0.006452879402786493, -0.012989562936127186, 0.015587475150823593, -0.020373594015836716, -0.009991255588829517, -0.005470514763146639, -0.02124887704849243, -0.003207816742360592, ...]}","repo_name":"EveryInc/transcriptbot","sub_path":"question_answering.py","file_name":"question_answering.py","file_ext":"py","file_size_in_byte":6379,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"33"} +{"seq_id":"28998916240","text":"\"\"\"\n커피 키오스크 코드를 수정하는데 이번에는 돈과 커피의 개수를 받아 다음과 같이 결과를 출력하자.\n\n돈을 입력하세요: 600\n커피는 몇 잔 드릴까요? 2\n커피 두 잔 나왔습니다.\"\"\"\n\ncoffee = 10\nprint(\"커피 한 잔의 가격은 300원 입니다.\")\n\nwhile True:\n if coffee <= 0:\n print(\"커피가 품절되었습니다.\")\n break\n\n cups = int(input(\"커피는 몇 잔 드릴까요? \"))\n\n if cups > coffee: # 주문한 커피 갯수가 남아있는 커피보다 많으면\n print(f\"커피가 {coffee}잔 남았습니다. 개수를 다시 지정해주세요.\")\n continue\n print(f\"내실 돈의 총 가격은 {cups * 300}원 입니다.\")\n\n money = int(input(\"내실 돈을 입력하세요 : \"))\n\n if money >= 300: # 넣은돈이 커피값과 같거나 크면\n if money - (cups * 300) != 0: # 넣은돈이 딱 맞을 경우\n print(f\"거스름돈은 {money - (cups * 300)}원 입니다.\")\n\n coffee -= cups\n else:\n print(f\"돈이 {(cups * 300) - money}원이 부족합니다 돈을 반환합니다.\")\n\n","repo_name":"yujin991207/NewDataScience","sub_path":"01_PythonBasic/coffee_qu02.py","file_name":"coffee_qu02.py","file_ext":"py","file_size_in_byte":1130,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"42476475371","text":"\"\"\"\nIntegration-y tests for the REST interface interacting with the mock model.\n\nThis is perhaps not the place for these tests to go. Also, perhaps this should\ninstead be tested by spinning up an actually HTTP server (thus this test can\nhappen using the mock tap file).\n\nBut until a decision has been made for integration test infrastructure and\nframeworks, this will do for now, as it is needed to verify that the rest unit\ntests and mock model unit tests do not lie.\n\"\"\"\n\nimport json\nimport mock\nfrom urlparse import urlsplit\n\nfrom twisted.trial.unittest import TestCase\nfrom twisted.internet import defer\n\nfrom otter.json_schema.group_examples import config, launch_server_config, policy\nfrom otter.models.interface import (\n GroupState, NoSuchPolicyError, NoSuchScalingGroupError, NoSuchWebhookError)\nfrom otter.models.mock import MockScalingGroupCollection\nfrom otter.rest.application import root, set_store\n\nfrom otter.test.rest.request import request\nfrom otter.test.utils import DeferredTestMixin, patch\n\nfrom otter.util.config import set_config_data\n\n\ndef _strip_base_url(url):\n return urlsplit(url)[2]\n\n\nclass MockStoreRestScalingGroupTestCase(DeferredTestMixin, TestCase):\n \"\"\"\n Test case for testing the REST API for the scaling group specific endpoints\n (not policies or webhooks) against the mock model.\n\n This could be made a base case instead, and different implementations of\n the model interfaces should be tested using a subclass of this base case.\n\n The store should be cleared between every test case and the test fixture\n reloaded at the start of every test case.\n\n The plan for the case of a DB is that an object can be created that starts\n up a DB, knows how to clear it, load particular fixtures, etc. Each test\n case can be passed to a function in this instance that loads a fixture\n before every test method (or not), and cleans up after every test calling\n the test case's `addCleanup` method. Then, the object will shut down the\n DB process when `trial` finishes its run.\n\n That way the same DB object can be used for other integration tests as well\n (not just this test case), and so the DB only needs to be started once.\n\n In the case of in-memory stores, fixtures can be loaded and duplicated.\n \"\"\"\n\n def setUp(self):\n \"\"\"\n Replace the store every time with a clean one.\n \"\"\"\n store = MockScalingGroupCollection()\n set_store(store)\n set_config_data({'url_root': 'http://127.0.0.1'})\n self.addCleanup(set_config_data, {})\n\n self.config = config()[1]\n self.config['minEntities'] = 0\n self.active_pending_etc = ({}, {}, 'date', {}, False)\n\n # patch both the config and the groups\n self.mock_controller = patch(self, 'otter.rest.configs.controller',\n spec=['obey_config_change'])\n patch(self, 'otter.rest.groups.controller', new=self.mock_controller)\n\n def _mock_obey_config_change(log, trans, config, group, state):\n return defer.succeed(GroupState(\n state.tenant_id, state.group_id, *self.active_pending_etc))\n\n self.mock_controller.obey_config_change.side_effect = _mock_obey_config_change\n\n def create_and_view_scaling_group(self):\n \"\"\"\n Creating a scaling group with a valid config returns with a 200 OK and\n a Location header pointing to the new scaling group.\n\n :return: the path to the new scaling group resource\n \"\"\"\n request_body = {\n \"groupConfiguration\": self.config,\n \"launchConfiguration\": launch_server_config()[0]\n }\n wrapper = self.successResultOf(request(\n root, 'POST', '/v1.0/11111/groups/', body=json.dumps(request_body)))\n\n self.assertEqual(wrapper.response.code, 201,\n \"Create failed: {0}\".format(wrapper.content))\n response = json.loads(wrapper.content)\n for key in request_body:\n self.assertEqual(response[\"group\"][key], request_body[key])\n for key in (\"id\", \"links\"):\n self.assertTrue(key in response[\"group\"])\n\n headers = wrapper.response.headers.getRawHeaders('Location')\n self.assertTrue(headers is not None)\n self.assertEqual(1, len(headers))\n\n # now make sure the Location header points to something good!\n path = _strip_base_url(headers[0])\n\n wrapper = self.successResultOf(request(root, 'GET', path))\n self.assertEqual(wrapper.response.code, 200, path)\n\n response = json.loads(wrapper.content)\n self.assertEqual(response[\"group\"]['groupConfiguration'], self.config)\n self.assertEqual(response[\"group\"]['launchConfiguration'],\n launch_server_config()[0])\n\n # make sure the created group has enough pending entities, and is\n # not paused\n wrapper = self.successResultOf(\n request(root, 'GET', path + 'state/'))\n self.assertEqual(wrapper.response.code, 200)\n\n response = json.loads(wrapper.content)\n self.assertTrue(not response[\"group\"]['paused'])\n\n return path\n\n def delete_and_view_scaling_group(self, path):\n \"\"\"\n Deleting a scaling group returns with a 204 no content. The next\n attempt to view the scaling group should return a 404 not found.\n \"\"\"\n wrapper = self.successResultOf(request(root, 'DELETE', path))\n self.assertEqual(wrapper.response.code, 204,\n \"Delete failed: {0}\".format(wrapper.content))\n self.assertEqual(wrapper.content, \"\")\n\n # now try to view\n wrapper = self.successResultOf(request(root, 'GET', path))\n self.assertEqual(wrapper.response.code, 404)\n wrapper = self.successResultOf(\n request(root, 'GET', path + 'state/'))\n self.assertEqual(wrapper.response.code, 404)\n\n # flush any logged errors\n self.flushLoggedErrors(NoSuchScalingGroupError)\n\n def assert_number_of_scaling_groups(self, number):\n \"\"\"\n Asserts that there are ``number`` number of scaling groups\n \"\"\"\n wrapper = self.successResultOf(\n request(root, 'GET', '/v1.0/11111/groups/'))\n self.assertEqual(200, wrapper.response.code)\n\n response = json.loads(wrapper.content)\n self.assertEqual(len(response[\"groups\"]), number)\n\n def test_crd_scaling_group(self):\n \"\"\"\n Start with no scaling groups. Create one, make sure it's listed, then\n delete it and make sure it's no longer listed.\n \"\"\"\n # start with no scaling groups\n self.assert_number_of_scaling_groups(0)\n path = self.create_and_view_scaling_group()\n\n # there should still be one scaling group\n self.assert_number_of_scaling_groups(1)\n self.delete_and_view_scaling_group(path)\n\n # there should be no scaling groups now\n self.assert_number_of_scaling_groups(0)\n\n def test_ru_launch_config(self):\n \"\"\"\n Editing the launch config of a scaling group with a valid launch config\n returns with a 204 no content. The next attempt to view the launch\n config should return the new launch config.\n \"\"\"\n # make sure there is a scaling group\n path = self.create_and_view_scaling_group() + 'launch/'\n edited_launch = launch_server_config()[1]\n\n wrapper = self.successResultOf(\n request(root, 'PUT', path, body=json.dumps(edited_launch)))\n\n self.assertEqual(wrapper.response.code, 204,\n \"Edit failed: {0}\".format(wrapper.content))\n self.assertEqual(wrapper.content, \"\")\n\n # now try to view again - the config should be the edited config\n wrapper = self.successResultOf(\n request(root, 'GET', path))\n self.assertEqual(wrapper.response.code, 200)\n self.assertEqual(json.loads(wrapper.content),\n {'launchConfiguration': edited_launch})\n\n\nclass MockStoreRestScalingPolicyTestCase(DeferredTestMixin, TestCase):\n \"\"\"\n Test case for testing the REST API for the scaling policy specific endpoints\n (but not webhooks) against the mock model.\n\n As above, this could be made a base case instead... yadda yadda.\n \"\"\"\n tenant_id = '11111'\n\n def setUp(self):\n \"\"\"\n Replace the store every time with a clean one.\n \"\"\"\n store = MockScalingGroupCollection()\n self.mock_log = mock.MagicMock()\n manifest = self.successResultOf(\n store.create_scaling_group(self.mock_log, self.tenant_id, config()[0],\n launch_server_config()[0]))\n self.group_id = manifest['id']\n set_store(store)\n\n self.policies_url = '/v1.0/{tenant}/groups/{group}/policies/'.format(\n tenant=self.tenant_id, group=self.group_id)\n\n controller_patcher = mock.patch('otter.rest.policies.controller')\n self.mock_controller = controller_patcher.start()\n self.mock_controller.maybe_execute_scaling_policy.return_value = defer.succeed(\n GroupState(self.tenant_id, self.group_id, {}, {}, 'date', {}, False))\n self.addCleanup(controller_patcher.stop)\n\n set_config_data({'url_root': 'http://127.0.0.1'})\n self.addCleanup(set_config_data, {})\n\n def assert_number_of_scaling_policies(self, number):\n \"\"\"\n Asserts that there are ``number`` number of scaling policies\n \"\"\"\n wrapper = self.successResultOf(\n request(root, 'GET', self.policies_url))\n self.assertEqual(200, wrapper.response.code)\n\n response = json.loads(wrapper.content)\n self.assertEqual(len(response[\"policies\"]), number)\n\n def create_and_view_scaling_policies(self):\n \"\"\"\n Creating valid scaling policies returns with a 200 OK, a Location\n header pointing to the list of all scaling policies, and a response\n containing a list of the newly created scaling policy resources only.\n\n :return: a list self links to the new scaling policies (not guaranteed\n to be in any consistent order)\n \"\"\"\n request_body = policy()[:-1] # however many of them there are minus one\n wrapper = self.successResultOf(request(\n root, 'POST', self.policies_url, body=json.dumps(request_body)))\n\n self.assertEqual(wrapper.response.code, 201,\n \"Create failed: {0}\".format(wrapper.content))\n response = json.loads(wrapper.content)\n\n self.assertEqual(len(request_body), len(response[\"policies\"]))\n\n # this iterates over the response policies, checks to see that each have\n # 'id' and 'links' keys, and then checks to see that the rest of the\n # response policy is in the original set of policies to be created\n for pol in response[\"policies\"]:\n original_pol = pol.copy()\n for key in ('id', 'links'):\n self.assertIn(key, pol)\n del original_pol[key]\n self.assertIn(original_pol, request_body)\n\n headers = wrapper.response.headers.getRawHeaders('Location')\n self.assertTrue(headers is not None)\n self.assertEqual(1, len(headers))\n\n # now make sure the Location header points to the list policies header\n self.assertEqual(_strip_base_url(headers[0]), self.policies_url)\n\n links = [_strip_base_url(link[\"href\"])\n for link in pol[\"links\"] if link[\"rel\"] == \"self\"\n for pol in response[\"policies\"]]\n return links\n\n def update_and_view_scaling_policy(self, path):\n \"\"\"\n Updating a scaling policy returns with a 204 no content. When viewing\n the policy again, it should contain the updated version.\n \"\"\"\n request_body = policy()[-1] # the one that was not created\n wrapper = self.successResultOf(\n request(root, 'PUT', path, body=json.dumps(request_body)))\n self.assertEqual(wrapper.response.code, 204,\n \"Update failed: {0}\".format(wrapper.content))\n self.assertEqual(wrapper.content, \"\")\n\n # now try to view\n wrapper = self.successResultOf(request(root, 'GET', path))\n self.assertEqual(wrapper.response.code, 200)\n\n response = json.loads(wrapper.content)\n updated = response['policy']\n\n self.assertIn('id', updated)\n self.assertIn('links', updated)\n self.assertIn(\n path, [_strip_base_url(link[\"href\"]) for link in updated[\"links\"]])\n\n del updated['id']\n del updated['links']\n\n self.assertEqual(updated, request_body)\n\n def delete_and_view_scaling_policy(self, path):\n \"\"\"\n Deleting a scaling policy returns with a 204 no content. The next\n attempt to view the scaling policy should return a 404 not found.\n \"\"\"\n wrapper = self.successResultOf(request(root, 'DELETE', path))\n self.assertEqual(wrapper.response.code, 204,\n \"Delete failed: {0}\".format(wrapper.content))\n self.assertEqual(wrapper.content, \"\")\n\n # now try to view\n wrapper = self.successResultOf(request(root, 'GET', path))\n self.assertEqual(wrapper.response.code, 404)\n\n # flush any logged errors\n self.flushLoggedErrors(NoSuchPolicyError)\n\n def test_crud_scaling_policies(self):\n \"\"\"\n Start with no policies. Create some, make sure they're listed,\n create some more because we want to verify that creation response\n contains only the ones that were created. Then update one of them,\n check changes. Then delete one of them and make sure it's no longer\n listed.\n \"\"\"\n # start with no scaling groups\n self.assert_number_of_scaling_policies(0)\n first_policies = self.create_and_view_scaling_policies()\n\n # create more scaling policies, to check the creation response\n self.assert_number_of_scaling_policies(len(first_policies))\n second_policies = self.create_and_view_scaling_policies()\n len_total_policies = len(first_policies) + len(second_policies)\n self.assert_number_of_scaling_policies(len_total_policies)\n\n # update scaling policy, and there should still be the same number of\n # policies after the update\n self.update_and_view_scaling_policy(first_policies[0])\n self.assert_number_of_scaling_policies(len_total_policies)\n\n # delete a scaling policy - there should be one fewer scaling policy\n self.delete_and_view_scaling_policy(second_policies[0])\n self.assert_number_of_scaling_policies(len_total_policies - 1)\n\n def test_execute_scaling_policy_success(self):\n \"\"\"\n Executing a scaling policy should result in a 202.\n \"\"\"\n self.assert_number_of_scaling_policies(0)\n first_policies = self.create_and_view_scaling_policies()\n\n self.assert_number_of_scaling_policies(len(first_policies))\n\n wrapper = self.successResultOf(\n request(root, 'POST', first_policies[0] + 'execute/'))\n self.assertEqual(wrapper.response.code, 202,\n \"Execute failed: {0}\".format(wrapper.content))\n self.assertEqual(wrapper.content, \"{}\")\n\n def test_execute_scaling_policy_failed(self):\n \"\"\"\n Executing a non-existant scaling policy should result in a 404.\n \"\"\"\n\n self.mock_controller.maybe_execute_scaling_policy.return_value = defer.fail(\n NoSuchPolicyError('11111', '1', '2'))\n\n wrapper = self.successResultOf(\n request(root, 'POST', self.policies_url + '1/execute/'))\n self.assertEqual(wrapper.response.code, 404,\n \"Execute did not fail as expected: {0}\".format(wrapper.content))\n\n self.flushLoggedErrors(NoSuchPolicyError)\n\n\nclass MockStoreRestWebhooksTestCase(DeferredTestMixin, TestCase):\n \"\"\"\n Test case for testing the REST API for the webhook specific endpoints\n against the mock model.\n\n As above, this could be made a base case instead... yadda yadda.\n \"\"\"\n tenant_id = '11111'\n\n def setUp(self):\n \"\"\"\n Replace the store every time with a clean one.\n \"\"\"\n self.mock_log = mock.MagicMock()\n store = MockScalingGroupCollection()\n manifest = self.successResultOf(\n store.create_scaling_group(self.mock_log, self.tenant_id,\n config()[0],\n launch_server_config()[0]))\n self.group_id = manifest['id']\n group = store.get_scaling_group(self.mock_log,\n self.tenant_id, self.group_id)\n self.policy_id = self.successResultOf(\n group.create_policies([{\n \"name\": 'set number of servers to 10',\n \"change\": 10,\n \"cooldown\": 3,\n \"type\": \"webhook\"\n }])).keys()[0]\n set_store(store)\n\n self.webhooks_url = (\n '/v1.0/{tenant}/groups/{group}/policies/{policy}/webhooks/'.format(\n tenant=self.tenant_id, group=self.group_id,\n policy=self.policy_id))\n\n self.mock_controller = patch(self, 'otter.rest.webhooks.controller')\n\n def _mock_maybe_execute(log, trans, group, state, policy_id):\n return defer.succeed(state)\n\n self.mock_controller.maybe_execute_scaling_policy.side_effect = _mock_maybe_execute\n\n set_config_data({'url_root': 'http://127.0.0.1'})\n self.addCleanup(set_config_data, {})\n\n def assert_number_of_webhooks(self, number):\n \"\"\"\n Asserts that there are ``number`` number of scaling policies\n \"\"\"\n wrapper = self.successResultOf(\n request(root, 'GET', self.webhooks_url))\n self.assertEqual(200, wrapper.response.code)\n\n response = json.loads(wrapper.content)\n self.assertEqual(len(response[\"webhooks\"]), number)\n\n def create_and_view_webhooks(self):\n \"\"\"\n Creating valid webhooks returns with a 200 OK, a Location header\n pointing to the list of all webhooks, and a response containing a list\n of the newly created webhook resources only.\n\n :return: a list self links to the new webhooks (not guaranteed\n to be in any consistent order)\n \"\"\"\n request_body = [\n {'name': 'first', 'metadata': {'notes': 'first webhook'}},\n {'name': 'second', 'metadata': {'notes': 'second webhook'}}\n ]\n wrapper = self.successResultOf(request(\n root, 'POST', self.webhooks_url, body=json.dumps(request_body)))\n\n self.assertEqual(wrapper.response.code, 201,\n \"Create failed: {0}\".format(wrapper.content))\n response = json.loads(wrapper.content)\n\n self.assertEqual(len(request_body), len(response[\"webhooks\"]))\n\n # this iterates over the webhooks, checks to see that each have\n # 'id' and 'links' keys, makes sure that there is an extra link\n # containing the capability URL, and then checks to see that the\n # rest of the responce is in the original set of webhooks to be created\n for webhook in response[\"webhooks\"]:\n keys = webhook.keys()\n keys.sort()\n self.assertEqual(['id', 'links', 'metadata', 'name'], keys)\n self.assertIn(\n {'metadata': webhook['metadata'], 'name': webhook['name']},\n request_body)\n self.assertIn('capability',\n [link_obj['rel'] for link_obj in webhook['links']])\n\n headers = wrapper.response.headers.getRawHeaders('Location')\n self.assertTrue(headers is not None)\n self.assertEqual(1, len(headers))\n\n # now make sure the Location header points to the list webhooks header\n self.assertEqual(_strip_base_url(headers[0]), self.webhooks_url)\n\n links = [_strip_base_url(link[\"href\"])\n for link in webhook[\"links\"] if link[\"rel\"] == \"self\"\n for webhook in response[\"webhooks\"]]\n return links\n\n def update_and_view_webhook(self, path):\n \"\"\"\n Updating a webhook returns with a 204 no content. When viewing\n the webhook again, it should contain the updated version.\n \"\"\"\n request_body = {'name': 'updated_webhook', 'metadata': {'foo': 'bar'}}\n wrapper = self.successResultOf(\n request(root, 'PUT', path, body=json.dumps(request_body)))\n self.assertEqual(wrapper.response.code, 204,\n \"Update failed: {0}\".format(wrapper.content))\n self.assertEqual(wrapper.content, \"\")\n\n # now try to view\n wrapper = self.successResultOf(request(root, 'GET', path))\n self.assertEqual(wrapper.response.code, 200)\n\n response = json.loads(wrapper.content)\n updated = response['webhook']\n\n self.assertIn('id', updated)\n self.assertIn('links', updated)\n for link in updated[\"links\"]:\n if link['rel'] == 'self':\n self.assertIn(_strip_base_url(link[\"href\"]), path)\n else:\n self.assertEqual(link['rel'], 'capability')\n self.assertIn('/v1.0/execute/1/', link[\"href\"])\n\n del updated['id']\n del updated['links']\n\n self.assertEqual(updated, {'name': 'updated_webhook', 'metadata': {'foo': 'bar'}})\n\n def delete_and_view_webhook(self, path):\n \"\"\"\n Deleting a webhook returns with a 204 no content. The next attempt to\n view the webhook should return a 404 not found.\n \"\"\"\n wrapper = self.successResultOf(request(root, 'DELETE', path))\n self.assertEqual(wrapper.response.code, 204,\n \"Delete failed: {0}\".format(wrapper.content))\n self.assertEqual(wrapper.content, \"\")\n\n # now try to view\n wrapper = self.successResultOf(request(root, 'GET', path))\n self.assertEqual(wrapper.response.code, 404)\n\n # flush any logged errors\n self.flushLoggedErrors(NoSuchWebhookError)\n\n def test_crud_webhooks(self):\n \"\"\"\n Start with no policies. Create some, make sure they're listed,\n create some more because we want to verify that creation response\n contains only the ones that were created. Then update one of them,\n check changes. Then delete one of them and make sure it's no longer\n listed.\n \"\"\"\n # start with no webhooks\n self.assert_number_of_webhooks(0)\n first_webhooks = self.create_and_view_webhooks()\n\n # create more webhooks, to check the creation response\n self.assert_number_of_webhooks(2)\n self.create_and_view_webhooks()\n self.assert_number_of_webhooks(4)\n\n # update webhook, and there should still be the same number of\n # webhook after the update\n self.update_and_view_webhook(first_webhooks[0])\n self.assert_number_of_webhooks(4)\n\n # delete webhook - there should be one fewer webhook\n self.delete_and_view_webhook(first_webhooks[0])\n self.assert_number_of_webhooks(3)\n\n def test_execute_webhook_by_hash(self):\n \"\"\"\n Executing a webhook should look up the policy by hash and attempt\n to execute that policy.\n \"\"\"\n self.assert_number_of_webhooks(0)\n first_webhooks = self.create_and_view_webhooks()\n\n wrapper = self.successResultOf(request(root, 'GET', first_webhooks[0]))\n webhook = json.loads(wrapper.content)['webhook']\n links = {link['rel']: link['href'] for link in webhook['links']}\n cap_path = _strip_base_url(links['capability'])\n\n wrapper = self.successResultOf(request(root, 'POST', cap_path))\n self.assertEqual(wrapper.response.code, 202)\n\n def test_execute_non_existant_webhook_by_hash(self):\n \"\"\"\n Executing a webhook that doesn't exist should still return a 202.\n \"\"\"\n self.assert_number_of_webhooks(0)\n\n wrapper = self.successResultOf(\n request(root, 'POST', '/v1.0/execute/1/1/'))\n self.assertEqual(wrapper.response.code, 202)\n","repo_name":"danngrant/otter","sub_path":"otter/test/unitgration/test_rest_mock_model.py","file_name":"test_rest_mock_model.py","file_ext":"py","file_size_in_byte":24318,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"33"} +{"seq_id":"15016613563","text":"import argparse\nimport json\n\nfrom evergraph.utils.logger_utils import setup_logger\nfrom evergraph.prep.data_prepper import DataPrepper\n\ndef parse_arguments():\n parser = argparse.ArgumentParser(\n description = \"Reorganize and preprocess outputs from HiggsDNA for training with EverGraphDNN\")\n\n # Required arguments\n parser.add_argument(\n \"--input_dir\",\n required=True,\n type=str,\n help=\"path to input directory with `merged_nominal.parquet` and `summary.json` from HiggsDNA\")\n\n parser.add_argument(\n \"--output_dir\",\n required=True,\n type=str,\n help=\"path to output directory\")\n\n # Optional arguments\n parser.add_argument(\n \"--log-level\",\n required=False,\n default=\"DEBUG\",\n type=str,\n help=\"Level of information printed by the logger\") \n\n parser.add_argument(\n \"--log-file\",\n required=False,\n type=str,\n help=\"Name of the log file\")\n\n parser.add_argument(\n \"--short\",\n required=False,\n action=\"store_true\",\n help=\"flag to just process 10k events\")\n\n parser.add_argument(\n \"--selection\",\n required=False,\n default=None,\n type=str,\n help=\"selection to apply on events\")\n\n parser.add_argument(\n \"--objects\",\n required=False,\n default=None,\n type=str,\n help=\"csv list of objects to process (photons, leptons, jets, met)\")\n\n return parser.parse_args()\n\n\ndef main(args):\n logger = setup_logger(args.log_level, args.log_file)\n \n data_prepper = DataPrepper(**vars(args))\n data_prepper.run()\n\n\nif __name__ == \"__main__\":\n args = parse_arguments()\n main(args)\n","repo_name":"sam-may/EverGraphDNN","sub_path":"scripts/prep.py","file_name":"prep.py","file_ext":"py","file_size_in_byte":1852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"38483875072","text":"import os.path\n\n\ndef hent_regnskap():\n regnskap = []\n try:\n les_fil = open(\"regnskap.csv\", \"r\")\n linjenummer = 0\n for linje in les_fil:\n rad = linje.split(\";\")\n if linjenummer > 0:\n regnskap.append(rad)\n linjenummer += 1\n les_fil.close()\n except FileNotFoundError:\n print(\"Regnskapsfil finnes ikke. Ny fil opprettes.\")\n except IOError:\n print(\"Feil under lesing fra fil, sjekk tilganger.\")\n except:\n print(\"Ukjent feil under lesing fra fil, kontakt IT.\")\n return regnskap\n\n\ndef lagre_til_regnskap(tid, betalt_mva, salgssum):\n # Finn neste ID ved å lese fil\n id = 0\n regnskap = hent_regnskap()\n for rad in regnskap:\n id = int(rad[0]) + 1\n # Lagre salg til regnskapsfil\n try:\n ny_fil = not os.path.isfile(\"regnskap.csv\")\n skriv_fil = open(\"regnskap.csv\", mode='a')\n if ny_fil:\n skriv_fil.write(\"ID;Tidspunkt;Betalt MVA;Salgssum\\n\")\n skriv_fil.write(f\"{id};{tid};{betalt_mva};{salgssum}\\n\")\n skriv_fil.close()\n except IOError:\n print(\"Feil under skriving til fil, sjekk tilganger.\")\n except:\n print(\"Ukjent feil under skriving til fil, kontakt IT.\")\n\n# if len(hent_regnskap()) == 0:\n# for month in range(1, 13):\n# for tilfeldig in range(1, 20):\n# date = datetime.date(2021, month, randint(1, 28))\n# time = datetime.time(randint(10, 16), randint(0, 59), 0, 0)\n# tid = datetime.datetime.combine(date, time)\n# tid = tid.strftime(\"%d.%m.%y %H:%M:%S\")\n# pris = float(randint(50, 2000))\n# mva = pris * 0.25\n# lagre_til_regnskap(tid, mva, pris)\n","repo_name":"anzure/python-apotek","sub_path":"lib/regnskap.py","file_name":"regnskap.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"no","doc_type":"code","stars":1,"dataset":"github-code","pt":"33"} +{"seq_id":"41943110247","text":"import torch\nimport torch.nn as nn\nimport numpy as np\n\nfrom net_utils import *\n\nfrom cky import ParsePredictor as CKY\nfrom ccky_basic import ConstrainedCKY as CCKY_Basic\nfrom constrained_cky import ConstrainedCKY as CCKY_MinDiff\n\n\ndef get_spans(tr, lookup):\n spans = []\n def helper(tr, pos):\n if isinstance(tr, str):\n return 1\n assert len(tr) == 2\n l_pos = pos\n l_size = helper(tr[0], l_pos)\n r_pos = l_pos + l_size\n r_size = helper(tr[1], r_pos)\n size = l_size + r_size\n idx = lookup[(l_pos, l_size, r_pos, r_size)]\n spans.append((pos, size, idx))\n return size\n helper(tr, 0)\n return spans\n\n\ndef build_inside_lookup(length):\n lookup = {}\n\n for level in range(1, length):\n L = length - level\n N = level\n for pos in range(L):\n for idx in range(N):\n l_level = idx\n l_pos = pos\n l_size = l_level + 1\n\n r_level = level-idx-1\n r_pos = pos+idx+1\n r_size = r_level + 1\n\n lookup[(l_pos, l_size, r_pos, r_size)] = idx\n\n return lookup\n\n\ndef is_crossing(query, spans):\n def is_crossing_(pos, size, pos_2, size_2):\n assert pos < pos_2\n if pos + size > pos_2:\n if (pos + size) < (pos_2 + size_2):\n return True\n return False\n\n pos, size = query\n for pos_2, size_2 in spans:\n if pos < pos_2 and is_crossing_(pos, size, pos_2, size_2):\n return True\n elif pos > pos_2 and is_crossing_(pos_2, size_2, pos, size):\n return True\n return False\n\n\nclass TreeStructureV3(nn.Module):\n name = 'tree_structure_v3'\n\n def __init__(self, embeddings, input_size, size, word2idx=None, cuda=False, print=False, skip=False,\n **kwargs):\n super().__init__()\n self.embeddings = embeddings\n self.size = size\n self._cuda = cuda\n self.skip = skip\n self.word2idx = word2idx\n\n self.init_defaults()\n\n for k, v in kwargs.items():\n setattr(self, k, v)\n\n def init_defaults(self):\n self.margin = 1.0\n self.weight = 1.0\n self.ccky_mode = 'ccky_mindiff'\n self.original_weight = 1000\n self.constraint_weight = 10000\n self.force_exclude = False\n self.rescale = False\n self.scalars_key = 'inside_xs_components'\n\n @classmethod\n def from_kwargs_dict(cls, context, kwargs_dict):\n kwargs_dict['embeddings'] = context['embedding_layer']\n kwargs_dict['cuda'] = context['cuda']\n kwargs_dict['word2idx'] = context['word2idx']\n return cls(**kwargs_dict)\n\n def get_tree_scores(self, s, batch_span_lst):\n scores = []\n\n for i_b, span_lst in enumerate(batch_span_lst):\n\n score_ = torch.FloatTensor(1).fill_(0).to(self.device)\n for pos, size, idx in span_lst:\n assert size > 1\n\n level = size - 1\n score_ = score_ + s[level][pos][i_b, idx]\n scores.append(score_.view(1))\n\n return torch.cat(scores)\n\n def forward(self, sentences, diora, info, embed=None):\n # print(self.force_exclude, self.rescale, self.ccky_mode)\n\n if self.ccky_mode == 'ccky_mindiff' and self.force_exclude:\n raise Exception(\"Sorry, invalid cky mode\")\n self.device = device = torch.cuda.current_device() if self._cuda else None\n self.batch_size, self.length = batch_size, length = sentences.shape\n size = self.size\n\n # TODO: Should we cache this?\n self.lookup = build_inside_lookup(length)\n\n # CKY\n cky_parser = CKY(net=diora, word2idx=self.word2idx, scalars_key=self.scalars_key)\n\n # Constrained CKY\n if self.ccky_mode == 'ccky_basic':\n ccky_parser = CCKY_Basic(\n net=diora, word2idx=self.word2idx, scalars_key=self.scalars_key)\n elif self.ccky_mode == 'ccky_mindiff':\n ccky_parser = CCKY_MinDiff(\n net=diora, word2idx=self.word2idx, scalars_key=self.scalars_key, pred_weight=self.original_weight, constraint_weight=self.constraint_weight)\n\n neg_parser = cky_parser\n if self.force_exclude:\n neg_parser = ccky_parser\n pos_parser = ccky_parser\n\n constraints = []\n for lst in info['constraints']:\n constraints.append([sp for sp in lst if sp[1] > 1])\n\n batch_map = {}\n batch_map['sentences'] = sentences\n batch_map['example_ids'] = info['example_ids']\n batch_map['ner_labels'] = constraints\n\n # Score components.\n score_components = diora.cache[self.scalars_key]\n\n # First, get the bad trees.\n neg_parser.mode = 'force_exclude'\n with torch.no_grad():\n pred_trees, pred_spans = [], []\n for j, x in enumerate(neg_parser.predict(batch_map)):\n spans = get_spans(x['binary_tree'], self.lookup)\n assert spans[-1][1] == length\n pred_trees.append(x['binary_tree'])\n pred_spans.append(set(spans))\n\n # Then, get the constrained trees.\n pos_parser.mode = 'force_include'\n with torch.no_grad():\n constrained_trees, constrained_spans = [], []\n for j, x in enumerate(pos_parser.predict(batch_map)):\n spans = get_spans(x['binary_tree'], self.lookup)\n assert spans[-1][1] == length\n constrained_trees.append(x['binary_tree'])\n constrained_spans.append(set(spans))\n\n pred_scores = self.get_tree_scores(score_components, pred_spans)\n ccky_scores = self.get_tree_scores(score_components, constrained_spans)\n\n # Mask sentences based on relevance.\n mask_is_different = torch.BoolTensor([a != b for a, b in zip(pred_spans, constrained_spans)]).to(device)\n mask_has_constraint = torch.BoolTensor([len(lst) > 0 for lst in constraints]).to(device)\n mask = torch.logical_and(mask_is_different, mask_has_constraint)\n\n # Compute margin-based loss.\n hinge_b = torch.clamp(self.margin + pred_scores - ccky_scores, min=0)\n\n # Optionally, rescale loss according to distance between trees.\n if self.rescale:\n g = torch.FloatTensor(batch_size).fill_(1).to(device)\n\n for i_b, (constr, pred) in enumerate(zip(constrained_spans, pred_spans)):\n total = len(constr)\n correct = len(set.intersection(constr, pred))\n g[i_b] = correct / total\n\n hinge_b = hinge_b * g\n\n # Apply mask.\n if mask.any().item():\n tr_loss = hinge_b[mask].mean()\n else:\n tr_loss = torch.FloatTensor(1).fill_(0).to(device)\n\n loss = tr_loss * self.weight\n ret = {}\n ret[self.name + '_loss'] = loss\n\n return loss, ret\n\n\nstructure_v3_class = TreeStructureV3\n","repo_name":"iesl/distantly-supervised-diora","sub_path":"loss_structure_v3.py","file_name":"loss_structure_v3.py","file_ext":"py","file_size_in_byte":6975,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"33"} +{"seq_id":"74781086815","text":"import json\nfrom flask import request, _request_ctx_stack, abort\nfrom functools import wraps\nfrom jose import jwt\nfrom urllib.request import urlopen\nfrom flask import Flask, jsonify\n\n\nAUTH0_DOMAIN = 'dev-6gnrncvpus8amyed.us.auth0.com'\nALGORITHMS = ['RS256']\nAPI_AUDIENCE = 'places'\n\n## AuthError Exception\n'''\nAuthError Exception\nA standardized way to communicate auth failure modes\n'''\nclass AuthError(Exception):\n def __init__(self, error, status_code):\n self.error = error\n self.status_code = status_code\n\n\n## Auth Header\n\ndef get_token_auth_header():\n auth = request.headers.get('Authorization', None)\n if not auth:\n abort(401)\n\n parts = auth.split()\n if parts[0].lower() != 'bearer':\n abort(401)\n\n elif len(parts) == 1:\n abort(401)\n\n elif len(parts) > 2:\n abort(401)\n token = parts[1]\n return token\n\ndef check_permissions(permission, payload):\n if 'permissions' not in payload:\n abort(403)\n\n if permission not in payload['permissions']:\n abort(403)\n return True\n\ndef verify_decode_jwt(token):\n try:\n jsonurl = urlopen(f'https://{AUTH0_DOMAIN}/.well-known/jwks.json')\n jwks = json.loads(jsonurl.read())\n unverified_header = jwt.get_unverified_header(token)\n rsa_key = {}\n except:\n abort(401)\n if 'kid' not in unverified_header:\n abort(401)\n\n for key in jwks['keys']:\n if key['kid'] == unverified_header['kid']:\n rsa_key = {\n 'kty': key['kty'],\n 'kid': key['kid'],\n 'use': key['use'],\n 'n': key['n'],\n 'e': key['e']\n }\n if rsa_key:\n try:\n payload = jwt.decode(\n token,\n rsa_key,\n algorithms=ALGORITHMS,\n audience=API_AUDIENCE,\n issuer='https://' + AUTH0_DOMAIN + '/'\n )\n\n return payload\n\n except:\n abort(401)\n\ndef get_user_id(payload):\n return payload.get('sub').split('|')[1]\n\ndef requires_auth(permission=''):\n def requires_auth_decorator(f):\n @wraps(f)\n def wrapper(*args, **kwargs):\n token = get_token_auth_header()\n payload = verify_decode_jwt(token)\n user_id = get_user_id(payload)\n check_permissions(permission, payload)\n return f(user_id, *args, **kwargs)\n\n return wrapper\n return requires_auth_decorator","repo_name":"hamidkhbl/RentersReview","sub_path":"src/auth/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"31730993131","text":"#!/usr/bin/env python3\n\nfrom dotenv import load_dotenv\nimport hashlib\nfrom os import getenv, path, makedirs\nimport re\nfrom typing import Iterator, List\nfrom uuid import uuid4\n\nfrom utils.os_ import get_env\n\nload_dotenv()\n\nBATCH_SIZE: int = 100\nMAX_ENTRIES: int = 10000\n\nDATA_SOURCE_PATH = get_env(\"SOURCE_DATA_FILE\")\nTARGET_DIR = get_env(\"EXTRACTED_TEXT_DIR\")\n\n\ndef load_nt_texts(path: str) -> Iterator[str]:\n with open(path) as file:\n for line in file:\n components = line.split(\" \")\n\n # remove id, description, and closing \".\"\n cleansed_line = \" \".join(components[2:-1])\n cleansed_line = cleansed_line.replace('\"', \"\")\n cleansed_line = cleansed_line.strip()\n\n yield cleansed_line\n\n\ndef contains_iconclass_candidate(text: str) -> bool:\n match = re.search(r\"\\d{2} ?[a-zA-Z]{1,2}\", text)\n return not match is None\n\n\ndef save_batch(data_batch: List[str], dir_path: str) -> None:\n file_path = f\"{dir_path}/{uuid4()}.txt\"\n\n with open(file_path, \"w\") as target_file:\n for i, entry in enumerate(data_batch):\n if i > 0:\n target_file.write(\"\\n\\n\")\n\n target_file.write(entry)\n\n\ndef has_been_encountered(text: str) -> bool:\n if not hasattr(has_been_encountered, \"hash_set\"):\n has_been_encountered.hash_set = set()\n\n text_hash = str(\n hashlib.md5(text.encode(\"utf-8\"), usedforsecurity=False).hexdigest()\n )\n\n if text_hash in has_been_encountered.hash_set:\n return True\n\n has_been_encountered.hash_set.add(text_hash)\n return False\n\n\nif __name__ == \"__main__\":\n if not path.exists(TARGET_DIR):\n makedirs(TARGET_DIR)\n\n entry_counter: int = 0\n\n current_batch: List[str] = []\n for line in load_nt_texts(DATA_SOURCE_PATH):\n if not contains_iconclass_candidate(line):\n continue\n\n # avoid duplicates\n if has_been_encountered(line):\n continue\n\n current_batch.append(line)\n\n entry_counter += 1\n if entry_counter == MAX_ENTRIES:\n break\n\n if len(current_batch) == BATCH_SIZE:\n save_batch(current_batch, TARGET_DIR)\n current_batch = []\n\n if len(current_batch) > 0:\n save_batch(current_batch, TARGET_DIR)\n","repo_name":"westoun/iconclass","sub_path":"iconclass_extraction/extract_text_to_annotate.py","file_name":"extract_text_to_annotate.py","file_ext":"py","file_size_in_byte":2283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"33"} +{"seq_id":"69897514335","text":"import pandas as pd\nimport numpy as np\nfrom matplotlib.pylab import *\nimport matplotlib.cm as cm\n\nxl_file = pd.ExcelFile('P:/Dropbox/TrungVu/GaussianProcessSGD/Airline/airline_results_gpy.xlsx')\n\ndfs = {sheet_name: xl_file.parse(sheet_name)\n for sheet_name in xl_file.sheet_names}\n\nu = np.array(dfs['vary_u_2008']['u'])\ntime = np.array(dfs['vary_u_2008']['time'])\ntest_rmse = np.array(dfs['vary_u_2008']['test_rmse'])\n\ncolors = [\"#3498db\", \"#e74c3c\", \"#2ecc71\"]\n\nfig, ax1 = plt.subplots()\nfig.set_size_inches(18.5, 3.5)\nax = fig.gca()\n#ax1.set_xticks(np.arange(min(D), max(D), (max(D) - min(D)/20)))\n#ax1.set_yticks(np.arange(min(time), max(time), (max(time) - min(time)/20)))\n#ax1.grid()\nr2 = 2753.61500001\n\nlns1 = ax1.plot(u, time, label=\"Time of SGP-SVI\", marker='o', color=colors[0])\n#ax1.errorbar(D, time, yerr=terr, fmt='b')\nax1.set_xlabel('u')\n# Make the y-axis label and tick labels match the line color.\n\nax1_ytick = ax1.get_yticks()\nax1_ylabel = ax1.get_yticklabels()\n\n#ax1_ylabel[0] = '120'\nax1.set_yticks((2000,r2,4000,6000,8000,10000,12000,14000))\n#ax.set_yticklabels(ax1_ylabel)\n\nax1.set_ylabel('Time (s)', color=colors[0])\nfor tl in ax1.get_yticklabels():\n tl.set_color(colors[0])\n\nfor i in xrange(7):\n x = i*100+200\n y = i*2000+2000\n ax1.plot([x,x],[0,14000],':',linewidth=1, color='black')\n ax1.plot([100,800],[y,y],':',linewidth=1, color='black')\n\nax2 = ax1.twinx()\nr1 = 37.64\nax2.plot([120,120],[0,r1],'go--',linewidth=1, color='black')\nax2.plot([800,120],[r1,r1],'+--',linewidth=1, color='black')\n\n\nlns2 = ax2.plot(u, test_rmse, label=\"RMSE of SGP-SVI\", marker='o', color=colors[1])\nlns3 = ax2.plot(120, r1, label=\"RMSE of GOGP\", marker='s',color=colors[1])\n# lns3b = ax2.plot(120, 34.7602, label=\"RMSE of GOGP\", marker='s', markersize=15,color=colors[1])\n\n\nax1.plot([120,100],[r2,r2],'+--',linewidth=1, color='black')\nlns4 = ax1.plot(120, r2, label=\"Time of GOGP\", marker='s',color=colors[0])\n# lns4b = ax1.plot(120, 331, label=\"Time of GOGP\", marker='s', markersize=15,color=colors[0])\n\nax2_ytick = ax2.get_yticks()\nax2_ylabel = ax2.get_yticklabels()\nnp.insert(ax2_ytick,1,r1)\n#ax1_ylabel[0] = '120'\nax2.set_yticks((30,32,34,36,r1,38,40))\n\nax2.set_xticks((100, 120, 200, 300, 400, 500, 600, 700, 800))\nax2.set_xticklabels(('', '120', '200', '300', '400', '500', '600', '700', '800'))\n# ax1.set_yscale('log')\n\n#ax2.errorbar(D, acc, yerr=aerr, fmt='r')\nax2.set_ylabel('RMSE', color=colors[1])\nax2.set_ylim(30,40)\nfor tl in ax2.get_yticklabels():\n tl.set_color(colors[1])\n\n\n\nlns = lns1+lns4+lns2+lns3\nlabs = [l.get_label() for l in lns]\nax1.legend(lns, labs, loc=4)\n\n#plt.savefig('Dvaried_uspst.pdf', bbox_inches='tight')\n\nplt.show()","repo_name":"khanhndk/libplot","sub_path":"complexity.py","file_name":"complexity.py","file_ext":"py","file_size_in_byte":2679,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"30617970656","text":"# -*- coding: utf-8 -*-\nimport tensorflow as tf\nimport numpy as np\n\n# Linear Regression5\n# 여러개의 파일에서 데이터 불러오기. 파일의 개수가 많으면 메모리에 못담으니까 queue이용한다\n\nfilename_queue = tf.train.string_input_producer([\"./data-01-test-score.csv\"], shuffle=False, name=\"filename_queue\")\nreader = tf.TextLineReader()\nkey, value = reader.read(filename_queue)\n\nrecord_defaults = [[0.], [0.], [0.], [0.]]\nxy = tf.decode_csv(value, record_defaults=record_defaults)\n\ntrain_x_batch, train_y_batch = tf.train.batch([xy[0:-1], xy[-1:]], batch_size=10)\n\nX = tf.placeholder(tf.float32, shape=[None, 3])\nY = tf.placeholder(tf.float32, shape=[None, 1])\n\n# tesnorflow가 자체적으로 변경시키는 변수. variable\n# random_normal은 shape만 지정해주고 아무 값이나 선정\nW = tf.Variable(tf.random_normal([3, 1]), name=\"weight\")\nb = tf.Variable(tf.random_normal([1]), name=\"bias\")\n\nhypothesis = tf.matmul(X, W) + b\n\ncost = tf.reduce_mean(tf.square(hypothesis - Y))\n\noptimizer = tf.train.GradientDescentOptimizer(learning_rate=1e-5)\ntrain = optimizer.minimize(cost)\n\n\n# 세션에 그래프를 launch시킨다\nsess = tf.Session()\n# W, b와 같은 variable을 미리 초기화한다 !!\nsess.run(tf.global_variables_initializer())\n\n# start populating the filename queue\ncoord = tf.train.Coordinator()\nthreads = tf.train.start_queue_runners(sess=sess, coord=coord)\n\nfor step in range(2000):\n X_batch, Y_batch = sess.run([train_x_batch, train_y_batch])\n cost_val, hy_val, _ = sess.run([cost, hypothesis, train], feed_dict={X:X_batch, Y:Y_batch})\n if step % 10 == 0:\n print(step, \"cost : \", cost_val, \"\\nhypothesis : \\n\", hy_val)\n\ncoord.request_stop()\ncoord.join(threads)","repo_name":"willthd/Machine-Learning","sub_path":"deep/linearRegression/linearRegression5.py","file_name":"linearRegression5.py","file_ext":"py","file_size_in_byte":1730,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"20641250237","text":"import matplotlib\r\nmatplotlib.use('Qt5Agg')\r\nfrom matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas\r\nfrom matplotlib.ticker import MultipleLocator \r\nfrom PyQt5 import QtCore, QtWidgets,QtGui\r\nfrom PyQt5.QtCore import Qt\r\nfrom PyQt5.QtWidgets import QLabel,QMainWindow, QTableWidget, QTableWidgetItem, QWidget, QSpinBox, QGroupBox, QSlider\r\nfrom PyQt5.QtWidgets import QFormLayout, QDockWidget, QComboBox, QHBoxLayout, QPushButton, QTextEdit, QAction, QApplication, QDesktopWidget, QRadioButton\r\nfrom PyQt5.QtGui import QIcon\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as patches\r\nfrom matplotlib.figure import Figure\r\nimport sys\r\nimport numpy as np\r\nimport random\r\nimport time\r\n\r\nclass My_Main_window(QtWidgets.QDialog):\r\n def __init__(self,parent=None):\r\n \r\n super(My_Main_window,self).__init__(parent)\r\n\r\n # set the User Interface\r\n self.setWindowTitle('NN')\r\n self.resize(750, 400)\r\n\r\n # set the figure (left&right)\r\n self.figure_1 = Figure(figsize=(4, 4), dpi=100)\r\n self.canvas_1 = FigureCanvas(self.figure_1)\r\n\r\n # draw the initial axes of left graph\r\n self.ax_1 = self.figure_1.add_axes([0.1,0.1,0.8,0.8])\r\n self.ax_1.set_xlim([0,5])\r\n self.ax_1.set_ylim([0,5])\r\n self.ax_1.plot()\r\n\r\n # set the group box\r\n self.file = QGroupBox(\"Choose Train and Test File\")\r\n self.association = QGroupBox(\"Choose Association Way\")\r\n self.show_data = QGroupBox(\"Choose Show Data\")\r\n self.show_result = QGroupBox(\"Result of Association\")\r\n\r\n # set the push button\r\n self.button_test = QPushButton(\"Test\")\r\n self.button_train = QPushButton(\"Train\")\r\n self.button_show = QPushButton(\"Show the Graph\")\r\n self.button_original = QPushButton(\"Original Graph\")\r\n self.button_association = QPushButton(\"Association Graph\")\r\n\r\n # set the combo box\r\n self.combo_train = QComboBox()\r\n self.combo_test = QComboBox()\r\n self.combo_train.addItems([\"Basic_Training.txt\", \"Bonus_Training.txt\"])\r\n self.combo_test.addItems([\"Basic_Testing.txt\", \"Bonus_Testing.txt\"])\r\n \r\n # set the label\r\n self.label_train_file=QLabel()\r\n self.label_test_file=QLabel()\r\n self.label_train_data=QLabel()\r\n self.label_test_data=QLabel()\r\n self.label_correct_rate=QLabel()\r\n self.label_correct_text=QLabel()\r\n self.label_iteration_time=QLabel()\r\n self.label_iteration_text=QLabel()\r\n self.label_train_file.setText(\"Train File\")\r\n self.label_test_file.setText(\"Test File\")\r\n self.label_train_data.setText(\"Train Data No.\")\r\n self.label_test_data.setText(\"Test Data No.\")\r\n self.label_correct_rate.setText(\"Correct Rate\")\r\n self.label_correct_text.setText(\" -- \")\r\n self.label_iteration_time.setText(\"Iteration Time\")\r\n self.label_iteration_text.setText(\" -- \")\r\n self.label_correct_text.setAlignment(Qt.AlignCenter)\r\n self.label_iteration_text.setAlignment(Qt.AlignCenter)\r\n\r\n # set the button trigger\r\n self.button_show.clicked.connect(self.ShowResult)\r\n self.button_train.clicked.connect(self.TrainData)\r\n self.button_test.clicked.connect(self.TestData)\r\n self.button_original.clicked.connect(self.ShowOriginal)\r\n self.button_association.clicked.connect(self.ShowAssociation)\r\n\r\n # set the combobox trigger\r\n self.combo_train.activated.connect(self.SetTrainFile)\r\n self.combo_test.activated.connect(self.SetTestFile)\r\n \r\n # set the radio button\r\n self.radio_syn=QRadioButton(\"Synchronization\")\r\n self.radio_asyn=QRadioButton(\"Asynchronization\")\r\n self.radio_train=QRadioButton(\"Train Data\")\r\n self.radio_test=QRadioButton(\"Test Data\")\r\n self.radio_syn.setChecked(True)\r\n self.radio_asyn.setChecked(False)\r\n self.radio_train.setChecked(True)\r\n self.radio_test.setChecked(False)\r\n\r\n # set the spin box\r\n self.spin_train=QSpinBox()\r\n self.spin_test=QSpinBox()\r\n\r\n # set the layout\r\n layout = QtWidgets.QHBoxLayout()\r\n layout_left = QtWidgets.QVBoxLayout()\r\n layout_right = QtWidgets.QVBoxLayout()\r\n layout_right_down = QtWidgets.QHBoxLayout()\r\n file_layout = QFormLayout()\r\n association_layout = QFormLayout()\r\n show_layout = QFormLayout()\r\n result_layout = QFormLayout()\r\n\r\n file_layout.addRow(self.label_train_file, self.combo_train)\r\n file_layout.addRow(self.label_test_file, self.combo_test)\r\n\r\n association_layout.addRow(self.radio_syn, self.radio_asyn)\r\n association_layout.addRow(self.button_train, self.button_test)\r\n\r\n show_layout.addRow(self.radio_train, self.radio_test)\r\n show_layout.addRow(self.label_train_data, self.spin_train)\r\n show_layout.addRow(self.label_test_data, self.spin_test)\r\n\r\n result_layout.addRow(self.label_correct_rate, self.label_correct_text)\r\n result_layout.addRow(self.label_iteration_time, self.label_iteration_text)\r\n\r\n self.file.setLayout(file_layout)\r\n self.association.setLayout(association_layout)\r\n self.show_data.setLayout(show_layout)\r\n self.show_result.setLayout(result_layout)\r\n \r\n layout_left.addWidget(self.file)\r\n layout_left.addWidget(self.association)\r\n layout_left.addWidget(self.show_data)\r\n layout_left.addWidget(self.show_result)\r\n layout_left.addWidget(self.button_show)\r\n\r\n layout_right_down.addWidget(self.button_original)\r\n layout_right_down.addWidget(self.button_association)\r\n\r\n layout_right.addWidget(self.canvas_1)\r\n layout_right.addLayout(layout_right_down)\r\n\r\n layout.addLayout(layout_left,10)\r\n layout.addLayout(layout_right,42)\r\n \r\n self.setLayout(layout)\r\n\r\n # process the train input and calculate the weight & theta matrix\r\n def SetTrainFile(self):\r\n self.train_input=[]\r\n f=open(self.combo_train.currentText())\r\n self.train_count=int(1) \r\n self.row=int(0)\r\n\r\n self.train_input.append([])\r\n while 1:\r\n line=f.readline()\r\n if line==\"\":\r\n break\r\n \r\n line=line[:len(line)].strip(\"\\n\")\r\n if len(line) == 0 :\r\n self.train_input.append([])\r\n if self.train_count == 1:\r\n self.col=int(len(self.train_input[self.train_count-1])/self.row)\r\n self.train_count=self.train_count+1\r\n else :\r\n if self.train_count == 1:\r\n self.row+=1\r\n for i in range(len(line)):\r\n if line[i] == '1':\r\n self.train_input[self.train_count-1].append(int(1))\r\n else:\r\n self.train_input[self.train_count-1].append(int(-1))\r\n\r\n self.dim = int(len(self.train_input[0]))\r\n self.weight = []\r\n self.theta = []\r\n\r\n for i in range(self.dim):\r\n self.weight.append([])\r\n for j in range(self.dim):\r\n self.weight[i].append(int(0))\r\n for k in range(self.train_count):\r\n self.weight[i][j]=self.weight[i][j]+(self.train_input[k][i] * self.train_input[k][j])\r\n ## weight[i][j]=float(weight[i][j]/dim)\r\n\r\n for i in range(self.dim):\r\n self.weight[i][i]=self.weight[i][i]-self.train_count\r\n\r\n self.theta = np.zeros((self.dim,), dtype=np.int)\r\n ## self.theta = np.sum(self.weight, 1)\r\n\r\n self.spin_train.setRange(1,self.train_count)\r\n\r\n # process the test input\r\n def SetTestFile(self):\r\n self.test_input = []\r\n f=open(self.combo_test.currentText())\r\n self.test_count=int(1)\r\n\r\n self.test_input.append([])\r\n while 1:\r\n line=f.readline()\r\n if line==\"\":\r\n break\r\n \r\n line=line[:len(line)].strip(\"\\n\")\r\n if len(line) == 0 :\r\n self.test_input.append([])\r\n self.test_count+=1\r\n else :\r\n for i in range(len(line)):\r\n if line[i] == '1':\r\n self.test_input[self.test_count-1].append(int(1))\r\n else:\r\n self.test_input[self.test_count-1].append(int(-1))\r\n \r\n self.spin_test.setRange(1,self.test_count)\r\n\r\n # calculate the association of train data\r\n def TrainData(self):\r\n self.train_output = []\r\n self.train_time = []\r\n self.train_rate = []\r\n\r\n # Synchronization\r\n if self.radio_syn.isChecked() :\r\n for z in range(self.train_count):\r\n temp = np.copy(self.train_input[z])\r\n run_time = int(0)\r\n similar=int(0)\r\n correct_rate=float(0)\r\n while (similar != self.dim) :\r\n similar=int(0)\r\n sigmoid_data = []\r\n run_time+=1\r\n \r\n for i in range(self.dim):\r\n sigmoid_data.append(np.dot(self.weight[i], temp) - self.theta[i])\r\n \r\n for i in range(self.dim):\r\n if sigmoid_data[i] < int(0):\r\n if temp[i] == int(-1):\r\n similar+=1\r\n else:\r\n temp[i]=int(-1)\r\n elif sigmoid_data[i] > int(0):\r\n if temp[i] == int(1):\r\n similar+=1\r\n else:\r\n temp[i]=int(1)\r\n else:\r\n similar+=1\r\n \r\n for i in range(self.dim):\r\n if temp[i] == self.train_input[z][i]:\r\n correct_rate+=1\r\n\r\n self.train_output.append(temp)\r\n self.train_time.append(run_time)\r\n self.train_rate.append(correct_rate/self.dim)\r\n\r\n # Asynchronization\r\n else:\r\n for z in range(self.train_count):\r\n temp = np.copy(self.train_input[z])\r\n run_time = int(0)\r\n similar=True\r\n correct_rate=float(0)\r\n while similar:\r\n similar=False\r\n sigmoid_data = np.copy(temp)\r\n run_time+=1\r\n\r\n for i in range(self.dim):\r\n res = np.dot(self.weight[i], sigmoid_data) - self.theta[i]\r\n if res < int(0):\r\n sigmoid_data[i]=int(-1)\r\n elif res > int(0):\r\n sigmoid_data[i]=int(1)\r\n\r\n for i in range(self.dim):\r\n if sigmoid_data[i] != temp[i]:\r\n similar = True\r\n \r\n temp=np.copy(sigmoid_data)\r\n\r\n for i in range(self.dim):\r\n if temp[i] == self.train_input[z][i]:\r\n correct_rate+=1\r\n\r\n self.train_output.append(temp)\r\n self.train_time.append(run_time)\r\n self.train_rate.append(correct_rate/self.dim)\r\n \r\n # calculate the association of test data\r\n def TestData(self):\r\n self.test_output = []\r\n self.test_time = []\r\n self.test_rate = []\r\n\r\n # Synchronization\r\n if self.radio_syn.isChecked() :\r\n for z in range(self.test_count):\r\n temp = np.copy(self.test_input[z])\r\n run_time = int(0)\r\n similar=int(0)\r\n correct_rate=float(0)\r\n while (similar != self.dim) :\r\n similar=int(0)\r\n sigmoid_data = []\r\n run_time+=1\r\n \r\n for i in range(self.dim):\r\n sigmoid_data.append(np.dot(self.weight[i], temp) - self.theta[i])\r\n \r\n for i in range(self.dim):\r\n if sigmoid_data[i] < int(0):\r\n if temp[i] == int(-1):\r\n similar+=1\r\n else:\r\n temp[i]=int(-1)\r\n elif sigmoid_data[i] > int(0):\r\n if temp[i] == int(1):\r\n similar+=1\r\n else:\r\n temp[i]=int(1)\r\n else:\r\n similar+=1\r\n\r\n for i in range(self.dim):\r\n if temp[i] == self.train_input[z][i]:\r\n correct_rate+=1\r\n \r\n self.test_output.append(temp)\r\n self.test_time.append(run_time)\r\n self.test_rate.append(correct_rate/self.dim)\r\n\r\n # Asynchronization\r\n else:\r\n for z in range(self.test_count):\r\n temp = np.copy(self.test_input[z])\r\n run_time = int(0)\r\n similar=True\r\n correct_rate=float(0)\r\n while similar:\r\n similar=False\r\n sigmoid_data = np.copy(temp)\r\n run_time+=1\r\n\r\n for i in range(self.dim):\r\n res = np.dot(self.weight[i], sigmoid_data) - self.theta[i]\r\n if res < int(0):\r\n sigmoid_data[i]=int(-1)\r\n elif res > int(0):\r\n sigmoid_data[i]=int(1)\r\n\r\n for i in range(self.dim):\r\n if sigmoid_data[i] != temp[i]:\r\n similar = True\r\n \r\n temp=np.copy(sigmoid_data)\r\n\r\n for i in range(self.dim):\r\n if temp[i] == self.train_input[z][i]:\r\n correct_rate+=1\r\n\r\n self.test_output.append(temp)\r\n self.test_time.append(run_time)\r\n self.test_rate.append(correct_rate/self.dim)\r\n\r\n # show the original graph\r\n def ShowOriginal(self):\r\n spacing = 1\r\n minorLocator = MultipleLocator(spacing)\r\n self.ax_1.cla()\r\n self.ax_1.set_xlim([0,self.col])\r\n self.ax_1.set_ylim([0,self.row])\r\n self.ax_1.set_title(\"Original Graph\")\r\n self.ax_1.plot()\r\n self.ax_1.xaxis.set_minor_locator(minorLocator) \r\n self.ax_1.yaxis.set_minor_locator(minorLocator) \r\n self.ax_1.grid(which='minor')\r\n for i in range(self.row):\r\n for j in range(self.col):\r\n if self.graph_original[i*self.col + j] == int(1):\r\n self.ax_1.add_patch(\r\n patches.Rectangle(\r\n (j, self.row-i-1), # (x,y)\r\n 1, # width\r\n 1, # height\r\n )\r\n )\r\n self.canvas_1.draw()\r\n\r\n # show the association graph\r\n def ShowAssociation(self):\r\n spacing = 1\r\n minorLocator = MultipleLocator(spacing)\r\n self.ax_1.cla()\r\n self.ax_1.set_xlim([0,self.col])\r\n self.ax_1.set_ylim([0,self.row])\r\n self.ax_1.set_title(\"Association Graph\")\r\n self.ax_1.plot()\r\n self.ax_1.xaxis.set_minor_locator(minorLocator) \r\n self.ax_1.yaxis.set_minor_locator(minorLocator) \r\n self.ax_1.grid(which='minor')\r\n for i in range(self.row):\r\n for j in range(self.col):\r\n if self.graph_result[i*self.col + j] == int(1):\r\n self.ax_1.add_patch(\r\n patches.Rectangle(\r\n (j, self.row-i-1), # (x,y)\r\n 1, # width\r\n 1, # height\r\n )\r\n )\r\n self.canvas_1.draw()\r\n\r\n # process the original & association graph \r\n def ShowResult(self):\r\n index = int(0)\r\n self.graph_original = []\r\n self.graph_result = []\r\n\r\n if self.radio_train.isChecked():\r\n index = self.spin_train.value()-1\r\n self.label_correct_text.setText(str(self.train_rate[index]))\r\n self.label_iteration_text.setText(str(self.train_time[index]))\r\n self.graph_original = np.copy(self.train_input[index])\r\n self.graph_result = np.copy(self.train_output[index])\r\n else:\r\n index = self.spin_test.value()-1\r\n self.label_correct_text.setText(str(self.test_rate[index]))\r\n self.label_iteration_text.setText(str(self.test_time[index]))\r\n self.graph_original = np.copy(self.test_input[index])\r\n self.graph_result = np.copy(self.test_output[index])\r\n\r\n spacing = 1\r\n minorLocator = MultipleLocator(spacing)\r\n self.ax_1.cla()\r\n self.ax_1.set_title(\"Original Graph\")\r\n self.ax_1.set_xlim([0,self.col])\r\n self.ax_1.set_ylim([0,self.row])\r\n self.ax_1.plot()\r\n self.ax_1.xaxis.set_minor_locator(minorLocator) \r\n self.ax_1.yaxis.set_minor_locator(minorLocator) \r\n self.ax_1.grid(which='minor')\r\n for i in range(self.row):\r\n for j in range(self.col):\r\n if self.graph_original[i*self.col + j] == int(1):\r\n self.ax_1.add_patch(\r\n patches.Rectangle(\r\n (j, self.row-i-1), # (x,y)\r\n 1, # width\r\n 1, # height\r\n )\r\n )\r\n self.canvas_1.draw()\r\n\r\nif __name__ == '__main__':\r\n app = QtWidgets.QApplication(sys.argv)\r\n main_window = My_Main_window()\r\n main_window.show()\r\n app.exec()\r\n","repo_name":"Zane2453/Neural-Networks_Hopfield-Neural-Network","sub_path":"HW_3.py","file_name":"HW_3.py","file_ext":"py","file_size_in_byte":18246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"1018138881","text":"from django.contrib import admin\nfrom .models import UserProfile\n\n# Register your models here.\nclass UserProfileAdmin(admin.ModelAdmin):\n list_display = [\n 'user',\n 'city',\n 'phone',\n 'user_info',\n ]\n\n def user_info(self, obj):\n return obj.desc\n\n def get_queryset(self, request):\n queryset = super(UserProfileAdmin, self).get_queryset(request)\n queryset = queryset.order_by('-city', 'user')\n return queryset\n\n\n\nadmin.site.register(UserProfile, UserProfileAdmin)\n\n# # Changing the django admin page - changed it in the template \n# admin.site.site_header = 'Administration'\n\n\n","repo_name":"gurashish1singh/maxG_Django","sub_path":"tutorial/accounts/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"36458046912","text":"from django.conf.urls import patterns, include, url\n\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('',\n # Examples:\n # url(r'^$', 'bookmaps.views.home', name='home'),\n # url(r'^blog/', include('blog.urls')),\n\n url(r'^admin/', include(admin.site.urls)),\n url(r'^$', 'bookmapsapp.views.bookmap', name = 'bookmap'),\n url(r'^get_data/$', 'bookmapsapp.views.get_data', name='get_data'),\n url(r'^add_book/$', 'bookmapsapp.views.add_book', name='add_book'),\n url(r'^add_place_time/$', 'bookmapsapp.views.add_place_time', name='add_place_time')\n)\n","repo_name":"mathhomework/bookmaps","sub_path":"bookmaps/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"34952383890","text":"#!/usr/bin/python3\n\"\"\" the class Square that inherits from Rectangle \"\"\"\nfrom models.rectangle import Rectangle\n\n\nclass Square(Rectangle):\n \"\"\" a square \"\"\"\n def __init__(self, size, x=0, y=0, id=None):\n super().__init__(size, size, x, y, id)\n\n @property\n def size(self):\n return self.__width\n\n @size.setter\n def size(self, value):\n if type(value) is not int:\n raise TypeError(\"width must be an integer\")\n elif value <= 0:\n raise ValueError(\"width must be > 0\")\n else:\n self.__width = value\n self.__height = value\n\n def update(self, *args, **kwargs):\n \"\"\" assigns an assignment to each attribute \"\"\"\n attributes = [\"id\", \"size\", \"x\", \"y\"]\n if args is not None and len(args) > 0:\n for attr, value in zip(attributes, args):\n if attr == \"size\":\n self.__width = value\n self.__height = value\n else:\n setattr(self, attr, value)\n elif kwargs is not None:\n for key, value in kwargs.items():\n if key == \"size\":\n self.__width = value\n self.__height = value\n else:\n setattr(self, key, value)\n\n def to_dictionary(self):\n \"\"\" returns the dictionary representation of a Square \"\"\"\n return {\n \"id\": self.id,\n \"size\": self.width,\n \"x\": self.x,\n \"y\": self.y\n }\n\n def __str__(self):\n \"\"\" it returns info about the square \"\"\"\n return \"[Square] ({}) {}/{} - {}\".format(\n self.id, self.x, self.y, self.width)\n","repo_name":"krisCrossApplesauce/holbertonschool-higher_level_programming","sub_path":"python-almost_a_circle/models/square.py","file_name":"square.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"73979513695","text":"\"\"\"\nTools for working with `PyTorch Lightning `_.\n\n.. _PL: https://www.pytorchlightning.ai/\n\"\"\"\n\nimport io\nimport logging\nimport os\nimport warnings\nfrom pathlib import Path\n\nfrom torch.functional import Tensor\n\ntry:\n import ipywidgets as widgets # type: ignore\nexcept ImportError:\n warnings.warn(\"Could not import ipywidgets. Some functionality won't work\")\n widgets = None\n\nimport imageio\nimport numpy as np\nimport pytorch_lightning as pl\nimport torch\nfrom IPython.display import Image, display\nfrom torchvision import transforms as T\nfrom torchvision.utils import make_grid\n\n_LOG = logging.getLogger(__name__)\n\n\nclass ImageCheckpoint(pl.Callback):\n \"\"\"\n A PyTorch Lightning callback for saving and previewing images.\n\n Image batches (b, c, h, w) should be generated by\n `module.forward()`.\n \"\"\"\n\n def __init__(\n self,\n path_template: str,\n video_path: str = None,\n interval=50,\n preview: bool = True,\n ):\n \"\"\"\n `path_template` can draw on the following variables:\n\n - `index`: the index of the image in the provided batch\n - `model`: the Lightning model\n - `trainer`: the Lightning trainer\n\n Args:\n path_template (str): a path template as described above\n interval (int, optional): the checkpoint interval\n preview (bool, optional): if true display an ipywidget preview\n panel. Defaults to True.\n \"\"\"\n super().__init__()\n self.path_template = str(path_template)\n self.interval = interval\n self._last_checkpoint_step = None\n self._preview = None\n self._video_writer = None\n\n _LOG.info(\n f\"Checkpointing images to {self.path_template} every {self.interval} steps\"\n )\n\n if video_path is not None:\n Path(video_path).parent.mkdir(parents=True, exist_ok=True)\n self._video_writer = imageio.get_writer(video_path)\n _LOG.info(f\"Writing video to {video_path}\")\n\n if preview:\n self._preview = widgets.Output()\n display(self._preview)\n\n def save(self, batch: Tensor, trainer: \"pl.Trainer\", module: \"pl.LightningModule\"):\n \"\"\"Save the image batch.\"\"\"\n if batch.shape[0] > 1 and \"{index}\" not in self.path.template:\n warnings.warn(\"Image batch size > 1, but template doesn't use {index}.\")\n batch = make_grid(batch, nrow=4, padding=10)\n\n for i in range(batch.shape[0]):\n img = T.functional.to_pil_image(batch[i, :])\n filename = Path(\n str.format(self.path_template, module=module, trainer=trainer, index=i)\n )\n os.makedirs(filename.parent, exist_ok=True)\n img.save(filename)\n _LOG.info(f\"Saved image as {filename}\")\n\n def save_frame(self, batch: Tensor):\n if self._video_writer is None:\n return\n img = T.functional.to_pil_image(batch[0, :])\n img = np.array(img)\n self._video_writer.append_data(img)\n\n def preview(self, batch: Tensor):\n \"\"\"Preview the image batch if configured, otherwise do nothing.\"\"\"\n if not self._preview:\n return\n img = T.functional.to_pil_image(make_grid(batch, nrow=4, padding=10))\n # Workaround https://github.com/jupyter-widgets/ipywidgets/issues/3003\n b = io.BytesIO()\n img.save(b, format=\"PNG\")\n img = Image(b.getvalue())\n\n # In principle could call clear_output. In practice the following works\n # better. See: \n self._preview.outputs = []\n self._preview.append_display_data(img)\n\n def checkpoint(self, trainer: \"pl.Trainer\", module: \"pl.LightningModule\"):\n \"\"\"Main checkpoint function, called on epoch start and training end.\"\"\"\n if trainer.global_step == self._last_checkpoint_step:\n return\n\n with torch.no_grad():\n module.eval()\n img = module.forward()\n module.train()\n\n self.save(img, trainer, module)\n self.save_frame(img)\n self.preview(img)\n self._last_checkpoint_step = trainer.global_step\n\n def on_batch_end(self, trainer: \"pl.Trainer\", module: \"pl.LightningModule\") -> None:\n \"\"\"\n Called at the end of each batch.\n\n Checkpoints if a multiple of `self.interval`.\n \"\"\"\n if (trainer.global_step % self.interval) == 0:\n self.checkpoint(trainer, module)\n\n def on_epoch_start(self, trainer: \"pl.Trainer\", module: \"pl.LightningModule\"):\n \"\"\"\n Called at the start of an epoch.\n\n Always checkpoints.\n \"\"\"\n self.checkpoint(trainer, module)\n\n def on_train_end(self, trainer: \"pl.Trainer\", module: \"pl.LightningModule\"):\n \"\"\"\n Called when training ends.\n\n Always checkpoints.\n \"\"\"\n _LOG.info(\"Shutting down ImageCheckpoint\")\n self.checkpoint(trainer, module)\n if self._video_writer is not None:\n self._video_writer.close()\n","repo_name":"joehalliwell/paraphernalia","sub_path":"paraphernalia/torch/lightning.py","file_name":"lightning.py","file_ext":"py","file_size_in_byte":5093,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"70778940575","text":"# -*- coding: utf-8 -*-\n\nfrom nsub import log_my, savetofile, list_key\nfrom common import *\nimport xbmcgui\nvalues = {'q': '','type': 'downloads_file','search_and_or': 'or','search_in': 'titles','sortby': 'relevancy'}\n\nheaders = {\n 'Upgrade-Insecure-Requests' : '1',\n 'User-Agent' : 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/60.0.3112.101 Safari/537.36',\n 'Content-Type' : 'application/x-www-form-urlencoded',\n 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3',\n 'Accept-Encoding': 'gzip, deflate',\n 'Referer' : 'http://www.easternspirit.org/forum/index.php?/files/',\n 'Accept-Language' : 'en-US,en;q=0.8'\n}\n\nurl = 'http://www.easternspirit.org/forum'\n\n\ndef get_id_url_n(txt, list):\n soup = BeautifulSoup(txt, 'html5lib')\n for link in soup.find_all(\"span\", class_=\"ipsContained ipsType_break\"):\n #print link\n href = link.find('a', href=True)\n title = link.getText()\n title = re.sub('[\\r\\n]+','',title)\n yr = re.search('.*\\((\\d+)',title).group(1)\n title = re.sub(' \\(.*\\s+','',title)\n \n list.append({'url': href['href'].encode('utf-8', 'replace'),\n 'info': title.encode('utf-8', 'replace'),\n 'year': yr.encode('utf-8', 'replace'),\n 'cds': '',\n 'fps': '',\n 'rating': '0.0',\n 'id': __name__})\n return\n\ndef get_data(l, key):\n out = []\n for d in l:\n out.append(d[key])\n return out\n\ndef read_sub (mov):\n list = []\n\n values['q'] = mov\n enc_values = urllib.urlencode(values)\n request = urllib2.Request(url + '/index.php?/search/&'+enc_values.replace('+','%20'), None, headers)\n\n response = urllib2.urlopen(request)\n log_my(response.code)\n\n\n if response.info().get('Content-Encoding') == 'gzip':\n buf = StringIO(response.read())\n f = gzip.GzipFile(fileobj=buf)\n data = f.read()\n f.close()\n buf.close()\n else:\n log_my('Error: ', response.info().get('Content-Encoding'))\n return None\n\n get_id_url_n(data, list)\n #if run_from_xbmc == False:\n for k in list_key:\n d = get_data(list, k)\n log_my(d)\n\n return list\n\n\n \ndef getResult(subs):\n IDs = [i[1] for i in subs]\n displays = [i[0] for i in subs]\n idx = xbmcgui.Dialog().select('Select subs',displays)\n if idx < 0: return None\n return IDs[idx]\n \ndef get_sub(id, sub_url, filename):\n request = urllib2.Request(sub_url, None, headers)\n response = urllib2.urlopen(request)\n mycook = response.info().get('Set-Cookie')\n if response.info().get('Content-Encoding') == 'gzip':\n buf = StringIO(response.read())\n f = gzip.GzipFile(fileobj=buf)\n data = f.read()\n f.close()\n buf.close()\n else:\n data = response.read()\n log_my('Error: ', response.info().get('Content-Encoding'))\n match = re.findall(\"([^<>]+)<.+?a href='([^']+)'\", data2)\n sub_url = getResult(match)\n request = urllib2.Request(sub_url, None, dheaders)\n request.add_header('Cookie',mycook)\n response = urllib2.urlopen(request)\n log_my(response.code, BaseHTTPServer.BaseHTTPRequestHandler.responses[response.code][0])\n s['data'] = response.read()\n s['fname'] = response.info()['Content-Disposition'].split('filename=')[1].strip('\"')\n return s\n","repo_name":"ByJohnie/service.subtitles.modedbg","sub_path":"resources/lib/easternspirit.py","file_name":"easternspirit.py","file_ext":"py","file_size_in_byte":5007,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"33"} +{"seq_id":"22864987159","text":"import termios\nimport tty\nimport sys\nimport select\n\"\"\"Self-made console input library. Prolly shit\"\"\"\n\ndef isData(): #| Checks if there is any console input\n\t\"\"\"Checks if there is any console\n\tinput. Might only work with Linux\"\"\"\n\treturn select.select([sys.stdin], [], [], 0) == ([sys.stdin], [], [])\n\ndef passiveInput(): #| Only works for arrows\n\t\"\"\"Will return 'None' if no input\n\tis given, otherwise will retrieve\n\tARROW input\"\"\"\n\n\told_settings = termios.tcgetattr(sys.stdin)\n\ttry:\n\t\ttty.setcbreak(sys.stdin.fileno())\n\t\tif isData(): return get_arrow()\n\t\telse: return None\n\tfinally:\n\t\ttermios.tcsetattr(sys.stdin, termios.TCSADRAIN, old_settings)\n\ndef get_arrow(): #| Kinda janky. Think this would only work for bash\n\t\"\"\"Function that will handle arrow input.\n\tI'm not sure if it won't be janky sometimes;\n\talso might only work with bash! Also, due to\n\tsome tinkering, might only work after setting\n\tup tty.setcbreak(sys.stdin.fileno()) and the\n\tother stuff\"\"\"\n\n\twhile True:\n\t\tsys.stdin.read(1) #| Eat space generated by arrow keys\n\t\tdirect = sys.stdin.read(2)\n\t\tif direct != '': break;\n\tif direct == \"[A\": #| Up\n\t\treturn 1\n\telif direct == \"[C\": #| Right\n\t\treturn 2\n\telif direct == \"[B\": #| Down\n\t\treturn 3\n\telif direct == \"[D\": #| Left\n\t\treturn 4\n\telse: sys.exit(\"Arrow key input error\") #| If you have to handle a non-arrow key, don't\n\n","repo_name":"TheLadd/python_snake","sub_path":"inputs.py","file_name":"inputs.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"72924944734","text":"import requests\nimport json\nimport time\nimport aiohttp\nimport asyncio\n\nstart = time.time()\n\nclient_id = \"ALECV5CBBEHRRKTIQ5ZV143YEXOH3SBLAMU54SPHKGZI1ZKE\"\nclient_secret = \"3JX3NRGRS2P0KE0NSKPTMCOZOY4MWUU4M3G33BO4XTRJ15SM\"\ndate = \"20190407\"\n\nasync def fetch(url, params = {}):\n async with aiohttp.ClientSession() as session:\n async with session.get(url, params = params) as response:\n return await response.text()\n\nterms = [\"pizza\", \"tacos\", \"ice cream\", \"italian\", \"chinese\", \"korean\"]\n\ndef get_venues_search(term):\n url = \"https://api.foursquare.com/v2/venues/search\"\n params = {\"ll\": \"40.7,-74\", \"query\": \"tacos\", \n \"client_id\": client_id, \"client_secret\": client_secret, \"v\": date}\n \n\nend = time.time()\nprint(end - start)","repo_name":"apis-jigsaw/async-foursquare-requests-lab","sub_path":"codebase/async_foursquare_start.py","file_name":"async_foursquare_start.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"11134558995","text":"# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n#import data\nfile = pd.read_csv(\"data_poly.csv\", header=None)\nfile[2] = 1\nfile[3] = file.apply(lambda row: row[0]**2, axis=1)\nprint(file.head())\ndata = file.values\nX = data[:, [2, 0, 3]]\nY = data[:, 1]\n\n#calculate weights\nw = np.linalg.solve(np.dot(X.T, X), np.dot(X.T, Y))\nY_hat = np.dot(X, w.T)\n\n#calculate r squared\ntmp = Y - Y_hat\ntmp2 = Y - np.mean(Y)\nr_squared = 1 - tmp.dot(tmp)/tmp2.dot(tmp2)\nprint(\"r squared = \", r_squared)\n\nplt.scatter(X[:, 1], Y)\nplt.plot(sorted(X[:, 1]), sorted(Y_hat))\nplt.show()","repo_name":"suchy1713/ML-Learning","sub_path":"0_linear/polynomial_regression.py","file_name":"polynomial_regression.py","file_ext":"py","file_size_in_byte":663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"71036951775","text":"'''\r\nCreated on 08-Nov-2019\r\n\r\n@author: TKA\r\n'''\r\n\r\n\r\n\r\nimport xlrd \r\nfrom Tools.Scripts.ndiff import fopen\r\nfrom tests.prepareCSV import ReadRules as rRul\r\n\r\nif __name__ == '__main__':\r\n \r\n loc = (\"C:/Kumar/Workspace/CASTExtensionDevWS/com.castsoftware.uc.OMNEXT.1.0.0/tests/Mendix_Objects_Rules.xlsx\") \r\n \r\n wb = xlrd.open_workbook(loc) \r\n sheet = wb.sheet_by_index(0) \r\n sheet.cell_value(0, 0) \r\n \r\n f = open(\"OMNEXTMetaModel.xml\", \"w+\")\r\n f.write(\"\\n\")\r\n f.write(\"\\n\\n\")\r\n \r\n f.write(\"\\t\\n\");\r\n f.write(\"\\t\\tOMNEXT\\n\");\r\n f.write(\"\\t\\t\\n\");\r\n f.write(\"\\t\\n\");\r\n \r\n f.write(\"\\t\\n\");\r\n f.write(\"\\t\\tOMNEXT Artifacts\\n\");\r\n f.write(\"\\t\\t\\n\");\r\n f.write(\"\\t\\n\");\r\n \r\n f.write(\"\\t\\n\");\r\n f.write(\"\\t\\tOMNEXT_Subset\\n\");\r\n f.write(\"\\t\\t\\n\");\r\n f.write(\"\\t\\t\\n\");\r\n f.write(\"\\t\\t\\n\");\r\n f.write(\"\\t\\n\");\r\n \r\n f.write(\"\\t\\n\");\r\n f.write(\"\\t\\tOMNEXT\\n\");\r\n f.write(\"\\t\\t\\n\");\r\n f.write(\"\\t\\n\\n\");\r\n \r\n f.write(\"\\t\\n\")\r\n f.write(\"\\t\\tOMNEXT\\n\")\r\n f.write(\"\\t\\t\\n\")\r\n f.write(\"\\t\\t\\n\")\r\n f.write(\"\\t\\t\\n\")\r\n f.write(\"\\t\\n\\n\")\r\n \r\n f.write(\"\\t\\n\")\r\n f.write(\"\\t\\tOMNEXTProject\\n\")\r\n f.write(\"\\t\\t\\n\")\r\n f.write(\"\\t\\t\\n\")\r\n f.write(\"\\t\\t\\n\")\r\n f.write(\"\\t\\n\\n\")\r\n for i in range(sheet.nrows): \r\n if i>0:\r\n artifIDActual = sheet.cell_value(i, 0)\r\n artifIDManipulated = artifIDActual.replace(\" \", \"_\")\r\n f.write(\"\\t\\n\")\r\n f.write(\"\\t\\t\"+ artifIDActual +\"\\n\")\r\n f.write(\"\\t\\t\\n\")\r\n f.write(\"\\t\\t\\n\")\r\n f.write(\"\\t\\t\\n\")\r\n f.write(\"\\t\\t\\n\");\r\n f.write(\"\\t\\n\")\r\n \r\n print(i , sheet.cell_value(i, 0)) \r\n \r\n f.write(\"\")\r\n f.close()\r\n \r\n \r\n","repo_name":"ThangaArchi/uc.mendix","sub_path":"com.castsoftware.uc.OMNEXT.1.0.0/tests/metaModelGenerator.py","file_name":"metaModelGenerator.py","file_ext":"py","file_size_in_byte":3266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"23428881094","text":"import numpy as np\nfrom sys import argv\nfrom os import path\nfrom PIL import Image\n\nif __name__ == \"__main__\":\n if len(argv) != 3:\n print(\"Error, usage python3 createImage.py \")\n exit(1)\n\n if not path.exists(argv[1]):\n print(\"Error, file does not exist\")\n exit(1)\n\n file = np.loadtxt(argv[1], dtype=\"i\", delimiter=\",\")\n img = Image.fromarray(np.uint8(file * 255), \"L\")\n img.save(\"{}\".format(argv[2]))","repo_name":"papertran/Greyscale-Image-Maker","sub_path":"createImage.py","file_name":"createImage.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"} +{"seq_id":"34389522913","text":"\"\"\"main.py tkinter python clone of breakout!.\"\"\"\r\nimport tkinter as tk\r\n\r\nclass Game(tk.Frame):\r\n \"\"\"Game instance, a Tkinter.Frame subclass given to Tkinter.Tk() root.\"\"\"\r\n def __init__(self, master):\r\n \"\"\"Initialize parent Tkinter.Frame() and game environment.\"\"\"\r\n # Init parent - Tkinter.Frame(Frame instance, Tk instance)\r\n tk.Frame.__init__(self, master)\r\n self.lives = 3\r\n self.width = 610\r\n self.height = 400\r\n # Tkinter.Canvas() will take up the Frame area, we can draw on it\r\n self.canvas = tk.Canvas(self, bg='#aaaaff', width=self.width,\r\n height=self.height)\r\n\r\n # require .pack() by Tk to do actual placement\r\n self.canvas.pack()\r\n self.pack()\r\n\r\n self.items = {}\r\n self.ball = None\r\n self._paddle_y_start = 326\r\n self.paddle = Paddle(self.canvas, self.width / 2, self._paddle_y_start)\r\n\r\n # e.g. self.items = {'32345': Paddle, }\r\n # the .item property is an int that is returned as a unique reference\r\n # to element created by a canvas method (e.g. canvas.create_oval() or\r\n # canvas.create_rectangle())\r\n # This dict will only hold canvas items that can collide with the ball\r\n self.items[self.paddle.item] = self.paddle\r\n\r\n # Create the brick layout\r\n for x in range(5, self.width - 5, 75): # 75 px step\r\n self.add_brick(x + 37.5, 50, 2)\r\n self.add_brick(x + 37.5, 70, 1)\r\n self.add_brick(x + 37.5, 90, 1)\r\n\r\n self.hud = None\r\n\r\n # set up game entities\r\n self.setup_game()\r\n\r\n # bind key events to movement methods\r\n self.canvas.focus_set() # set focus to canvas to make sure we hear\r\n\r\n # We use anonymouse function calls here as event handlers.\r\n # '_' is just placeholder to mean ignore the first parameter given\r\n # to us (a Tkinter event by bind()).\r\n # We do it this way because the bind() call requires a callback\r\n # argument, so we can't just put in self.paddle.move(10) because\r\n # it is not callable (it would evaluate .move(10) in place first\r\n # before calling the .bind() command!\r\n self.canvas.bind('', lambda _: self.paddle.move(-10))\r\n self.canvas.bind('', lambda _: self.paddle.move(10))\r\n\r\n def setup_game(self):\r\n \"\"\"Do all the necessary things to start the game.\"\"\"\r\n self.add_ball()\r\n self.update_lives_text()\r\n self.text = self.draw_text(300, 200, \"Press Spacebar to start\")\r\n # Bind only here otherwise would call start_game() each time pressed\r\n self.canvas.bind('', lambda _: self.start_game())\r\n\r\n def add_ball(self):\r\n \"\"\"Create a Ball and store a reference in self.Paddle as well.\"\"\"\r\n if self.ball is not None:\r\n self.ball.delete()\r\n paddle_coords = self.paddle.get_position()\r\n # set the ball on top of player's paddle at start\r\n x = (paddle_coords[0] + paddle_coords[2]) * 0.5\r\n self.ball = Ball(self.canvas, x, 310)\r\n self.paddle.set_ball(self.ball) # store reference to it\r\n\r\n def add_brick(self, x, y, hits):\r\n \"\"\"\r\n Create a Brick object.\r\n\r\n :param x: x-axis int location to create Brick.\r\n :param y: y-axis int location to create Brick.\r\n :param hits: int number of hits before Brick breaks.\r\n \"\"\"\r\n brick = Brick(self.canvas, x, y, hits)\r\n # brick.item will be int that uniquely ID's that brick on canvas\r\n self.items[brick.item] = brick\r\n\r\n def draw_text(self, x, y, text, size='40'):\r\n \"\"\"\r\n Draw text message on the canvas instance.\r\n\r\n :param x: int x-axix location to start text\r\n :param y: int y-axis location to start text\r\n :param text: text to draw at location\r\n :param size: default 40. Int size of font to use\r\n :rtype: int that references item uniquely on canvas\r\n \"\"\"\r\n font = ('Helvetica', size)\r\n return self.canvas.create_text(x, y, text=text, font=font)\r\n\r\n def update_lives_text(self):\r\n \"\"\"Displays number of lives left on canvas.\"\"\"\r\n text = \"Lives: {}\".format(self.lives)\r\n if self.hud is None:\r\n self.hud = self.draw_text(50, 20, text, 15)\r\n else:\r\n self.canvas.itemconfig(self.hud, text=text)\r\n\r\n def start_game(self):\r\n \"\"\"Start main loop of game.\"\"\"\r\n # unbind pressing space to call start_game()\r\n self.canvas.unbind('')\r\n self.canvas.delete(self.text)\r\n self.paddle.ball = None\r\n self.game_loop()\r\n\r\n def game_loop(self):\r\n \"\"\"Main game loop.\"\"\"\r\n self.check_collisions()\r\n # get how many Bricks left\r\n num_bricks = len(self.canvas.find_withtag('brick'))\r\n if num_bricks == 0:\r\n self.ball.speed = None\r\n self.draw_text(300, 200, \"You've won!\")\r\n elif self.ball.get_position()[3] >= self.height:\r\n # bottom of screen, lose a life\r\n self.ball.speed = None\r\n self.lives -= 1\r\n if self.lives < 0:\r\n self.draw_text(300, 200, \"Game Over\")\r\n else:\r\n self.after(1000, self.setup_game)\r\n else:\r\n self.ball.update() # update position\r\n # use Tkinter .after() method to call game loop again\r\n # after(delay in ms, callback)\r\n self.after(50, self.game_loop)\r\n\r\n def check_collisions(self):\r\n \"\"\"\r\n Process the ball's collisions.\r\n\r\n Since Ball.collide receives a list of game objects and\r\n canvas.find_overlapping() returns a list of colliding items\r\n with a given position, we use the dict of items to transform\r\n each canvas item into its corresponding game object.\r\n\r\n Game.items property will only contain canvas items that can\r\n collide with the ball. Therefore, we only need to pass the\r\n items from the Game.items dict.\r\n\r\n We filter the canvas items that cannot collide with the ball,\r\n like text objects, and then we retrieve each game objects by\r\n its key.\r\n \"\"\"\r\n ball_coords = self.ball.get_position()\r\n items = self.canvas.find_overlapping(*ball_coords) # list\r\n # list comprehension to filter down to only objects that\r\n # can collide with the ball\r\n collideables = [self.items[x] for x in items if x in self.items]\r\n self.ball.collide(collideables)\r\n\r\n\r\nclass GameObject():\r\n \"\"\"Base class for game entities on a Tkinter.Canvas().\"\"\"\r\n def __init__(self, canvas, item):\r\n \"\"\"\r\n Stores the canvas and item parameters as properties of this instance\r\n for reference.\r\n\r\n :param canvas: a Tkinter.Canvas instance\r\n :param item: an entity/shape, e.g. a Canvas.create_oval reference\r\n \"\"\"\r\n self.canvas = canvas\r\n self.item = item\r\n\r\n def get_position(self):\r\n \"\"\"\r\n Returns bounding coordinates of instance's item property.\r\n\r\n :rtype: list of integers\r\n \"\"\"\r\n return self.canvas.coords(self.item)\r\n\r\n def move(self, x, y):\r\n \"\"\"\r\n Move the instance's item property by x horizontally, and y vertically.\r\n\r\n :param x: distance to move self.item horizontally in pixels\r\n :param y: distance to move self.item vertically in pixels\r\n \"\"\"\r\n self.canvas.move(self.item, x, y)\r\n\r\n def delete(self):\r\n \"\"\"Remove instance's self.item.\"\"\"\r\n self.canvas.delete(self.item)\r\n\r\n\r\nclass Ball(GameObject):\r\n \"\"\"\r\n Ball that bounces off solid objects on screen. Stores information\r\n about speed, direction, and radius of the ball.\r\n \"\"\"\r\n def __init__(self, canvas, x, y):\r\n \"\"\"Creates ball shape using canvas.create_oval().\"\"\"\r\n self.radius = 10\r\n self.direction = [1, -1] # right and up\r\n self.speed = 10\r\n\r\n # self.item value will be an integer, which is ref num returned by method\r\n item = canvas.create_oval(x - self.radius, y - self.radius,\r\n x + self.radius, y + self.radius,\r\n fill='white')\r\n # now call parent constructor with our required item\r\n GameObject.__init__(self, canvas, item)\r\n\r\n def update(self):\r\n \"\"\"Logic for changing Ball direction based on collisions.\"\"\"\r\n\r\n # ---------------------------------------------------------\r\n # BOUNDS COLLISIONS\r\n # ---------------------------------------------------------\r\n ball_coords = self.get_position()\r\n width = self.canvas.winfo_width()\r\n\r\n if ball_coords[0] <= 0 or ball_coords[2] >= width:\r\n self.direction[0] *= -1 # reverse x vector\r\n if ball_coords[1] <= 0:\r\n self.direction[1] *= -1 # reverse y vector\r\n x = self.direction[0] * self.speed # scale by Ball's speed\r\n y = self.direction[1] * self.speed\r\n self.move(x, y) # inherited method\r\n\r\n\r\n def collide(self, game_objects):\r\n \"\"\"\r\n Handles the outcome of collision with one or more objects.\r\n\r\n :param game_objects: list of colliding objects.\r\n\r\n Code Explanation:\r\n # First get center x of Ball\r\n # x0, y0 is top left corner, x1, y1 is bottomright corner\r\n ball_coords = self.get_position() # -> [x0, y0, x1, y1]\r\n # we add the start and end x positions and * 0.5 to get midx\r\n ball_center_x = (ball_coords[0] + coords[2]) * 0.5 # center\r\n brick_coords = brick.get_position() # -> [x0, y0, x1, y1]\r\n # if ball_center is greater than lower right of brick, meaning\r\n # ball center is to right of right side of brick during collision\r\n if ball_center_x > brick_coords[2]:\r\n self.direction[0] = 1 # ball x to right\r\n # check is ball center is left of the left side of brick\r\n # during collision\r\n elif ball_center_x < brick_coords[0]:\r\n self.direction[0] = -1 # ball x to the left\r\n # else case means ball_center is between left and right x of brick\r\n # which means a top/bottom hit, so we just reverse y-vector of ball\r\n else:\r\n self.direction[1] *= -1\r\n\r\n Above is valid for when ball hits the paddle or a single brick. But\r\n if we hit two bricks at the same time things get hairy. We simplify\r\n by assuming multiple brick collisions can only happen from above or\r\n below. That means that we change the y-axis direction of the ball\r\n without calculating the position of the colliding bricks.\r\n\r\n So what we do is guard all of the above by checking how many\r\n colliding objects we have, in the argument game_objects, and if it\r\n is two or more we can just flip the y-axis on the ball and be done.\r\n If not, we have to do more investigation and do all of the above.\r\n \"\"\"\r\n ball_coords = self.get_position()\r\n ball_center_x = (ball_coords[0] + ball_coords[2]) * 0.5 # same as / 2\r\n\r\n if len(game_objects) > 1: # 2+ collisions, just flip y-axis and done\r\n self.direction[1] *= -1\r\n elif len(game_objects) == 1: # investigate more if just one collision\r\n game_object = game_objects[0]\r\n coords = game_object.get_position()\r\n if ball_center_x > coords[2]:\r\n self.direction[0] = 1\r\n elif ball_center_x < coords[0]:\r\n self.direction[0] = -1\r\n else:\r\n self.direction[1] *= -1\r\n # Do below regardless of how many collisions came in\r\n for game_object in game_objects:\r\n if isinstance(game_object, Brick):\r\n game_object.hit() # decrement hit counter, etc. in Brick class\r\n\r\n\r\nclass Paddle(GameObject):\r\n \"\"\"\r\n The player's paddle. A set_ball method stores a reference to the ball,\r\n which can be moved with the ball before the game starts.\r\n \"\"\"\r\n def __init__(self, canvas, x, y):\r\n \"\"\"\r\n Create a Paddle instance using canvas.create_rectangle().\r\n\r\n :param canvas: a Tkinter.Canvas() instance\r\n :param x: the horizontal axis location (int)\r\n :param y: the vertical axis location (int)\r\n \"\"\"\r\n self.width = 80\r\n self.height = 10\r\n self.ball = None\r\n\r\n # item will be int ref num returned by create_rectangle()\r\n item = canvas.create_rectangle(x - self.width / 2,\r\n y - self.height / 2,\r\n x + self.width / 2,\r\n y + self.height / 2,\r\n fill='blue')\r\n # call parent class now with our require item argument\r\n GameObject.__init__(self, canvas, item)\r\n\r\n def set_ball(self, ball):\r\n \"\"\"Store a reference to a ball on this instance.\"\"\"\r\n self.ball = ball\r\n\r\n def move(self, offset):\r\n \"\"\"\r\n Move the Paddle on the Tkinter.Canvas within bounds.\r\n\r\n Contained here is the pre-move logic. The actual move is\r\n done by calling our parent GameObject.move() method.\r\n\r\n :param offset: integer. amount to move in pixels left or right.\r\n \"\"\"\r\n coords = self.get_position() # e.g., [int, int, int, int]\r\n width = self.canvas.winfo_width()\r\n # bounds check\r\n if coords[0] + offset >= 0 and coords[2] + offset <= width:\r\n GameObject.move(self, offset, 0) # 0 is y-axis\r\n # Below happens when the game has not been started; move the ball\r\n if self.ball is not None:\r\n self.ball.move(offset, 0) # Call Ball inherited move() method\r\n\r\n\r\nclass Brick(GameObject):\r\n \"\"\"Ball objects destroy these canvas rectangle built objects when hit.\"\"\"\r\n COLORS = {1: '#999999', 2: '#555555', 3: '#222222'}\r\n\r\n def __init__(self, canvas, x, y, hits):\r\n \"\"\"\r\n Initialize a Brick object.\r\n\r\n :param canvas: a Tkinter.Canvas() instance\r\n :param x: Where to place it on horizontal x axis\r\n :param y: Where to place it on the vertical x axis\r\n :param hits: number of hits Brick can take before 'breaking'\r\n \"\"\"\r\n self.width = 75\r\n self.height = 20\r\n self.hits = hits\r\n color = Brick.COLORS[hits] # hits arg must be int 1,2, or 3\r\n\r\n # tags keyword is so we can reference it easy on canvas\r\n item = canvas.create_rectangle(x - self.width / 2,\r\n y - self.height / 2,\r\n x + self.width / 2,\r\n y + self.height / 2,\r\n fill=color, tags='brick')\r\n # now call parent class with our require item\r\n GameObject.__init__(self, canvas, item)\r\n\r\n def hit(self):\r\n \"\"\"Decrement hits counter. Delete instance if at 0.\"\"\"\r\n self.hits -= 1\r\n if self.hits == 0:\r\n self.delete() # inherited from GameObject()\r\n else: # repaint next color to indicate Brick was hit\r\n self.canvas.itemconfig(self.item, fill=Brick.COLORS[self.hits])\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # Create the root app and then create the Game instance (a tk.Frame())\r\n ROOT = tk.Tk()\r\n ROOT.title('Tkinter Breakout')\r\n # Frame() needs a Tk() instance as its parent, we pass our root app\r\n GAME = Game(ROOT)\r\n GAME.mainloop()\r\n","repo_name":"craigmac/tkinter-breakout","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":15622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"33"}