diff --git "a/2264.jsonl" "b/2264.jsonl" new file mode 100644--- /dev/null +++ "b/2264.jsonl" @@ -0,0 +1,1370 @@ +{"seq_id":"70896842404","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/7/6 4:35 PM\n# @Author : Joli\n# @Email : 99755349@qq.com\nimport json\nimport os\nimport shutil\nimport zlib\nimport time\nimport math\nimport random\n\nimport openpyxl\nimport demjson\nimport requests\nfrom jonlin.utils import FS, Log, Bit\nfrom jonlin.cl import Shell\n\nlog = Log.Logger(__file__)\n\ndef test_load_cdn_files():\n dstdir = '/Users/joli/Desktop/dldlh5/cdn'\n cdnurl = 'https://res.xxh5.z7xz.com/xxh5dev'\n errors = []\n\n # 根据资源表加载资源\n def load_by_json():\n flist = json.loads(FS.read_text('/Users/joli/Desktop/dldlh5/files.json'))\n httpss = requests.session()\n httpss.keep_alive = False\n\n def _httpload(host, filename):\n # filename = '%s_%s%s' % (FS.get_file_name(key), obj, ext)\n file_url = '%s/%s' % (host, filename)\n response = httpss.get(file_url)\n if response.status_code == 200:\n filename = file_url[len(cdnurl) + 1:]\n print(filename)\n filepath = os.path.join(dstdir, filename)\n FS.make_parent(filepath)\n with open(filepath, \"wb\") as fp:\n fp.write(response.content)\n return True\n\n def fullpath(parent, info):\n for key in info:\n obj = info[key]\n if isinstance(obj, dict):\n fullpath('%s/%s' % (parent, key), obj)\n else:\n ext = FS.extensions(key)\n isetc = False\n if ext == '.etc':\n isetc = True\n ext = '.png'\n filename = '%s_%s%s' % (FS.filename(key), obj, ext)\n if not _httpload(parent, filename):\n if isetc:\n filename = '%s_%s%s' % (FS.filename(key), obj, '.jpg')\n if not _httpload(parent, filename):\n filename = '%s_%s%s' % (FS.filename(key), obj, '.etc')\n if not _httpload(parent, filename):\n failurl = parent + '/' + filename\n log.e('fail', failurl)\n errors.append(failurl)\n else:\n failurl = parent + '/' + filename\n log.e('fail', failurl)\n errors.append(failurl)\n flist.pop('skins')\n fullpath(cdnurl, flist)\n\n # 根据文件目录结构加载资源\n def load_by_disktree():\n svdir = '/Users/joli/Desktop/apps/h5/map'\n iddir = os.path.join(dstdir, 'map')\n flist = sorted(os.listdir(iddir))\n guess = 1000\n ss = requests.session()\n ss.keep_alive = False\n num = 0\n # for n in range(len(flist)-1, -1, -1):\n for n in range(95, -1, -1):\n fid = flist[n]\n col = guess\n end = False\n for i in range(guess):\n for j in range(col):\n filename = 'pic%d_%d.swf' % (i, j)\n file_url = '%s/map/%s/swf/%s' % (cdnurl, fid, filename)\n log.d(n, \"load\", file_url)\n response = ss.get(file_url)\n if response.status_code == 404:\n if i == 0:\n col = j\n else:\n end = True\n break\n elif response.status_code == 200:\n filepath = os.path.join(svdir, fid, filename)\n FS.make_parent(filepath)\n with open(filepath, \"wb\") as fp:\n fp.write(response.content)\n else:\n log.e(num, file_url)\n errors.append(file_url)\n if end:\n break\n # load_by_disktree()\n load_by_json()\n print('----------------------------------', len(errors))\n for url in errors:\n print(url)\n\ndef test_hack_xxtea():\n import xxtea\n\n def fix_key(key):\n size = len(key)\n if size < 16:\n return key + bytes(16 - size)\n elif size > 16:\n return key[:16]\n return key\n\n def dexxtea(buffer, bsign, bkey):\n sign_len = len(bsign)\n if buffer[0: sign_len] != bsign:\n return buffer\n source = buffer[sign_len:]\n return xxtea.decrypt(source, bkey, padding=False)\n\n def dexxtea_file(src, dst, bsign, bkey):\n with open(src, 'rb') as fp:\n data = dexxtea(fp.read(), bsign, bkey)\n FS.make_parent(dst)\n with open(dst, 'wb') as fp:\n fp.write(data)\n\n sjldt = {\n 'xxtea_sign': b'Cokutau',\n 'xxtea_key': fix_key(b'Cokutau_pjzz'),\n 'src_dir': '/Users/joli/Desktop/apps/神将乱斗团/assets/res',\n 'dst_dir': '/Users/joli/Desktop/apps/1/神将乱斗团/res',\n 'testfile': 'battle/unit_text/cirt_sp.png'\n }\n sszg = {\n 'xxtea_sign': b'shiyuegame',\n 'xxtea_key': fix_key(b'JYDYdpyRecDuHQc8'),\n 'src_dir': '/Users/joli/Desktop/apps/闪烁之光/assets/res',\n 'dst_dir': '/Users/joli/Desktop/apps/1/闪烁之光/res',\n 'testfile': 'resource/face/face.png'\n }\n qqsg = {\n 'xxtea_sign': b'@bianfeng',\n 'xxtea_key': fix_key(b'8x120161031*#0b@^4(j&b='), # fix_key(b\"|-_Rrv2b>LP%4]'rn\"),\n 'src_dir': '/Users/joli/Desktop/test/hack/com.tencent.tmgp.bfqqsg_1.6.5_110520/assets',\n 'dst_dir': '/Users/joli/Desktop/test/hack/com.tencent.tmgp.bfqqsg_1.6.5_110520/assets1',\n 'testfile': 'Data/Art/UI_new/bg_activity.jpg'\n }\n target = qqsg\n # for filename in FS.walk_files(target['src_dir'], cut_pos=len(target['src_dir'])+1):\n # srcpath = os.path.join(target['src_dir'], filename)\n # dstpath = os.path.join(target['dst_dir'], filename)\n # print('dexxtea', srcpath)\n # dexxtea_file(srcpath, dstpath, target['xxtea_sign'], target['xxtea_key'])\n dexxtea_file(\n os.path.join(target['src_dir'], target['testfile']),\n os.path.join(target['dst_dir'], target['testfile']),\n target['xxtea_sign'],\n target['xxtea_key']\n )\n\ndef test_hack_xor():\n sig = b'laoma'\n src_dir = '/Users/joli/Downloads/nds_19041501/assets'\n dst_dir = '/Users/joli/Downloads/nds_19041501/de_assets'\n for filename in FS.walk_files(src_dir, cut=len(src_dir) + 1):\n # src = '/Users/joli/Downloads/nds_19041501/assets/src/accountLogin/Img_account_bg.png'\n # dst = '/Users/joli/Downloads/nds_19041501/assets/src/accountLogin/Img_account_bg1.png'\n src = os.path.join(src_dir, filename)\n dst = os.path.join(dst_dir, filename)\n with open(src, 'rb') as fp:\n temp = fp.read()\n if temp[:5] == sig:\n temp = temp[5:]\n size = len(temp)\n data = bytearray(size)\n for i in range(size):\n data[i] = temp[i] ^ 0x6\n else:\n continue\n FS.make_parent(dst)\n with open(dst, 'wb') as fp:\n fp.write(data)\n\ndef test_hack_luac():\n unluac = '/Users/joli/source/mac/app/hack/unluac_2015_06_13.jar'\n src = '/Users/joli/Desktop/apps/apk/res2/script/main.lua'\n dst = '/Users/joli/Desktop/apps/apk/res2/script/main1.lua'\n Shell.run('java -Djava.awt.headless=true -jar %s %s>%s' % (unluac, src, dst))\n\ndef test_hack_respack():\n def split_files(pkg, buffer):\n with open(pkg + '_filelist.txt', 'r') as fp:\n filelist = []\n for item in fp.read().split('\\n'):\n if item:\n colon = item.find(':')\n filelist.append((int(item[0:colon]), item[colon+1:]))\n print(\"filelist:\", len(filelist))\n pos = len(buffer)\n for i in range(len(filelist)-1, -1, -1):\n item = filelist[i]\n path = os.path.join(pkg, item[1])\n FS.make_parent(path)\n beg = item[0] + len(item[1]) + 1\n with open(path, 'wb') as fp:\n fp.write(buffer[beg:pos])\n pos = item[0]\n\n def parse_package():\n # pkg = '/Users/joli/Desktop/apps/三国杀名将传/assets/package1.assets'\n pkg = '/Users/joli/Desktop/apps/三国杀名将传/assets/patch.assets'\n with open(pkg, 'rb') as fp:\n # extract_extlist(pkg[0:-7], fp.read())\n extract_filelist(pkg[0:-7], fp.read())\n # split_files(pkg[0:-7], fp.read())\n # ba = Bit.ByteArray().init_buffer(buff)\n # print(ba.read_u16())\n # print(ba.read_u16())\n # print(ba.read_u16())\n # print(ba.read_int())\n # parse_package()\n\n def create_lua_table():\n filelist = set()\n with open('/Users/joli/Desktop/apps/三国杀名将传/assets/package1_filelist.txt', 'r') as fp:\n for item in fp.read().split('\\n'):\n if item:\n name = item[item.find(':')+1:]\n fext = FS.extensions(name)\n if fext == '.png' or fext == '.jpg':\n filelist.add('\"%s\"' % name)\n with open('/Users/joli/Desktop/apps/三国杀名将传/assets/patch_filelist.txt', 'r') as fp:\n for item in fp.read().split('\\n'):\n if item:\n name = item[item.find(':')+1:]\n fext = FS.extensions(name)\n if fext == '.png' or fext == '.jpg':\n filelist.add('\"%s\"' % name)\n filelist = sorted(filelist)\n print(len(filelist))\n fileroot = '/Users/joli/Documents/AndroidStudio/DeviceExplorer/emulator-5554/data/user/0/com.tencent.tmgp.sanguosha.mjz/files'\n resroot = '/Users/joli/Desktop/apps/apk/res'\n n = 0\n for i in range(len(filelist)):\n filename = filelist[i][1:-1]\n hackname = 'hackimage_%d.%s' % (i+1, filename[-3:])\n hackpath = os.path.join(fileroot, hackname)\n if os.path.isfile(hackpath):\n dst = os.path.join(resroot, filename)\n FS.make_parent(dst)\n shutil.copy2(hackpath, dst)\n else:\n n += 1\n print(\"miss\", n, i, filename, hackname)\n # print(',\\n'.join(filelist))\n create_lua_table()\n\n # b = bytes([0x9d, 0x02, 0x0, 0x0])\n # print(Bit.u32_from(b))\n # b = bytes([0x9f, 0x02, 0x0, 0x0])\n # print(Bit.u32_from(b))\n # b = bytes([0x45, 0x16, 0x0, 0x0])\n # print(Bit.u32_from(b))\n # b = bytes([0xc9, 0x0, 0x0, 0x0])\n # print(Bit.u32_from(b))\n # print('%x' % 184, '%x' % 69)\n\ndef test_hack_zlib():\n def deflate(data, compresslevel=9):\n # compress = zlib.compressobj(\n # compresslevel, # level: 0-9\n # zlib.DEFLATED, # method: must be DEFLATED\n # -zlib.MAX_WBITS, # window size in bits:\n # # -15..-8: negate, suppress header\n # # 8..15: normal\n # # 16..30: subtract 16, gzip header\n # zlib.DEF_MEM_LEVEL, # mem level: 1..8/9\n # 0 # strategy:\n # # 0 = Z_DEFAULT_STRATEGY\n # # 1 = Z_FILTERED\n # # 2 = Z_HUFFMAN_ONLY\n # # 3 = Z_RLE\n # # 4 = Z_FIXED\n # )\n encoder = zlib.compressobj()\n buffer = encoder.compress(data)\n buffer += encoder.flush()\n return buffer\n\n def inflate(data):\n # decoder = zlib.decompressobj(\n # -zlib.MAX_WBITS # see above\n # )\n decoder = zlib.decompressobj()\n buffer = decoder.decompress(data)\n buffer += decoder.flush()\n return buffer\n # return zlib.decompress(data)\n\n src = '/Users/joli/Desktop/dldlh5/filetable_2dw0b3_mix_etc.bin'\n dst = '/Users/joli/Desktop/dldlh5/filetable_2dw0b3_mix_etc_dec.bin'\n # inflate_file(src, dst)\n with open(src, 'rb') as fp:\n bf = fp.read()\n bf = inflate(bf)\n # ba = Bit.ByteArray().init_buffer(bf)\n # ba.set_endian(Bit.BIG_ENDIAN)\n # nums = read_int(ba)\n # print(nums)\n # for n in range(nums):\n # size = read_int(ba)\n # print(size)\n # print(ba.read_utf8(size))\n with open(dst, 'wb') as fp:\n fp.write(bf)\n\ndef test_hack_sqlite3():\n pass\n\nclass Data2Excel:\n class ExcelInfo:\n def __init__(self):\n self.datas = []\n self.ckeys = []\n self.skeys = []\n self.types = []\n\n def __init__(self):\n pass\n\n @staticmethod\n def build_sheet(sheet, title: str, info: ExcelInfo):\n sheet.title = title\n sheet.append([title])\n # set client line\n row = ['CLIENT']\n row.extend(info.ckeys)\n sheet.append(row)\n # set types line\n row = ['']\n row.extend(info.types)\n sheet.append(row)\n # set server line\n row = ['SERVER']\n row.extend(info.skeys)\n sheet.append(row)\n # set data matrix\n for line in info.datas:\n row = ['']\n row.extend(line)\n sheet.append(row)\n\n def guess_info_by_list(self, source, id_field):\n info = self.ExcelInfo()\n for line in source:\n for k, v in line.items():\n pass\n return info\n # name = FS.filename(file)\n # wb = openpyxl.Workbook()\n # # print(wb.get_sheet_names())\n # _build_book1(wb, conf, name, ('ed', 'hg'))\n # dstfile = os.path.join(dst, name + '.xlsx')\n # FS.make_parent(dstfile)\n # wb.save(dstfile)\n\n def guess_info_by_dict(self, source):\n pass\n\n @staticmethod\n def guess_type(v):\n if isinstance(v, int):\n return 'int'\n if isinstance(v, float):\n return 'float'\n if isinstance(v, str):\n return 'string'\n if isinstance(v, dict):\n return 'dict'\n if isinstance(v, list):\n return 'list'\n raise RuntimeError('unknow type ' + v)\n\ndef test_json2excel():\n def _build_sheet1(sheet, config, title, flat=False): # 要求config是二维数组或字典\n sheet.title = title\n ckey = []\n skey = []\n kid1 = {}\n kid2 = []\n isdict = isinstance(config, dict)\n for idx in config:\n if isdict:\n item = config[idx]\n else:\n item = idx\n if not flat:\n for k in item:\n if k not in ckey:\n ckey.append(k)\n kid1[k] = _guess_type(item.get(k))\n else:\n ckey.append(idx)\n kid1[idx] = _guess_type(item)\n ckey.sort(key=_keysort)\n if isdict and not flat and ckey[0] != 'id':\n ckey.insert(0, 'id')\n kid1['id'] = 'int'\n is_add_id = True\n else:\n is_add_id = False\n for k in ckey:\n t = kid1[k]\n if t == 'dict' or t == 'list':\n kid2.append('string')\n else:\n kid2.append(t)\n print(f'{len(ckey)} {ckey}')\n print(f'{len(kid2)} {kid2}')\n # header\n sheet.append([title])\n row = ['CLIENT']\n row.extend(ckey)\n sheet.append(row)\n row = ['']\n row.extend(kid2)\n sheet.append(row)\n row = ['SERVER']\n row.extend(skey)\n sheet.append(row)\n if not flat:\n for idx in config:\n row = ['']\n item = config[idx] if isdict else idx\n if is_add_id:\n try:\n row.append(int(idx))\n except:\n row.append(idx)\n for i in range(1 if is_add_id else 0, len(ckey)):\n k = ckey[i]\n t = kid1[k]\n v = item.get(k)\n if t == 'dict' or t == 'list' or isinstance(v, dict) or isinstance(v, list):\n v = demjson.encode(v, encoding='UTF-8')\n row.append(v)\n # print(f'{k} {t} {v}')\n sheet.append(row)\n else:\n row = ['']\n for i in range(1 if is_add_id else 0, len(ckey)):\n k = ckey[i]\n t = kid1[k]\n v = config.get(k)\n if t == 'dict' or t == 'list' or isinstance(v, dict) or isinstance(v, list):\n v = json.dumps(v, ensure_ascii=False) # demjson.encode(v, encoding='UTF-8')\n row.append(v)\n sheet.append(row)\n\n def _build_sheet2(sheet, config, title):\n sheet.title = title\n keys = []\n mkey = sorted(config['m'].keys())\n for k in mkey:\n keys.append(config['m'][k])\n print(f'{title}: {keys}')\n skey = []\n kid1 = []\n kid2 = []\n data = config['d']\n for i in range(len(mkey)-1, -1, -1):\n k = mkey[i]\n for item in data.values():\n if isinstance(item, dict):\n val = item.get(k)\n if val is None:\n mkey.pop(i)\n keys.pop(i)\n else:\n t = _guess_type(val)\n kid1.append(t)\n if t == 'dict' or t == 'list':\n kid2.append('string')\n else:\n kid2.append(t)\n break\n elif isinstance(item, list):\n keys = ['id', 'item']\n kid1 = ['int', 'list']\n kid2 = ['int', 'string']\n break\n else:\n print('unkonw item type')\n kid1.reverse()\n kid2.reverse()\n # header\n sheet.append([title])\n row = ['CLIENT']\n row.extend(keys)\n sheet.append(row)\n row = ['']\n row.extend(kid2)\n sheet.append(row)\n row = ['SERVER']\n row.extend(skey)\n sheet.append(row)\n for rid in sorted(data.keys()):\n item = data[rid]\n row = ['']\n if isinstance(item, dict):\n for i in range(len(mkey)):\n k = mkey[i]\n if kid1[i] == 'dict' or kid1[i] == 'list':\n row.append(demjson.encode(item.get(k), encoding='UTF-8'))\n else:\n row.append(item.get(k))\n sheet.append(row)\n elif isinstance(item, list):\n newitem = []\n for it in item:\n newit = {}\n for k in it:\n newit[config['m'][k]] = it[k]\n newitem.append(newit)\n row.append(rid)\n row.append(demjson.encode(newitem, encoding='UTF-8'))\n sheet.append(row)\n\n def _build_book1(book, config, title, roots=None):\n content, actived = None, False\n if roots:\n for r in roots:\n content = config.get(r)\n if content:\n break\n content = content if content else config\n if isinstance(content, dict):\n for title in content.keys():\n print(f'--------------------- book:{title}')\n data = content[title]\n is_sub = True\n for v in data.values():\n for sv in v.values():\n if not isinstance(sv, dict) and not isinstance(sv, list):\n is_sub = False\n break\n if is_sub:\n for k, v in data.items():\n k = k.replace('?', '_')\n if actived:\n if book.__contains__(k):\n b = book.get_sheet_by_name(k)\n else:\n\n b = book.create_sheet(k)\n else:\n actived = True\n b = book.active\n _build_sheet1(b, v, k)\n else:\n if actived:\n if book.__contains__(title):\n b = book.get_sheet_by_name(title)\n else:\n b = book.create_sheet(title)\n else:\n actived = True\n b = book.active\n _build_sheet1(b, data, title)\n else:\n _build_sheet1(book.active, content, title)\n\n def _build_book2(book, config, title):\n if 'm' in config and 'd' in config:\n _build_sheet2(book.active, config, title)\n return\n isfirst = True\n for subkey in config:\n subobj = config[subkey]\n title = subkey.rstrip('_json')\n if 'm' in subobj and 'd' in subobj:\n if isfirst:\n isfirst = False\n _build_sheet2(book.active, subobj, title)\n else:\n _build_sheet2(book.create_sheet(title), subobj, title)\n else:\n print('unexcept config format:', title)\n\n def _output1():\n src = '/Users/joli/Documents/AndroidStudio/DeviceExplorer/emulator-5554/data/data/com.lilithgames.hgame.cn/files/jsonc_dir'\n dst = '/Users/joli/Documents/AndroidStudio/DeviceExplorer/emulator-5554/data/data/com.lilithgames.hgame.cn/files/excel_dir'\n for fn in FS.walk_files(src, ewhites=['.json'], cut=len(src) + 1):\n if fn.endswith('languageDb.json'):\n continue\n file = os.path.join(src, fn)\n print('------------------------------------------', file)\n conf = demjson.decode_file(file)\n if not conf:\n print('empty config')\n continue\n name = FS.filename(file)\n wb = openpyxl.Workbook()\n # print(wb.get_sheet_names())\n _build_book1(wb, conf, name, ('ed', 'hg'))\n dstfile = os.path.join(dst, name + '.xlsx')\n FS.make_parent(dstfile)\n wb.save(dstfile)\n\n def _output2():\n json_ver = '/Users/joli/Downloads/fy/assets/game/resource/1_00.58_version.json'\n conf_src = '/Users/joli/Downloads/fy/assets/game/resource/config'\n conf_dst = '/Users/joli/Downloads/fy/assets/game/resource/config'\n ver_dict = {}\n for k, v in json.loads(FS.read_text(json_ver)).items():\n ver_dict[v] = k\n for f in FS.walk_files(conf_src, ewhites=['.json']):\n # f = '/Users/joli/Downloads/fy/assets/game/resource/config/4643a093.json'\n config = demjson.decode_file(f)\n if not config:\n print('empty config:' + f)\n continue\n vf = ver_dict[FS.filename(f)]\n df = os.path.join(conf_dst, vf[0: vf.rfind('.')] + '.xlsx')\n print(f)\n print(vf)\n print(df)\n wb = openpyxl.Workbook()\n if vf.startswith('global/') or 'error_code_data' in vf:\n print(config)\n _build_sheet1(wb.active, config, FS.filename(df), flat=True)\n else:\n _build_book1(wb, config, FS.filename(df))\n FS.make_parent(df)\n wb.save(df)\n # break\n\n _output1()\n # _output2()\n print('done')\n\ndef test_hack_apk():\n from simples.rob import RobAPK\n deapk = RobAPK.RobYQCR()\n # deapk.decompile()\n # deapk.reinstall()\n # deapk.extract_files()\n # deapk.pull_files()\n # deapk.decrypt_res()\n # deapk.pull_files()\n\ndef test_hack_h5():\n # from simples.rob import RobH5\n # deh5 = RobH5.DeDMXKL()\n # deh5.de_json()\n # print('done')\n pass\n\ndef extract_text():\n # ff = '/Users/joli/Downloads/xxx/npc_talk.json'\n # ff = '/Users/joli/Downloads/xxx/npc_menu.json'\n # ff = '/Users/joli/Downloads/xxx/npc_story.json'\n ff = '/Users/joli/Downloads/xxx/npc.json'\n with open(ff, 'rb') as fp:\n sheet = json.load(fp)\n with open(ff.replace('.json', '.txt'), 'w') as fp1:\n for obj in sheet:\n pass\n # fp1.write(obj['content'] + '\\n')\n\n # fp1.write(obj['text'] + '\\n')\n # if 'follow' in obj:\n # for follow in obj['follow']:\n # fp1.write(follow[1] + '\\n')\n # for v in obj['dbase'].values():\n # fp1.write(v + '\\n')\n\n # obj = sheet[obj]\n # if 'story_fragment' in obj:\n # fp1.write(obj['story_fragment'] + '\\n')\n\n # obj = sheet[obj]\n # if 'desc' in obj:\n # fp1.write(obj['desc'] + '\\n')\n # for v in obj['dialog']:\n # fp1.write(v + '\\n')\n\ndef click_spine_forum():\n url = 'http://zh.esotericsoftware.com/forum/P40-15632'\n http_sess = requests.session()\n http_sess.keep_alive = False\n for i in range(99999999999):\n secs = random.randint(1, 10)\n print(f'start request:{i}, wait:{secs}')\n try:\n # time.sleep(secs)\n response = http_sess.get(url)\n if response.status_code == 200:\n print(f'request:{i} successful')\n # print(response.content)\n response.close()\n except:\n pass\n http_sess.close()\n\ndef test_ab():\n ab_dir = '/Users/joli/Downloads/lingmaochuan_123/assets'\n # ab_dir = '/Users/joli/Downloads/xian_M205161_OfficialAd_LtshareSocial/assets'\n for par, _, files in os.walk(ab_dir):\n for fn in files:\n ff = os.path.join(par, fn)\n with open(ff, 'rb') as fp:\n buf = fp.read()\n if buf and buf[8:15] == b'UnityFS':\n print('write:', ff)\n with open(ff, 'wb') as fp:\n fp.write(buf[8:])\n\n\ndef main():\n pass\n test_ab()\n # test_hack_h5()\n # test_json2excel()\n # test_load_cdn_files()\n # test_hack_xor()\n # test_hack_xxtea()\n # test_hack_luac()\n # test_hack_zlib()\n # test_hack_respack()\n # test_hack_apk()","repo_name":"JoliChen/py-tool","sub_path":"easy2/simples/TestRob.py","file_name":"TestRob.py","file_ext":"py","file_size_in_byte":26579,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"14912597329","text":"from duit.ui.annotations.UIAnnotation import UIAnnotation\n\n\nclass TextAnnotation(UIAnnotation):\n def __init__(self, name: str, placeholder_text: str = \"\",\n tooltip: str = \"\", readonly: bool = False, copy_content: bool = False):\n \"\"\"\n Initialize a TextAnnotation.\n\n :param name: The name of the text annotation.\n :param placeholder_text: The placeholder text to display in the text field.\n :param tooltip: The tooltip text for the annotation.\n :param readonly: Whether the annotation is read-only (default is False).\n :param copy_content: Whether to enable content copying (default is False).\n \"\"\"\n super().__init__(name, tooltip, readonly)\n self.placeholder_text = placeholder_text\n self.copy_content = copy_content\n","repo_name":"cansik/duit","sub_path":"duit/ui/annotations/TextAnnotation.py","file_name":"TextAnnotation.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"26230761480","text":"import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nclass Actor(nn.Module):\n def __init__(self, state_dim, action_dim):\n super(Actor, self).__init__()\n self.fc1 = nn.Linear(state_dim, 400)\n self.fc2 = nn.Linear(400, 300)\n self.fc3 = nn.Linear(300, action_dim)\n\n def forward(self, obs):\n x = F.relu(self.fc1(obs))\n x = F.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\nclass Critic(nn.Module):\n def __init__(self, state_dim, action_dim):\n super(Critic, self).__init__()\n self.fc1 = nn.Linear(state_dim+action_dim, 400)\n self.fc2 = nn.Linear(400, 300)\n self.fc3 = nn.Linear(300, 1)\n\n self.fc4 = nn.Linear(state_dim+action_dim, 400)\n self.fc5 = nn.Linear(400, 300)\n self.fc6 = nn.Linear(300, 1)\n\n def forward(self, action, obs):\n xu = torch.cat([obs, action], dim=1)\n x1 = F.relu(self.fc1(xu))\n x1 = F.relu(self.fc2(x1))\n x1 = self.fc3(x1)\n\n x2 = F.relu((self.fc4(xu)))\n x2 = F.relu((self.fc5(x2)))\n x2 = self.fc6(x2)\n\n return x1, x2\n\n def q1(self, action, obs):\n xu = torch.cat([obs, action], dim=1)\n x1 = F.relu(self.fc1(xu))\n x1 = F.relu(self.fc2(x1))\n x1 = self.fc3(x1)\n\n return x1\n\n\nclass ActorCritic(nn.Module):\n def __init__(self, act_limit=2):\n super().__init__()\n\n self.actor = Actor()\n self.actor.cuda()\n self.critic1 = Critic()\n self.critic2 = Critic()\n self.critic1.cuda()\n self.critic2.cuda()\n\n self.act_limit = act_limit\n\n for m in self.modules():\n if isinstance(m, nn.Linear):\n nn.init.xavier_normal_(m.weight)\n nn.init.constant_(m.bias, 0)\n\n self.actor_target = Actor()\n self.actor_target.cuda()\n self.critic1_target = Critic()\n self.critic2_target = Critic()\n self.critic1_target.cuda()\n self.critic2_target.cuda()\n\n self.copy_params()\n\n def copy_params(self):\n self.actor_target.load_state_dict(self.actor.state_dict())\n self.critic1_target.load_state_dict(self.critic1.state_dict())\n self.critic2_target.load_state_dict(self.critic2.state_dict())\n\n def get_action(self, obs, noise_scale):\n pi = self.act_limit * self.actor(obs)\n pi += noise_scale * torch.rand_like(pi)\n pi.clamp(max=self.act_limit, min=-self.act_limit)\n return pi.squeeze()\n\n def get_target_action(self, obs, noise_scale=0.2, clip_param=2):\n pi = self.act_limit * self.actor_target(obs)\n eps = noise_scale * torch.randn_like(pi)\n eps.clamp(max=clip_param, min=-clip_param)\n pi += eps\n pi.clamp(max=self.act_limit, min=-self.act_limit)\n return pi.detach()\n\n def update_target(self, tau):\n # compute theta_taget = tau * target_p + (1 - tau) * policy_p\n for actor_p, actor_target_p in zip(self.actor.parameters(), self.actor_target.parameters()):\n actor_target_p.data = tau * actor_target_p.data + (1-tau) * actor_p.data\n\n for critic_p, critic_target_p in zip(self.critic1.parameters(), self.critic1_target.parameters()):\n critic_target_p.data = tau * critic_target_p.data + (1-tau) * critic_p.data\n\n for critic_p, critic_target_p in zip(self.critic2.parameters(), self.critic2_target.parameters()):\n critic_target_p.data = tau * critic_target_p.data + (1-tau) * critic_p.data\n\n def compute_target(self, obs, pi, gamma, rewards, done):\n # compute r + gamma * (1 - d) * Q(s', mu_targ(s'))\n q1 = self.critic1_target(obs, pi.reshape(-1, 1))\n q2 = self.critic2_target(obs, pi.reshape(-1, 1))\n q = torch.min(q1, q2)\n return (rewards + gamma * (1-done) * q.squeeze().cpu()).detach()\n\n def q_function(self, obs, detach=True, action=None):\n # compute Q(s, a) or Q(s, mu(s))\n if action is None:\n pi = self.act_limit * self.actor(obs)\n else:\n pi = action\n if detach:\n pi = pi.detach()\n return self.critic1(obs, pi.reshape(-1, 1)).squeeze(),\\\n self.critic2(obs, pi.reshape(-1, 1)).squeeze()\n \n def save_weights(self, epoch):\n torch.save(self.actor.state_dict(), 'weights/actor_{}.pth'.format(epoch))\n torch.save(self.critic1.state_dict(), 'weights/critic1_{}.pth'.format(epoch))\n torch.save(self.critic2.state_dict(), 'weights/critic2_{}.pth'.format(epoch))\n\n\n\n\n\n\n\n","repo_name":"takeru1205/Insomnia","sub_path":"TD3/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14200446637","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport datetime, sys\nsys.path.insert(0, 'lib.zip')\nfrom google.appengine.api import users, app_identity, mail\nfrom google.appengine.ext import ndb\nfrom flask import Flask, render_template, jsonify, request, redirect, make_response\n\napp = Flask(__name__)\n\napp.jinja_env.line_statement_prefix = '#'\napp.jinja_env.line_comment_prefix = '##'\n\n### Constants\n\nCOLORS = [\n '#c74b16',\n '#6c16c7',\n '#8d9fd2',\n '#c71f16',\n '#16a9c7',\n '#c7c116',\n '#1663c7',\n '#16c72e',\n '#986e4c',\n '#c7166f',\n '#86c716',\n '#16c79e',\n '#2516c7',\n '#107b89',\n '#c76f16',\n '#bb2581',\n '#475c7a',\n '#b20c1d',\n '#be9f9a',\n '#1a6b47'\n ]\n\n### Models\n\nclass Root(ndb.Model): pass\nROOT = Root.get_or_insert(app_identity.get_application_id())\n\nclass Customer(ndb.Model):\n name = ndb.StringProperty()\n tags = ndb.StringProperty(repeated=True)\n channels = ndb.StringProperty(repeated=True)\n timer = ndb.IntegerProperty(default=0)\n address = ndb.JsonProperty(default=dict(city=None, state=None, street=None, zip=None))\n income = ndb.IntegerProperty(default=0)\n created = ndb.DateTimeProperty(auto_now_add=True)\n modified = ndb.DateTimeProperty(auto_now=True)\n owner = ndb.UserProperty(default=None)\n phone = ndb.StringProperty()\n\n\n @classmethod\n def all(cls, search=None, sort=None):\n \n results = []\n all_customers = cls.query(ancestor=ROOT.key).filter(cls.owner == users.get_current_user()).fetch()\n\n if search:\n for customer in all_customers:\n if customer.name.lower().startswith(search.lower()) or search in customer.channels + customer.tags:\n results.append(customer)\n\n else: results = all_customers\n\n\n if sort and results:\n results.sort(key=lambda x: getattr(x,sort.split(' ')[0]), reverse='DESC' in sort)\n\n return results\n\n @classmethod\n def all_owners(cls):\n all_customers = cls.query(ancestor=ROOT.key).fetch()\n \n all_owners = {}\n for customer in all_customers:\n all_owners[customer.owner.email()] = all_owners.get(customer.owner.email(), 0) + 1\n return all_owners\n\nclass AppUser(ndb.Model):\n google_account = ndb.UserProperty(default=None)\n max_customers = ndb.IntegerProperty(default=20)\n created = ndb.DateTimeProperty(auto_now_add=True)\n usage = ndb.DateTimeProperty(repeated=True)\n tags = ndb.PickleProperty(default={})\n\n\n @classmethod \n def get_current(cls):\n return cls.query(ancestor=ROOT.key).filter(cls.google_account==users.get_current_user()).get()\n\n @classmethod \n def is_known(cls):\n return bool(cls.get_current())\n\n @classmethod\n def all(cls):\n return cls.query(ancestor=ROOT.key).fetch()\n\n @property\n def has_quota(self):\n owners = Customer.all_owners()\n user_email = users.get_current_user().email()\n return True if user_email not in owners else owners[user_email] < self.max_customers\n\n\n def get_next_tag_color(self):\n \n color_indexes = []\n\n for element in self.tags.values():\n color_indexes.append(element['color_index'])\n\n color_occurences = [color_indexes.count(x) for x in range(len(COLORS))]\n \n return color_occurences.index(min(color_occurences))\n\n def update_usage(self):\n now = datetime.datetime.now()\n if self.usage[-1].date() != now.date():\n self.usage.append(now)\n self.put()\n\n def update_tags(self, tags_to_be_added, tags_to_be_deleted):\n \n unique_tags_to_be_added = []\n unique_tags_to_be_deleted = []\n\n if not tags_to_be_added and not tags_to_be_deleted:\n do_put = False\n\n else:\n do_put = True\n \n for tag in tags_to_be_added:\n try:\n self.tags[tag]['occurence'] += 1\n except KeyError:\n new_tag_color_index = self.get_next_tag_color()\n self.tags[tag] = {'color_index': new_tag_color_index, 'occurence':1}\n unique_tags_to_be_added.append({'tagName':tag, 'tagColorIdx':new_tag_color_index})\n\n for tag in tags_to_be_deleted:\n self.tags[tag]['occurence'] -= 1\n if self.tags[tag]['occurence'] == 0:\n del self.tags[tag]\n unique_tags_to_be_deleted.append(tag)\n\n return self, do_put, unique_tags_to_be_added, unique_tags_to_be_deleted\n\n def get_tag_infos_for_jtable(self):\n \n jtableTagColors = COLORS\n jtableTagNames = []\n jtableTagColorIndexes = []\n jtableTagOccurences = []\n\n for key, value in self.tags.iteritems():\n jtableTagNames.append(key)\n jtableTagColorIndexes.append(value['color_index'])\n jtableTagOccurences.append(value['occurence'])\n\n return jtableTagColors, jtableTagNames, jtableTagColorIndexes, jtableTagOccurences\n\n\n### Utils\n\ndef encode_keys(entities):\n return [dict(e.to_dict(exclude=['owner', 'created', 'modified']), **dict(key=e.key.urlsafe())) for e in entities]\n\ndef encode_key(entity):\n return encode_keys([entity])[0]\n\ndef decode_safekey(safekey):\n return ndb.Key(urlsafe=safekey)\n\ndef form_to_customer(form, customer):\n\n tags_to_be_added = []\n tags_to_be_deleted = []\n\n for key, value in form.iteritems():\n\n\n if key == 'key':\n continue\n \n if key == 'timer': \n try: value = int(value)\n except ValueError: value=0\n \n if key == 'channels':\n value = value.strip().replace(\" \", \"\").split(',')\n \n if key == 'tags':\n value = value.strip().replace(\" \", \"\").split(',')\n \n new_tags = value\n old_tags = customer.tags\n\n tags_to_be_deleted = [ tag for tag in old_tags if tag not in new_tags]\n tags_to_be_added = [ tag for tag in new_tags if tag not in old_tags]\n\n\n setattr(customer, key, value)\n \n return customer, tags_to_be_added, tags_to_be_deleted\n\ndef get_google_user_info():\n return users.get_current_user(), users.is_current_user_admin(), users.create_login_url('/'), users.create_logout_url('/')\n\n\n### Routes\n\n@app.route('/')\ndef index():\n \n if not users.get_current_user():\n return redirect('/login')\n\n user, user_is_admin, login_url, logout_url = get_google_user_info()\n app_user = AppUser.get_current()\n \n if not app_user:\n AppUser(parent=ROOT.key, google_account=users.get_current_user(), usage=[datetime.datetime.now()]).put()\n app_user = AppUser.get_current()\n app_user.update_usage()\n \n navbar_customers = 'active'\n\n return render_template('index.html', **locals())\n\n\n@app.route('/login')\ndef login():\n user, user_is_admin, login_url, logout_url = get_google_user_info()\n if user:\n return redirect('/')\n return render_template('login.html', **locals())\n\n\n@app.route('/recommend', methods=['POST'])\ndef recommend():\n sender = users.get_current_user()\n recipient_email = request.form['email']\n\n if not mail.is_email_valid(recipient_email):\n response = jsonify(message='Invalid email')\n response.status_code = 406\n return response\n\n else:\n\n message = mail.EmailMessage(\n sender=sender.email(),\n subject=\"I recommend u this app\")\n\n message.to = recipient_email\n message.body = \"\"\"Check out http://flask-crm.appspot.com\"\"\"\n message.send()\n return jsonify()\n\n@app.route('/admin')\ndef admin():\n user, user_is_admin, login_url, logout_url = get_google_user_info()\n navbar_admin = 'active'\n \n owners = Customer.all_owners()\n app_users = AppUser.all()\n app_user = AppUser.get_current()\n \n return render_template('admin.html', **locals())\n\n\n@app.route('/api/read/customers', methods=['GET'])\ndef get_customers():\n app_user = AppUser.get_current()\n customers = Customer.all(request.args.get('search'), request.args.get('jtSorting'))\n jtable_tag_infos = app_user.get_tag_infos_for_jtable()\n return jsonify(Result='OK', Records=encode_keys(customers), jtableTagColors=jtable_tag_infos[0], jtableTagNames= jtable_tag_infos[1], jtableTagColorIndexes=jtable_tag_infos[2], jtableTagOccurences=jtable_tag_infos[3])\n\n@app.route('/api/create/customers', methods=['POST'])\ndef create_customer():\n \n app_user = AppUser.get_current()\n\n if app_user.has_quota:\n \n new_customer, tags_to_be_added, tags_to_be_deleted = form_to_customer(request.form, Customer(parent=ROOT.key, owner=users.get_current_user()))\n app_user, put_user, unique_tags_to_be_added, unique_tags_to_be_deleted = app_user.update_tags(tags_to_be_added, tags_to_be_deleted)\n\n if put_user:\n ndb.put_multi([new_customer, app_user])\n else:\n new_customer.put()\n\n jtable_tag_infos = app_user.get_tag_infos_for_jtable()\n return jsonify(Result='OK', Record=encode_key(new_customer), jtableAddTags= unique_tags_to_be_added, jtableDeleteTags=unique_tags_to_be_deleted)\n\n else:\n return jsonify(Result='ERROR', Message='You cannot create more than '+str(app_user.max_customers) +' customers')\n\n\n@app.route('/api/update/customers', methods=['POST'])\ndef update_customer():\n app_user = AppUser.get_current()\n updated_customer, tags_to_be_added, tags_to_be_deleted = form_to_customer(request.form, decode_safekey(request.form['key']).get())\n app_user, put_user, unique_tags_to_be_added, unique_tags_to_be_deleted = app_user.update_tags(tags_to_be_added, tags_to_be_deleted)\n \n if put_user:\n ndb.put_multi([updated_customer, app_user])\n else:\n updated_customer.put()\n \n return jsonify(Result='OK', jtableAddTags=unique_tags_to_be_added, jtableDeleteTags=unique_tags_to_be_deleted)\n\n\n@app.route('/api/delete/customers', methods=['POST'])\ndef delete_customer():\n app_user = AppUser.get_current()\n delete_customer = decode_safekey(request.form['key']).get()\n app_user, put_user, unique_tags_to_be_added, unique_tags_to_be_deleted = app_user.update_tags(tags_to_be_added=[], tags_to_be_deleted=delete_customer.tags)\n if put_user: app_user.put()\n delete_customer.key.delete()\n return jsonify(Result='OK', jtableAddTags=[], jtableDeleteTags=unique_tags_to_be_deleted)","repo_name":"joelviel/flask-crm","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10862,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"26411443581","text":"from collections import defaultdict\nimport argparse\nfrom binarypredictor import BinaryPredictor\n\n\nclass Prior(BinaryPredictor):\n def __init__(self, filename, balanced=False, dataset=\"ucsd\"):\n self._prior_pred = True\n self._balanced = balanced\n self._dataset = dataset\n self._stopwordslist = []\n self._props = {\"balanced\": balanced, \"dataset\": dataset}\n super(Prior, self).__init__(filename)\n\n def train(self, filename):\n print(filename)\n self._filename = filename\n self._prior = {}\n self._model = None\n\n diag_totals = defaultdict(lambda: 0)\n diag_joined = defaultdict(lambda: 0)\n sentences = []\n self.seq_count = 0\n\n with open(filename) as f:\n for s in f:\n self.seq_count += 1\n sentences.append(s.split(\"|\")[2].split(\" \") +\n s.split(\"|\")[3].replace(\"\\n\", \"\").split(\" \"))\n next_diags = s.split(\"|\")[0].split(\",\")\n prev_diags = [e for e in s.split(\"|\")[2].split(\" \") if e.startswith(\"d_\")]\n for d in prev_diags:\n diag_totals[d] += 1\n if d in next_diags:\n diag_joined[d] += 1\n\n for d in diag_totals:\n self._prior[d] = diag_joined[d] * 1.0 / diag_totals[d]\n\n def predict(self, feed_events):\n diags = [x for x in feed_events if x.startswith(\"d_\")]\n predictions = defaultdict(lambda: 0)\n for d in diags:\n predictions[d] = 1\n return predictions\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Prior')\n parser.add_argument('-b', '--balanced', action=\"store\", default=0, type=int,\n help='Whether to use balanced or not blanaced datasets (0 or 1) default 0')\n parser.add_argument('-ds', '--dataset', action=\"store\", default=\"ucsd\", type=str,\n help='Which dataset to use \"ucsd\" or \"mimic\", default \"ucsd\"')\n args = parser.parse_args()\n\n ds = \"ucsd\"\n if args.dataset == \"mimic\":\n ds = \"mimic\"\n\n data_path = \"../Data/\" + ds + \"_seq/\"\n if args.balanced:\n data_path = \"../Data/\" + ds + \"_balanced/\"\n\n bal = False if args.balanced == 0 else True\n model = Prior(data_path + 'vocab', bal, ds)\n\n train_files = []\n valid_files = []\n test_files = []\n for i in range(10):\n train_files.append(data_path + 'trainv_'+str(i))\n valid_files.append(data_path + 'test_'+str(i))\n\n model.cross_validate(train_files, valid_files)\n model.write_stats()\n print(model.accuracy)\n","repo_name":"wael34218/SequentialPhenotypePredictor","sub_path":"Prediction/prior.py","file_name":"prior.py","file_ext":"py","file_size_in_byte":2644,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"52"} +{"seq_id":"72248369765","text":"# ##### BEGIN GPL LICENSE BLOCK #####\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software Foundation,\n# Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n#\n# ##### END GPL LICENSE BLOCK #####\n\n# \n\nimport bpy\nfrom bpy.types import Header, Menu\n\n\nclass GRAPH_HT_header(Header):\n bl_space_type = 'GRAPH_EDITOR'\n\n def draw(self, context):\n from bl_ui.space_dopesheet import dopesheet_filter\n\n layout = self.layout\n\n st = context.space_data\n\n row = layout.row(align=True)\n row.template_header()\n\n if context.area.show_menus:\n row.menu(\"GRAPH_MT_view\")\n row.menu(\"GRAPH_MT_select\")\n row.menu(\"GRAPH_MT_marker\")\n row.menu(\"GRAPH_MT_channel\")\n row.menu(\"GRAPH_MT_key\")\n\n layout.prop(st, \"mode\", text=\"\")\n\n dopesheet_filter(layout, context)\n\n layout.prop(st, \"auto_snap\", text=\"\")\n layout.prop(st, \"pivot_point\", text=\"\", icon_only=True)\n\n row = layout.row(align=True)\n row.operator(\"graph.copy\", text=\"\", icon='COPYDOWN')\n row.operator(\"graph.paste\", text=\"\", icon='PASTEDOWN')\n\n row = layout.row(align=True)\n if st.has_ghost_curves:\n row.operator(\"graph.ghost_curves_clear\", text=\"\", icon='GHOST_DISABLED')\n else:\n row.operator(\"graph.ghost_curves_create\", text=\"\", icon='GHOST_ENABLED')\n\n\nclass GRAPH_MT_view(Menu):\n bl_label = \"View\"\n\n def draw(self, context):\n layout = self.layout\n\n st = context.space_data\n\n layout.operator(\"graph.properties\", icon='MENU_PANEL')\n layout.separator()\n\n layout.prop(st, \"use_realtime_update\")\n layout.prop(st, \"show_frame_indicator\")\n layout.prop(st, \"show_cursor\")\n layout.prop(st, \"show_sliders\")\n layout.prop(st, \"use_auto_merge_keyframes\")\n\n layout.separator()\n layout.prop(st, \"use_beauty_drawing\")\n\n layout.separator()\n if st.show_handles:\n layout.operator(\"graph.handles_view_toggle\", icon='CHECKBOX_HLT', text=\"Show All Handles\")\n else:\n layout.operator(\"graph.handles_view_toggle\", icon='CHECKBOX_DEHLT', text=\"Show All Handles\")\n layout.prop(st, \"use_only_selected_curves_handles\")\n layout.prop(st, \"use_only_selected_keyframe_handles\")\n layout.operator(\"anim.time_toggle\")\n\n layout.separator()\n layout.operator(\"anim.previewrange_set\")\n layout.operator(\"anim.previewrange_clear\")\n layout.operator(\"graph.previewrange_set\")\n\n layout.separator()\n layout.operator(\"graph.frame_jump\")\n layout.operator(\"graph.view_all\")\n layout.operator(\"graph.view_selected\")\n\n layout.separator()\n layout.operator(\"screen.area_dupli\")\n layout.operator(\"screen.screen_full_area\")\n\n\nclass GRAPH_MT_select(Menu):\n bl_label = \"Select\"\n\n def draw(self, context):\n layout = self.layout\n\n # This is a bit misleading as the operator's default text is \"Select All\" while it actually *toggles* All/None\n layout.operator(\"graph.select_all_toggle\")\n layout.operator(\"graph.select_all_toggle\", text=\"Invert Selection\").invert = True\n\n layout.separator()\n layout.operator(\"graph.select_border\")\n layout.operator(\"graph.select_border\", text=\"Border Axis Range\").axis_range = True\n layout.operator(\"graph.select_border\", text=\"Border (Include Handles)\").include_handles = True\n\n layout.separator()\n layout.operator(\"graph.select_column\", text=\"Columns on Selected Keys\").mode = 'KEYS'\n layout.operator(\"graph.select_column\", text=\"Column on Current Frame\").mode = 'CFRA'\n\n layout.operator(\"graph.select_column\", text=\"Columns on Selected Markers\").mode = 'MARKERS_COLUMN'\n layout.operator(\"graph.select_column\", text=\"Between Selected Markers\").mode = 'MARKERS_BETWEEN'\n\n layout.separator()\n layout.operator(\"graph.select_leftright\", text=\"Before Current Frame\").mode = 'LEFT'\n layout.operator(\"graph.select_leftright\", text=\"After Current Frame\").mode = 'RIGHT'\n\n layout.separator()\n layout.operator(\"graph.select_more\")\n layout.operator(\"graph.select_less\")\n\n layout.separator()\n layout.operator(\"graph.select_linked\")\n\n\nclass GRAPH_MT_marker(Menu):\n bl_label = \"Marker\"\n\n def draw(self, context):\n layout = self.layout\n\n #layout.operator_context = 'EXEC_REGION_WIN'\n\n layout.operator(\"marker.add\", \"Add Marker\")\n layout.operator(\"marker.duplicate\", text=\"Duplicate Marker\")\n layout.operator(\"marker.delete\", text=\"Delete Marker\")\n\n layout.separator()\n\n layout.operator(\"marker.rename\", text=\"Rename Marker\")\n layout.operator(\"marker.move\", text=\"Grab/Move Marker\")\n\n # TODO: pose markers for action edit mode only?\n\n\nclass GRAPH_MT_channel(Menu):\n bl_label = \"Channel\"\n\n def draw(self, context):\n layout = self.layout\n\n layout.operator_context = 'INVOKE_REGION_CHANNELS'\n\n layout.operator(\"anim.channels_delete\")\n\n layout.separator()\n layout.operator(\"anim.channels_setting_toggle\")\n layout.operator(\"anim.channels_setting_enable\")\n layout.operator(\"anim.channels_setting_disable\")\n\n layout.separator()\n layout.operator(\"anim.channels_editable_toggle\")\n layout.operator(\"anim.channels_visibility_set\")\n layout.operator_menu_enum(\"graph.extrapolation_type\", \"type\", text=\"Extrapolation Mode\")\n\n layout.separator()\n layout.operator(\"anim.channels_expand\")\n layout.operator(\"anim.channels_collapse\")\n\n layout.separator()\n layout.operator_menu_enum(\"anim.channels_move\", \"direction\", text=\"Move...\")\n\n layout.separator()\n layout.operator(\"anim.channels_fcurves_enable\")\n\n\nclass GRAPH_MT_key(Menu):\n bl_label = \"Key\"\n\n def draw(self, context):\n layout = self.layout\n\n layout.menu(\"GRAPH_MT_key_transform\", text=\"Transform\")\n\n layout.operator_menu_enum(\"graph.snap\", \"type\", text=\"Snap\")\n layout.operator_menu_enum(\"graph.mirror\", \"type\", text=\"Mirror\")\n\n layout.separator()\n layout.operator(\"graph.keyframe_insert\")\n layout.operator(\"graph.fmodifier_add\")\n layout.operator(\"graph.sound_bake\")\n\n layout.separator()\n layout.operator(\"graph.duplicate_move\")\n layout.operator(\"graph.delete\")\n\n layout.separator()\n layout.operator_menu_enum(\"graph.handle_type\", \"type\", text=\"Handle Type\")\n layout.operator_menu_enum(\"graph.interpolation_type\", \"type\", text=\"Interpolation Mode\")\n\n layout.separator()\n layout.operator(\"graph.clean\")\n layout.operator(\"graph.smooth\")\n layout.operator(\"graph.sample\")\n layout.operator(\"graph.bake\")\n\n layout.separator()\n layout.operator(\"graph.copy\")\n layout.operator(\"graph.paste\")\n\n layout.separator()\n layout.operator(\"graph.euler_filter\", text=\"Discontinuity (Euler) Filter\")\n\n\nclass GRAPH_MT_key_transform(Menu):\n bl_label = \"Transform\"\n\n def draw(self, context):\n layout = self.layout\n\n layout.operator(\"transform.translate\", text=\"Grab/Move\")\n layout.operator(\"transform.transform\", text=\"Extend\").mode = 'TIME_EXTEND'\n layout.operator(\"transform.rotate\", text=\"Rotate\")\n layout.operator(\"transform.resize\", text=\"Scale\")\n\nif __name__ == \"__main__\": # only for live edit.\n bpy.utils.register_module(__name__)\n","repo_name":"damiles/blendocv","sub_path":"release/scripts/startup/bl_ui/space_graph.py","file_name":"space_graph.py","file_ext":"py","file_size_in_byte":8154,"program_lang":"python","lang":"en","doc_type":"code","stars":42,"dataset":"github-code","pt":"52"} +{"seq_id":"74896855523","text":"from __future__ import unicode_literals\nimport copy\nimport json\nimport sys\n\n\nclass BertConfig(object):\n \"\"\"Configuration class to store the configuration of a `BertModel`.\n \"\"\"\n\n def __init__(self,\n vocab_size_or_config_json_file,\n hidden_size=768,\n num_hidden_layers=12,\n num_attention_heads=12,\n intermediate_size=3072,\n hidden_act=\"gelu\",\n hidden_dropout_prob=0.1,\n attention_probs_dropout_prob=0.1,\n max_position_embeddings=512,\n type_vocab_size=2,\n initializer_range=0.02,\n layer_norm_eps=1e-12):\n \"\"\"Constructs BertConfig.\"\"\"\n\n if isinstance(vocab_size_or_config_json_file, str) or (sys.version_info[0] == 2\n and isinstance(vocab_size_or_config_json_file, str)):\n with open(vocab_size_or_config_json_file, \"r\", encoding='utf-8') as reader:\n json_config = json.loads(reader.read())\n for key, value in json_config.items():\n self.__dict__[key] = value\n elif isinstance(vocab_size_or_config_json_file, int):\n self.vocab_size = vocab_size_or_config_json_file\n self.hidden_size = hidden_size\n self.num_hidden_layers = num_hidden_layers\n self.num_attention_heads = num_attention_heads\n self.hidden_act = hidden_act\n self.intermediate_size = intermediate_size\n self.hidden_dropout_prob = hidden_dropout_prob\n self.attention_probs_dropout_prob = attention_probs_dropout_prob\n self.max_position_embeddings = max_position_embeddings\n self.type_vocab_size = type_vocab_size\n self.initializer_range = initializer_range\n self.layer_norm_eps = layer_norm_eps\n else:\n raise ValueError(\"First argument must be either a vocabulary size (int)\"\n \"or the path to a pretrained model config file (str)\")\n\n @classmethod\n def from_dict(cls, json_object):\n \"\"\"Constructs a `BertConfig` from a Python dictionary of parameters.\"\"\"\n config = BertConfig(vocab_size_or_config_json_file=-1)\n for key, value in json_object.items():\n config.__dict__[key] = value\n return config\n\n @classmethod\n def from_json_file(cls, json_file):\n \"\"\"Constructs a `BertConfig` from a json file of parameters.\"\"\"\n with open(json_file, \"r\", encoding='utf-8') as reader:\n text = reader.read()\n return cls.from_dict(json.loads(text))\n\n def __repr__(self):\n return str(self.to_json_string())\n\n def to_dict(self):\n \"\"\"Serializes this instance to a Python dictionary.\"\"\"\n output = copy.deepcopy(self.__dict__)\n return output\n\n def to_json_string(self):\n \"\"\"Serializes this instance to a JSON string.\"\"\"\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n\n def to_json_file(self, json_file_path):\n \"\"\" Save this instance to a json file.\"\"\"\n with open(json_file_path, \"w\", encoding='utf-8') as writer:\n writer.write(self.to_json_string())\n\n","repo_name":"wubet/bert-fused-amharic","sub_path":"bert/bert_config.py","file_name":"bert_config.py","file_ext":"py","file_size_in_byte":3279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30420662527","text":"from decimal import Decimal\nfrom django.conf import settings\nfrom product.models import Product, Image_color\n\n\nclass Cart(object):\n def __init__(self, request):\n \"\"\"\n Инициализация корзины\n \"\"\"\n self.session = request.session\n cart = self.session.get(settings.CART_SESSION_ID)\n if not cart:\n cart = self.session[settings.CART_SESSION_ID] = {}\n self.cart = cart\n\n def add(self, product, color, quantity=1, update_quantity=False):\n \"\"\"\n Добавить продукт в корзину или обновить его количество.\n \"\"\"\n product_id = str(product.id)\n\n if product_id not in self.cart:\n self.cart[product_id] = {\n 'colors': {str(color.id): 0},\n 'old_price': str(product.price),\n 'new_price': str(product.new_price),\n 'quantity': 0,\n 'price': str(product.price),\n 'line_quantity': str(product.quantity)\n }\n if update_quantity:\n self.cart[product_id]['quantity'] = quantity\n else:\n self.cart[product_id]['quantity'] += quantity\n try:\n self.cart[product_id]['colors'][str(color.id)] += 1\n except KeyError:\n self.cart[product_id]['colors'][str(color.id)] = quantity\n self.save()\n\n def save(self):\n # Обновление сессии cart\n self.session[settings.CART_SESSION_ID] = self.cart\n # Отметить сеанс как \"измененный\", чтобы убедиться, что он сохранен\n self.session.modified = True\n\n def remove(self, color, minus):\n \"\"\"\n Удаление товара из корзины.\n \"\"\"\n product_id = str(color.image_color.id)\n if product_id in self.cart:\n if not minus or self.cart[product_id]['colors'][str(color.id)] < 2:\n del self.cart[product_id]['colors'][str(color.id)]\n if self.cart[product_id]['colors'] == {}:\n del self.cart[product_id]\n else:\n self.cart[product_id]['colors'][str(color.id)] -= 1\n self.cart[product_id]['quantity'] -= 1\n self.save()\n\n def get_cart_products(self):\n \"\"\"\n Получение товаров из корзины\n \"\"\"\n product_ids = self.cart.keys()\n\n # получаем все цвета товара из корзины\n # l_color -> list_color\n # col -> col\n l_color = [list(col['colors'].keys()) for col in self.cart.values()]\n list_color_normal = set().union(*l_color)\n\n # получаем все товары из корзины\n product_list = Product.objects.filter(id__in=product_ids)\n\n # получаем все цвета полученных продуктов\n color_list = Image_color.objects.filter(id__in=list_color_normal)\n # color_list = [Image_color.objects.get()]\n return {\"products\": product_list, \"colors\": color_list}\n\n def clear(self):\n # удаление корзины из сессии\n del self.session[settings.CART_SESSION_ID]\n self.session.modified = True\n\n def get_total_price(self):\n \"\"\"\n Подсчет стоимости товаров в корзине.\n \"\"\"\n return {\"price\": sum(Decimal(item['price']) * item['quantity'] for item in self.cart.values()),\n \"discount\": sum(Decimal(item['new_price']) * item['quantity'] for item in self.cart.values())}\n\n def __len__(self):\n \"\"\"\n Подсчет всех товаров в корзине.\n \"\"\"\n return sum(item['quantity'] for item in self.cart.values())\n\n def get_total_quantity(self):\n \"\"\"\n Подсчет всех товаров из корзины (штук)\n \"\"\"\n return sum(int(item['line_quantity']) * item['quantity'] for item in self.cart.values())\n","repo_name":"anvar-front/Zeon_shop","sub_path":"cart/cart.py","file_name":"cart.py","file_ext":"py","file_size_in_byte":4242,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"30316742446","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 2 14:24:13 2022\n\n@author: pmaroneh\n\"\"\"\n\n\"\"\".. _ref_buckling_postbuckling_ring_stiffened_cylinder:\n\nBuckling and post-buckling analysis of a ring-stiffened\ncylinder using nonlinear stabilization\n======================================================\n\nThis examples shows how to use PyMAPDL to import an existing FE model and to\nperform a nonlinear buckling and postbuckling analysis using nonlinear\nstabilization. The problem uses a stiffened cylinder subjected to uniform\nexternal pressure to show how to find the nonlinear buckling loads,\nachieve convergence at the post-buckling stage, and interpret the results.\n\nThis example is inspired from the model and analysis defined in Chapter 21 of\nthe Mechanical APDL Technology Showcase Manual.\n\n\"\"\"\n\n###############################################################################\n# Setting up model\n# ----------------\n#\n# The original FE model is given in the Ansys Mechanical APDL Technology\n# Showcase Manual. The .cdb contains a FE model of a ring-stiffened cylinder.\n#\n# A circular cylinder made of bare 2024-T3 aluminum alloy is stiffened inside\n# with five Z-section rings. Its ends are closed with thick aluminum bulkheads.\n# A riveted L section exists between the top plate and the top ring and the\n# bottom plate and bottom ring.\n# The cylinder is subjected to a differential external pressure. The pressure\n# causes a local buckling phenomenon characterized by buckling of the skin\n# between stiffening rings, leading eventually to collapse.\n#\n# The finite element model of the ring stiffened cylinder is meshed with\n# SHELL281 elements with an element size of 10 mm. The fine mesh is required\n# for buckling analysis, and a full 360-degree model is necessary because\n# the deformation is no longer axisymmetric after buckling occurs.\n#\n# All shell elements have uniform thickness. Five sections are created in the\n# model with no offsets, so the shell sections are offset to the midplane\n# by default.\n#\n# Starting MAPDL as a service and importing an external model\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n\nfrom ansys.mapdl.core import launch_mapdl\nfrom ansys.mapdl.core.examples.downloads import download_tech_demo_data\n\n# define geometric parameters\nbs = 95.3 # Ring spacing (mm)\nts = 1.034 # Skin thickness (mm)\ntw = 0.843 # Ring thickness (mm)\nr = 344 * ts # Radius of cylinder (mm)\nL = 431.8 + 2 * (19 - 9.5) # Length of cylinder (mm)\npext = 0.24 # Differential external pressure (MPa)\n\n# start MAPDL as a service\nmapdl = launch_mapdl(run_location=\"D:\\PyAnsys\\Examples\\Buckling_PostBuckling_TD21\")\nprint(mapdl)\n\nmapdl.filname(\"buckling\") # change filename\n# mapdl.nerr(nmerr=200, nmabt=10000, abort=-1, ifkey=0, num=0)\n\n# enter preprocessor\nmapdl.prep7()\n\n# define material properties for 2024-T3 Alluminum alloy\nEX = 73000 # Young's Modulus (MPA)\nET = 73 # Tangent modulus\nmapdl.mp(\"ex\", 1, EX) # Young's Modulus (MPA)\nmapdl.mp(\"prxy\", 1, 0.33) # Poisson's ratio\nEP = EX * ET / (EX - ET)\nmapdl.tb(\"biso\", 1)\nmapdl.tbdata(1, 268.9, EP)\n# create material plot\nmapdl.show(\"png\")\nmapdl.tbplot(\"biso\", 1)\nmapdl.show(\"close\")\n\n# define shell elements and their sections\nmapdl.et(1, 181)\n# cylinder\nmapdl.sectype(1, \"shell\")\nmapdl.secdata(ts, 1)\n# L\nmapdl.sectype(2, \"shell\")\nmapdl.secdata(ts + 1.64, 1)\n# Z shaped ring stiffener\nmapdl.sectype(3, \"shell\")\nmapdl.secdata(tw, 1)\n# Plate at z=0 with thickness=25 mm\nmapdl.sectype(4, \"shell\")\nmapdl.secdata(25, 1)\n# Plate at z=L with thickness=25 mm\nmapdl.sectype(5, \"shell\")\nmapdl.secdata(25, 1)\n\n\n# read model of stiffened cylinder\n# download the cdb file\nring_mesh_file = download_tech_demo_data(\n \"td-21\", \"ring_stiffened_cylinder_mesh_file.cdb\"\n)\n\n# read in cdb\nmapdl.cdread(\"db\", ring_mesh_file)\nmapdl.allsel()\nmapdl.eplot(background=\"w\", savefig=\"eplot.png\")\nmapdl.cmsel(\"all\")\n\n###############################################################################\n# Define static prestress analysis\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Displacement boundary conditions are defined to prevent the six rigid body\n# motions. A total of six displacements are therefore applied to three nodes\n# located on the top plate at 0, 90, and 270 degrees; the nodes are restricted\n# so that all rigid translations and rotations are not possible for the\n# cylinder.\n#\n# Loading consists of a uniformly distributed external differential\n# pressure: :math:`P_{ext} = 0.24 MPa`\n\nprint(\"Begin static prestress analysis\")\n\nmapdl.csys(1) # activate cylindrical coordinate system\n\n# Define pressure on plate at z=0\nmapdl.nsel(\"s\", \"loc\", \"z\", 0)\nmapdl.esln(\"s\", 1)\nmapdl.sfe(\"all\", 2, \"pres\", 1, pext)\nmapdl.allsel()\n\n# Define pressure on the rim of plate at z=0\nmapdl.nsel(\"s\", \"loc\", \"z\", 0)\nmapdl.nsel(\"r\", \"loc\", \"x\", r - ts / 2, 760 / 2)\nmapdl.esln(\"s\", 1)\nmapdl.sfe(\"all\", 1, \"pres\", 1, pext)\nmapdl.allsel()\n\n# Define pressure on plate at z=L\nmapdl.nsel(\"s\", \"loc\", \"z\", L)\nmapdl.esln(\"s\", 1)\nmapdl.sfe(\"all\", 2, \"pres\", 1, pext)\nmapdl.allsel()\n\n# Define pressure on the rim of plate at z=L\nmapdl.nsel(\"s\", \"loc\", \"z\", L)\nmapdl.nsel(\"r\", \"loc\", \"x\", r - ts / 2, 760 / 2)\nmapdl.esln(\"s\", 1)\nmapdl.sfe(\"all\", 1, \"pres\", 1, pext)\nmapdl.allsel()\n\n# Define pressure on cylinder\nmapdl.nsel(\"s\", \"loc\", \"x\", r - ts / 2)\nmapdl.esln(\"s\", 1)\nmapdl.sfe(\"all\", 2, \"pres\", 1, pext)\nmapdl.allsel()\n\n# Define displacement BSs to avoid rigid body motion\nmapdl.csys(0) # activate cartesian coordinate system\nmapdl.nsel(\"s\", \"loc\", \"x\", r - ts / 2)\nmapdl.nsel(\"r\", \"loc\", \"y\", 0)\nmapdl.nsel(\"r\", \"loc\", \"z\", 0)\nmapdl.d(\"all\", \"ux\", 0)\nmapdl.d(\"all\", \"uy\", 0)\nmapdl.d(\"all\", \"uz\", 0)\nmapdl.allsel()\n#\nmapdl.nsel(\"s\", \"loc\", \"x\", 0)\nmapdl.nsel(\"r\", \"loc\", \"y\", r - ts / 2)\nmapdl.nsel(\"r\", \"loc\", \"z\", 0)\nmapdl.d(\"all\", \"uz\", 0)\nmapdl.allsel()\n#\nmapdl.nsel(\"s\", \"loc\", \"x\", 0)\nmapdl.nsel(\"r\", \"loc\", \"y\", -(r - ts / 2))\nmapdl.nsel(\"r\", \"loc\", \"z\", 0)\nmapdl.d(\"all\", \"uy\", 0)\nmapdl.d(\"all\", \"uz\", 0)\nmapdl.allsel()\n#\n\n# Print DOF constraints\nprint(mapdl.dlist())\n\n# Solve static prestress analysis\nmapdl.slashsolu()\nmapdl.pstres(\"on\")\nmapdl.antype(\"STATIC\")\noutput = mapdl.solve()\nprint(output)\n\n# Plot total deformation\nmapdl.post1()\nmapdl.set(\"last\")\nmapdl.post_processing.plot_nodal_displacement(\n \"NORM\", smooth_shading=True, savefig=\"nodal_disp_static_prestress.png\"\n)\n\nprint(\"End static prestress analysis\")\n#%%\n###############################################################################\n# Run linear buckling analysis\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# This preliminary analysis predicts the theoretical buckling pressure of the\n# ideal linear elastic structure (perfect cylinder) and the buckled mode shapes\n# used in the next step to generate the imperfections.\n# It is also an efficient way to check the completeness and\n# correctness of modeling.\n# To run the linear buckling analysis, a static solution with prestress effects\n# must be obtained, followed by the eigenvalue buckling solution using the\n# Block Lanczos method and mode expansion.\n\nprint(\"Begin linear buckling analysis\")\n\n# Define and solve linear buckling analysis\nmapdl.slashsolu()\nmapdl.outres(\"all\", \"all\")\nmapdl.antype(\"BUCKLE\")\nmapdl.bucopt(\"lanb\", \"10\")\nmapdl.mxpand(10)\noutput = mapdl.solve()\nprint(output)\n\n# Plot total deformation of first and 10th mode\nmapdl.post1()\nmapdl.set(1, 1)\nmapdl.post_processing.plot_nodal_displacement(\n \"NORM\", smooth_shading=True, savefig=\"nodal_disp_linear_buckling_mode1.png\"\n)\nmapdl.set(1, 10)\nmapdl.post_processing.plot_nodal_displacement(\n \"NORM\", smooth_shading=True, savefig=\"nodal_disp_linear_buckling_mode10.png\"\n)\n\nprint(\"End linear buckling analysis\")\n#%%\n###############################################################################\n# Generate imperfections\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# If a structure is perfectly symmetric, nonsymmetric buckling does not occur\n# numerically, and a nonlinear buckling analysis fails because\n# nonsymmetric buckling responses cannot be triggered. In this problem,\n# the geometry, elements, and pressure are all axisymmetric.\n# It is not possible, therefore, to simulate nonaxisymmetric buckling with\n# the initial model. To overcome this problem, small geometric imperfections\n# (similar to those caused by manufacturing a real structure) must be\n# introduced to trigger the buckling responses.\n# Because the radius of the cylinder is 355.69 mm and the maximum\n# displacement of a mode shape is 1 mm, a factor of 0.1 is applied when\n# updating the geometry with mode shapes. The factor assumes the manufacturing\n# tolerance of the radius to be on the order of 0.1.\n\nprint(\"Begin adding imperfections\")\n\nmapdl.finish()\nmapdl.prep7()\nfor i in range(1, 11):\n mapdl.upgeom(0.1, 1, i, \"buckling\", \"rst\") # Add imperfections as a tenth of each\n # mode shape\nmapdl.finish()\n\nprint(\"Finish adding imperfections\")\n#%%\n###############################################################################\n# Run nonlinear static analysis on geometry with imperfections\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# The nonlinear buckling analysis is a static analysis performed after adding\n# imperfections with large deflection active (NLGEOM,ON), extended to a point\n# where the stiffened cylinder can reach its limit load.\n# To perform the analysis, the load must be allowed to increase using very\n# small time increments so that the expected critical buckling load can\n# be predicted accurately.\n# Note - as this is a buckling analysis, divergence is expected.\n\nprint(\"Begin nonlinear static analysis on imperfect geometry\")\n\nmapdl.slashsolu()\nmapdl.antype(\"STATIC\")\nmapdl.nlgeom(\"on\")\nmapdl.pred(\"on\")\nmapdl.time(1)\nmapdl.nsubst(100, 10000, 10)\nmapdl.rescontrol(\"define\", \"all\", 1)\nmapdl.outres(\"all\", \"all\")\nmapdl.ncnv(2) # Do not terminate the program execution if the solution diverges\nmapdl.allow_ignore = True # in order for PyMAPDL to not raise an error\noutput = mapdl.solve()\nprint(output)\nmapdl.finish()\n\nprint(\"End nonlinear static analysis on imperfect geometry\")\n\n#%%\n###############################################################################\n# Post-buckling analysis\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# An unconverged solution of the nonlinear static analysis could mean that\n# buckling has occurred. In this example, the change in time (or load)\n# increment, and displacement value, occurs between substeps 10 and 11,\n# which corresponds to TIME = 0.51781 and TIME = 0.53806 and to a pressure\n# between 0.124 MPa and 0.129 MPa. It is therefore very likely that buckling\n# occurred at this time; to be sure, the analysis is continued. The goal is to\n# verify the assessment made at this stage by obtaining the load-displacement\n# behavior over a larger range. Because the post-buckling state is unstable,\n# special techniques are necessary to compensate - in this case, nonlinear\n# stabilization is used.\n\nprint(\"Begin post-buckling analysis\")\n\nmapdl.slashsolu() # Restart analysis with stabilization\nmapdl.antype(\"static\", \"restart\", 1, 10)\nmapdl.nsubst(100, 50000, 10)\nmapdl.rescontrol(\"define\", \"last\")\nmapdl.stabilize(\"constant\", \"energy\", 0.000145) # Use energy option\noutput = mapdl.solve()\nprint(output)\nmapdl.finish()\n\nprint(\"End of post-buckling analysis run\")\n\n#%%\n###############################################################################\n# Postprocess buckling analysis in POST1\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n\nprint(\"Begin POST1 postprocessing of post-buckling analysis\")\nmapdl.post1()\nmapdl.set(\"last\")\nmapdl.post_processing.plot_nodal_displacement(\n \"NORM\", smooth_shading=True, savefig=\"nodal_disp_post_buckling.png\"\n)\nmapdl.post_processing.plot_nodal_eqv_stress(savefig=\"nodal_stress_post_buckling.png\")\nmapdl.finish()\nprint(\"End POST1 postprocessing of post-buckling analysis\")\n#%%\n###############################################################################\n# Postprocess buckling analysis in POST26\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n#\n\nprint(\"Begin POST26 postprocessing of post-buckling analysis\")\nmapdl.post26()\n\n\nmapdl.numvar(100) # allow storage for 100 variables\nmapdl.enersol(13, \"sene\") # store stiffness energy\nmapdl.enersol(14, \"sten\") # store artificial stabilization energy\n\nmapdl.axlab(\"X\", \"Radial Displacement\")\nmapdl.axlab(\"Y\", \"Applied Pressure\")\nmapdl.plvar(12)\n# # time history plot of stiffness and stabilization energies\nmapdl.show(\"png\")\nmapdl.plvar(13, 14)\nmapdl.show(\"close\")\n\n# pressure versus axial shortening for some nodes under the upper ring\nmapdl.nsol(2, 67319, \"U\", \"Z\", \"UZ1\")\nmapdl.prod(\n ir=3, ia=2, ib=\"\", ic=\"\", name=\"strain1\", facta=\"\", factb=\"\", factc=-1 / 431.8\n)\nmapdl.prod(ir=12, ia=1, ib=\"\", ic=\"\", name=\"Load\", facta=\"\", factb=\"\", factc=0.24)\nmapdl.xvar(3)\nmapdl.show(\"png\")\nmapdl.xrange(0.01)\nmapdl.yrange(0.24)\nmapdl.axlab(\"X\", \"Axial Shortening\")\nmapdl.axlab(\"Y\", \"Applied Pressure \")\nmapdl.plvar(12)\nmapdl.show(\"close\")\nmapdl.xvar(3)\nmapdl.show(\"png\")\nmapdl.xrange(0.002)\nmapdl.yrange(1)\nmapdl.axlab(\"X\", \"Axial Shortening\")\nmapdl.axlab(\"Y\", \"Time\")\nmapdl.plvar(1)\nmapdl.show(\"png\")\nmapdl.show(\"close\")\n\n# pressure versus radial displacement for the node with max. deformation\nmapdl.nsol(6, 65269, \"U\", \"Y\", \"UY_1\")\nmapdl.prod(ir=7, ia=6, ib=6, ic=\"\", name=\"UY2_1\")\nmapdl.nsol(8, 65269, \"U\", \"X\", \"UX_1\")\nmapdl.prod(ir=9, ia=8, ib=8, ic=\"\", name=\"UX2_1\")\nmapdl.add(10, 7, 9, \"sum\")\nmapdl.sqrt(ir=11, ia=10, name=\"Urad\")\nmapdl.xvar(11)\nmapdl.show(\"png\")\nmapdl.xrange(4)\nmapdl.yrange(0.24)\nmapdl.show(\"png\")\nmapdl.show(\"close\")\nmapdl.finish()\n\nprint(\"End POST26 postprocessing of post-buckling analysis\")\n\n#%%\n###############################################################################\n# Exit MAPDL\n# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n# Exit MAPDL instance\n\nmapdl.exit()\nprint(\"Exited MAPDL\")\n","repo_name":"ansys/pymapdl-examples","sub_path":"examples/tech-demos/21-example-technology-showcase-buckling.py","file_name":"21-example-technology-showcase-buckling.py","file_ext":"py","file_size_in_byte":13861,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"70625831846","text":"from tkinter import Button, Label, messagebox\n#import tkMessageBox\nimport random\nimport minesweepsetting\nimport ctypes\nimport sys\n\nclass Cell:\n all=[]\n cellcount=minesweepsetting.cellscount\n cellcountlabelobject=None\n def __init__(self,x,y,is_mine=False):\n self.is_mine=is_mine\n self.isopened=False\n self.cellbuttonobj=None\n self.possiblemine=False\n self.x=x\n self.y=y\n #Append the object to the cell.all list \n Cell.all.append(self)\n def createbuttonobj(self, location):\n btn=Button(\n #bg='Red',\n location,\n width=12,\n height=4,\n #chaning the text to be displayed from simply\"Text\" \n # to a formatted string that prints the range imported from minesweeper\n #text=f\"{self.x},{self.y}\" \n ) \n#need to make the buttons left and right clickable also \n btn.bind('', self.leftclick) \n btn.bind('', self.rightclick)\n self.cellbuttonobj=btn\n \n @staticmethod\n def createcellcountlabel(location):\n lbl= Label(\n location,\n bg='RosyBrown2',\n text=f\" Cells Left : {Cell.cellcount}\",\n width=12,\n height=4,\n font=(\"\", 30)\n )\n #return lbl\n Cell.cellcountlabelobject= lbl \n \n #simple display of a message when we left-click \n '''def leftclick(self, event):\n print(event)\n print(\"I am left clicked\")'''\n#if the chosen cell is a mine it turns background red\n def leftclick(self, action):\n if self.is_mine:\n self.showmine()\n else:\n if self.surroundedcellsmineslength==0:\n for cellobj in self.suroundedcells:\n cellobj.showcell()\n self.showcell()\n #if no of mines is equal to the cells left, player won\n if Cell.cellcount==minesweepsetting.Minescount:\n messagebox.showerror(\"YOU WON\", \"Congratulations! You Won!\")\n \n #cancel left and right click events if cell is already opened:\n self.cellbuttonobj.unbind('')\n self.cellbuttonobj.unbind('') \n \n def getcellbyaxis(self,x,y):\n #Return cell object based on a value of x and y\n for cell in Cell.all:\n if cell.x==x and cell.y==y:\n return cell\n \n @property\n def suroundedcells(self):\n #print(self.getcellbyaxis(0,0))\n cells=[\n self.getcellbyaxis(self.x,self.y+1),\n self.getcellbyaxis(self.x,self.y-1),\n self.getcellbyaxis(self.x+1,self.y),\n self.getcellbyaxis(self.x-1,self.y),\n self.getcellbyaxis(self.x+1,self.y+1),\n self.getcellbyaxis(self.x+1,self.y-1),\n self.getcellbyaxis(self.x-1,self.y-1),\n self.getcellbyaxis(self.x-1,self.y+1)\n ]\n cells=[cell for cell in cells if cell is not None]\n #print(surroundedcells)\n return cells\n \n @property\n def surroundedcellsmineslength(self):\n count=0\n for cell in self.suroundedcells:\n if cell.is_mine:\n count+=1\n return count \n \n \n def showcell(self):\n if not self.isopened:\n \n #decrease cell count each time, but only is cell not open\n Cell.cellcount-=1\n#we started by printing the no.of mines in the console. Now we show it on the button.\n #print(self.surroundedcellsmineslength)\n self.cellbuttonobj.configure(text=self.surroundedcellsmineslength)\n #replace cell count with new count\n if Cell.cellcountlabelobject:\n Cell.cellcountlabelobject.configure(\n text=f\" Cells Left : {Cell.cellcount}\")\n #after marking it yello, but then left clicking, it should revert to normal color:\n self.cellbuttonobj.configure(\n highlightbackground='SystemButtonFace'\n ) \n #mark the cell as opened\n self.isopened= True\n \n def showmine(self):\n self.cellbuttonobj.config(highlightbackground='red')\n messagebox.showerror(\"GAME OVER\", \"Woops...you clicked on a mine!! GAME OVER\")\n sys.exit() \n \n def rightclick(self,event):\n if not self.possiblemine:\n self.cellbuttonobj.configure(\n highlightbackground='orange'\n ) \n self.possiblemine=True\n else:\n self.cellbuttonobj.configure(\n highlightbackground='SystemButtonFace'\n )\n self.possiblemine=False \n #print(event)\n #print(\"I am right clicked\") \n \n#self.cellbuttonobj=btn \n @staticmethod\n def randomisemines():\n #random.sample accepts the list first and then the number of objects to be chosen randomly\n '''mlist = ['a','b','c','d']\n name=random.sample(mlist, 2) \n print(name)'''\n minecells=random.sample(Cell.all, minesweepsetting.Minescount)\n #print(minecells)\n #(Converting some cells into mines):\n for minecells in minecells:\n minecells.is_mine = True\n \n \n def __repr__(self):\n return f\"Cell({self.x},{self.y})\"\n \n \n ","repo_name":"shumailah/minesweeper-using-python","sub_path":"cells.py","file_name":"cells.py","file_ext":"py","file_size_in_byte":5380,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"23903908791","text":"'''\r\nMisc test cases\r\n'''\r\n\r\nimport unittest\r\nimport utils\r\nfrom struct import pack, unpack\r\n\r\ndef suite():\r\n\tsuite = unittest.TestSuite()\r\n\tsuite.addTest(FixupTest1())\r\n\tsuite.addTest(FixupTest2())\r\n\tsuite.addTest(FixupTest3())\r\n\treturn suite\r\n\r\nclass FixupTest1(utils.PeachTcpTestCase):\r\n\tdef runTest(self):\r\n\t\t# Test\r\n\t\tself.peachUtils.RunPeachXml(\"fixups1.xml\")\r\n\t\tret = self.peachUtils.GetListenerData()\r\n\t\tdata = \"DAAAAAAAAAAyMzkwODIwMzk4NDVYewZM\"\r\n\t\tassert ret == data, 'fixups1.xml failed. [%s]' % ret\r\n\r\nclass FixupTest2(utils.PeachTcpTestCase):\r\n\tdef runTest(self):\r\n\t\t# Test\r\n\t\tself.peachUtils.RunPeachXml(\"fixups2.xml\")\r\n\t\tret = self.peachUtils.GetListenerData()\r\n\t\tdata = \"FAAAAAAAAAAyMzkwODIwMzk4NDVYewZM\"\r\n\t\tassert ret == data, 'fixups2.xml failed. [%s]' % ret\r\n\t\r\nclass FixupTest3(utils.PeachTcpTestCase):\r\n\tdef runTest(self):\r\n\t\t# Test\r\n\t\tself.peachUtils.RunPeachXml(\"fixups3.xml\")\r\n\t\tret = self.peachUtils.GetListenerData()\r\n\t\tdata = \"cnqZSaQ0E05ilAAAMjkwMTM0MDIxMzk3NDM5MDc0MTIzNDEyMw==\"\r\n\t\tassert ret == data, 'fixups3.xml failed. [%s]' % ret\r\n\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()\r\n\r\n# end\r\n","repo_name":"delphi0127/generate-network-xmls-for-peach","sub_path":"Peach2.3.9/test/fixups.py","file_name":"fixups.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"52"} +{"seq_id":"45048624196","text":"import pygame\nimport random\n\n# This is a 2d vector that holds the size of the screen.\nSCREEN_SIZE = [1024, 768]\n\n# Sets the prefered fps. Mostly affects the speed of the main gameloop,\n# although complex calculations may cause the fps to drop.\nFPS = 60 #FUN FACT, if you run this at > 5000 fps it stops hurting your eyes ...\n\n# This is a constant primarily used to set the frequency of filled shapes appearing,\n# yet it also affects the max line width and min object size.\n# Min object size must be larger than the max fill width.\nOBJECT_MAX_FILL = 1\nOBJECT_MAX_SIZE = 400 # This is a constant used to choose object size.\n\n# Starts pygame.\npygame.init()\n\n# Makes a screen, size by screen_size and names it.\nDISPLAY_SURFACE = pygame.display.set_mode(SCREEN_SIZE)\npygame.display.set_caption(\"Random Shapes\")\n\n# Runtime constant used to modify movement.\n# Delta time is set to the change in time after each frame.\ndelta_time = 0\n\n# Starts the game loop.\ngame_stopped = False\nwhile not game_stopped:\n time_at_frame_start = pygame.time.get_ticks() # Get time before calulations.\n\n # Input handeler\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n game_stopped = True\n\n # Chooses a random shape to draw\n random_number = random.randint(1, 4)\n\n # Pre calculate shared parameters.\n random_colour = (random.randint(0, 255), random.randint(0, 255), random.randint(0, 255))\n random_fill = random.randint(0, OBJECT_MAX_FILL)\n\n # Choose the shape to draw.\n if random_number == 1:\n '''----RECTANGLE----'''\n # Calculate Perameters\n random_position = ( random.randint(0, SCREEN_SIZE[0]), random.randint(0, SCREEN_SIZE[1]) )\n random_size = ( random.randint(OBJECT_MAX_FILL + 1, OBJECT_MAX_SIZE), random.randint(OBJECT_MAX_FILL + 1, OBJECT_MAX_SIZE) )\n\n # Draw Object\n pygame.draw.rect(DISPLAY_SURFACE, random_colour, (random_position, random_size), random_fill)\n\n elif random_number == 2:\n '''----CIRCLE----'''\n # Calculate Perameters\n random_position = ( random.randint(0, SCREEN_SIZE[0]), random.randint(0, SCREEN_SIZE[1]) )\n random_radius = random.randint(OBJECT_MAX_FILL + 1, OBJECT_MAX_SIZE/2)\n\n # Draw Object\n pygame.draw.circle(DISPLAY_SURFACE, random_colour, random_position, random_radius, random_fill)\n\n elif random_number == 3:\n '''----ELLIPSE----'''\n # Calculate Parameters\n random_position = ( random.randint(0, SCREEN_SIZE[0]), random.randint(0, SCREEN_SIZE[1]) )\n random_size = ( random.randint(OBJECT_MAX_FILL + 5, OBJECT_MAX_SIZE), random.randint(OBJECT_MAX_FILL + 5, OBJECT_MAX_SIZE) )\n\n # Draw Object\n pygame.draw.ellipse(DISPLAY_SURFACE, random_colour, (random_position, random_size), random_fill)\n\n elif random_number == 4:\n '''----POLYGON----'''\n # Calculate Parameters\n random_point_list = [( random.randint(0, SCREEN_SIZE[0]), random.randint(0, SCREEN_SIZE[1]) ) for x in range(10)] #Done\n\n # Draw Object\n pygame.draw.polygon(DISPLAY_SURFACE, random_colour, random_point_list, 0) # Polygons look sucky as just a line\n\n pygame.display.update() # Updates the display with changes.\n\n # Set the wait_time (after calculations have been made) (in ms, not seconds)\n # wait_time = time_single_frame_ - time_elapsed_\n wait_time = ((1 / float(FPS)) * 1000) - (pygame.time.get_ticks() - time_at_frame_start)\n\n pygame.time.wait(int(wait_time)) # Pause the program for the set amount of time.\n\n delta_time = wait_time / 1000.0 # This updates the delta time variable. (in seconds, not ms)\n #print delta_time\n\n# Close pygame before application closes.\npygame.quit()\n","repo_name":"EarthenSky/Python-Practice","sub_path":"Lesson2Folder-Pygame/Ex1.py","file_name":"Ex1.py","file_ext":"py","file_size_in_byte":3721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35616007569","text":"import os\n\nimport pytest\n\nfrom tests.fixtures.client import ClientSpawner\nfrom virtool.config import get_config_from_app\nfrom virtool.data.layer import DataLayer\nfrom virtool.fake.next import DataFaker\nfrom virtool.samples.fake import READ_FILES_PATH, copy_reads_file, create_fake_sample\n\n\n@pytest.mark.parametrize(\"paired\", [True, False])\n@pytest.mark.parametrize(\"finalized\", [True, False])\nasync def test_create_fake_sample(\n paired,\n finalized,\n data_layer: DataLayer,\n fake2: DataFaker,\n snapshot,\n spawn_client: ClientSpawner,\n static_time,\n):\n client = await spawn_client(authenticated=True)\n\n user = await fake2.users.create()\n\n await create_fake_sample(\n client.app, \"sample_1\", user.id, finalized=finalized, paired=paired\n )\n\n sample = await data_layer.samples.get(\"sample_1\")\n\n if finalized is True:\n assert len(sample.reads) == (2 if paired else 1)\n assert sample.ready is True\n\n assert sample == snapshot\n\n\nasync def test_copy_reads_file(app):\n file_path = READ_FILES_PATH / \"paired_1.fq.gz\"\n\n await copy_reads_file(app, file_path, \"reads_1.fq.gz\", \"sample_1\")\n\n assert os.listdir(get_config_from_app(app).data_path / \"samples\" / \"sample_1\") == [\n \"reads_1.fq.gz\"\n ]\n","repo_name":"virtool/virtool","sub_path":"tests/samples/test_fake.py","file_name":"test_fake.py","file_ext":"py","file_size_in_byte":1262,"program_lang":"python","lang":"en","doc_type":"code","stars":41,"dataset":"github-code","pt":"52"} +{"seq_id":"6796662804","text":"import torch\nimport torch.nn as nn\nfrom torch.nn import init\nimport functools\nfrom torch.optim import lr_scheduler\n\nimport torch.nn.functional as F\n\nimport math\nimport torch.utils.model_zoo as model_zoo\nimport sys\n\n###############################################################################\n# Helper Functions\n###############################################################################\n\n\ndef get_norm_layer(norm_type='instance'):\n if norm_type == 'batch':\n norm_layer = functools.partial(nn.BatchNorm2d, affine=True)\n elif norm_type == 'instance':\n norm_layer = functools.partial(nn.InstanceNorm2d, affine=False, track_running_stats=False)\n elif norm_type == 'none':\n norm_layer = None\n else:\n raise NotImplementedError('normalization layer [%s] is not found' % norm_type)\n return norm_layer\n\n\ndef get_scheduler(optimizer, opt):\n if opt.lr_policy == 'lambda':\n def lambda_rule(epoch):\n lr_l = 1.0 - max(0, epoch + opt.epoch_count - opt.niter) / float(opt.niter_decay + 1)\n return lr_l\n scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lambda_rule)\n elif opt.lr_policy == 'step':\n scheduler = lr_scheduler.StepLR(optimizer, step_size=opt.lr_decay_iters, gamma=0.1)\n elif opt.lr_policy == 'plateau':\n scheduler = lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.2, threshold=0.01, patience=5)\n elif opt.lr_policy == 'cosine':\n scheduler = lr_scheduler.CosineAnnealingLR(optimizer, T_max=opt.niter, eta_min=0)\n else:\n return NotImplementedError('learning rate policy [%s] is not implemented', opt.lr_policy)\n return scheduler\n\n\ndef init_weights(net, init_type='normal', gain=0.02):\n def init_func(m):\n classname = m.__class__.__name__\n if hasattr(m, 'weight') and (classname.find('Conv') != -1 or classname.find('Linear') != -1):\n if init_type == 'normal':\n init.normal_(m.weight.data, 0.0, gain)\n elif init_type == 'xavier':\n init.xavier_normal_(m.weight.data, gain=gain)\n elif init_type == 'kaiming':\n init.kaiming_normal_(m.weight.data, a=0, mode='fan_in')\n elif init_type == 'orthogonal':\n init.orthogonal_(m.weight.data, gain=gain)\n else:\n raise NotImplementedError('initialization method [%s] is not implemented' % init_type)\n if hasattr(m, 'bias') and m.bias is not None:\n init.constant_(m.bias.data, 0.0)\n elif classname.find('BatchNorm2d') != -1:\n init.normal_(m.weight.data, 1.0, gain)\n init.constant_(m.bias.data, 0.0)\n\n print('initialize network with %s' % init_type)\n net.apply(init_func)\n\n\ndef init_net(net, init_type='normal', init_gain=0.02, gpu_ids=[]):\n if len(gpu_ids) > 0:\n assert(torch.cuda.is_available())\n net.to(gpu_ids[0])\n net = torch.nn.DataParallel(net, gpu_ids)\n init_weights(net, init_type, gain=init_gain)\n return net\n\n\ndef define_G(input_nc, output_nc, ngf, netG, norm='batch', use_dropout=False, init_type='normal',\n init_gain=0.02, gpu_ids=[], depth=18, fpn_weights=[1.0, 1.0, 1.0, 1.0]):\n net = None\n norm_layer = get_norm_layer(norm_type=norm)\n\n if netG == 'resnet_9blocks':\n net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)\n elif netG == 'resnet_6blocks':\n net = ResnetGenerator(input_nc, output_nc, ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=6)\n elif netG == 'resnet_fpn':\n # Create the model\n if depth == 18:\n net = resnet18(input_nc, output_nc, ngf, fpn_weights, use_dropout=use_dropout, pretrained=False)\n # print \"EVET\"\n # netG_B2A = resnet18(pretrained=False)\n elif depth == 34:\n net = resnet34(input_nc, output_nc, ngf, fpn_weights, use_dropout=use_dropout, pretrained=False)\n # netG_B2A = resnet34(pretrained=False)\n elif netG == \"ablation_model1\":\n net = AblationModel1(BasicBlock_Ganilla, [2, 2, 2, 2])\n elif netG == \"ablation_model2\":\n net = AblationModel2(ngf, norm_layer=norm_layer, use_dropout=use_dropout, n_blocks=9)\n elif netG == 'unet_128':\n net = UnetGenerator(input_nc, output_nc, 7, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n elif netG == 'unet_256':\n net = UnetGenerator(input_nc, output_nc, 8, ngf, norm_layer=norm_layer, use_dropout=use_dropout)\n else:\n raise NotImplementedError('Generator model name [%s] is not recognized' % netG)\n return init_net(net, init_type, init_gain, gpu_ids)\n\n\ndef define_D(input_nc, ndf, netD,\n n_layers_D=3, norm='batch', use_sigmoid=False, init_type='normal', init_gain=0.02, gpu_ids=[]):\n net = None\n norm_layer = get_norm_layer(norm_type=norm)\n\n if netD == 'basic':\n net = NLayerDiscriminator(input_nc, ndf, n_layers=3, norm_layer=norm_layer, use_sigmoid=use_sigmoid)\n elif netD == 'n_layers':\n net = NLayerDiscriminator(input_nc, ndf, n_layers_D, norm_layer=norm_layer, use_sigmoid=use_sigmoid)\n elif netD == 'pixel':\n net = PixelDiscriminator(input_nc, ndf, norm_layer=norm_layer, use_sigmoid=use_sigmoid)\n else:\n raise NotImplementedError('Discriminator model name [%s] is not recognized' % net)\n return init_net(net, init_type, init_gain, gpu_ids)\n\n\n##############################################################################\n# Classes\n##############################################################################\n\n\n# Defines the GAN loss which uses either LSGAN or the regular GAN.\n# When LSGAN is used, it is basically same as MSELoss,\n# but it abstracts away the need to create the target label tensor\n# that has the same size as the input\nclass GANLoss(nn.Module):\n def __init__(self, use_lsgan=True, target_real_label=1.0, target_fake_label=0.0):\n super(GANLoss, self).__init__()\n self.register_buffer('real_label', torch.tensor(target_real_label))\n self.register_buffer('fake_label', torch.tensor(target_fake_label))\n if use_lsgan:\n self.loss = nn.MSELoss()\n else:\n self.loss = nn.BCELoss()\n\n def get_target_tensor(self, input, target_is_real):\n if target_is_real:\n target_tensor = self.real_label\n else:\n target_tensor = self.fake_label\n return target_tensor.expand_as(input)\n\n def __call__(self, input, target_is_real):\n target_tensor = self.get_target_tensor(input, target_is_real)\n return self.loss(input, target_tensor)\n\n\n# Defines the generator that consists of Resnet blocks between a few\n# downsampling/upsampling operations.\n# Code and idea originally from Justin Johnson's architecture.\n# https://github.com/jcjohnson/fast-neural-style/\nclass ResnetGenerator(nn.Module):\n def __init__(self, input_nc, output_nc, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=6, padding_type='reflect'):\n assert(n_blocks >= 0)\n super(ResnetGenerator, self).__init__()\n self.input_nc = input_nc\n self.output_nc = output_nc\n self.ngf = ngf\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n model = [nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, ngf, kernel_size=7, padding=0,\n bias=use_bias),\n norm_layer(ngf),\n nn.ReLU(True)]\n\n n_downsampling = 2\n for i in range(n_downsampling):\n mult = 2**i\n model += [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3,\n stride=2, padding=1, bias=use_bias),\n norm_layer(ngf * mult * 2),\n nn.ReLU(True)]\n\n mult = 2**n_downsampling\n for i in range(n_blocks):\n model += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout, use_bias=use_bias)]\n\n for i in range(n_downsampling):\n mult = 2**(n_downsampling - i)\n model += [nn.ConvTranspose2d(ngf * mult, int(ngf * mult / 2),\n kernel_size=3, stride=2,\n padding=1, output_padding=1,\n bias=use_bias),\n norm_layer(int(ngf * mult / 2)),\n nn.ReLU(True)]\n model += [nn.ReflectionPad2d(3)]\n model += [nn.Conv2d(ngf, output_nc, kernel_size=7, padding=0)]\n model += [nn.Tanh()]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, input):\n return self.model(input)\n\n\n# Define a resnet block\nclass ResnetBlock(nn.Module):\n def __init__(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n super(ResnetBlock, self).__init__()\n self.conv_block = self.build_conv_block(dim, padding_type, norm_layer, use_dropout, use_bias)\n\n def build_conv_block(self, dim, padding_type, norm_layer, use_dropout, use_bias):\n conv_block = []\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias),\n norm_layer(dim),\n nn.ReLU(True)]\n if use_dropout:\n conv_block += [nn.Dropout(0.5)]\n\n p = 0\n if padding_type == 'reflect':\n conv_block += [nn.ReflectionPad2d(1)]\n elif padding_type == 'replicate':\n conv_block += [nn.ReplicationPad2d(1)]\n elif padding_type == 'zero':\n p = 1\n else:\n raise NotImplementedError('padding [%s] is not implemented' % padding_type)\n conv_block += [nn.Conv2d(dim, dim, kernel_size=3, padding=p, bias=use_bias),\n norm_layer(dim)]\n\n return nn.Sequential(*conv_block)\n\n def forward(self, x):\n out = x + self.conv_block(x)\n return out\n\n\n# Defines the Unet generator.\n# |num_downs|: number of downsamplings in UNet. For example,\n# if |num_downs| == 7, image of size 128x128 will become of size 1x1\n# at the bottleneck\nclass UnetGenerator(nn.Module):\n def __init__(self, input_nc, output_nc, num_downs, ngf=64,\n norm_layer=nn.BatchNorm2d, use_dropout=False):\n super(UnetGenerator, self).__init__()\n\n # construct unet structure\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=None, norm_layer=norm_layer, innermost=True)\n for i in range(num_downs - 5):\n unet_block = UnetSkipConnectionBlock(ngf * 8, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer, use_dropout=use_dropout)\n unet_block = UnetSkipConnectionBlock(ngf * 4, ngf * 8, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf * 2, ngf * 4, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(ngf, ngf * 2, input_nc=None, submodule=unet_block, norm_layer=norm_layer)\n unet_block = UnetSkipConnectionBlock(output_nc, ngf, input_nc=input_nc, submodule=unet_block, outermost=True, norm_layer=norm_layer)\n\n self.model = unet_block\n\n def forward(self, input):\n return self.model(input)\n\n\n# Defines the submodule with skip connection.\n# X -------------------identity---------------------- X\n# |-- downsampling -- |submodule| -- upsampling --|\nclass UnetSkipConnectionBlock(nn.Module):\n def __init__(self, outer_nc, inner_nc, input_nc=None,\n submodule=None, outermost=False, innermost=False, norm_layer=nn.BatchNorm2d, use_dropout=False):\n super(UnetSkipConnectionBlock, self).__init__()\n self.outermost = outermost\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n if input_nc is None:\n input_nc = outer_nc\n downconv = nn.Conv2d(input_nc, inner_nc, kernel_size=4,\n stride=2, padding=1, bias=use_bias)\n downrelu = nn.LeakyReLU(0.2, True)\n downnorm = norm_layer(inner_nc)\n uprelu = nn.ReLU(True)\n upnorm = norm_layer(outer_nc)\n\n if outermost:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1)\n down = [downconv]\n up = [uprelu, upconv, nn.Tanh()]\n model = down + [submodule] + up\n elif innermost:\n upconv = nn.ConvTranspose2d(inner_nc, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv]\n up = [uprelu, upconv, upnorm]\n model = down + up\n else:\n upconv = nn.ConvTranspose2d(inner_nc * 2, outer_nc,\n kernel_size=4, stride=2,\n padding=1, bias=use_bias)\n down = [downrelu, downconv, downnorm]\n up = [uprelu, upconv, upnorm]\n\n if use_dropout:\n model = down + [submodule] + up + [nn.Dropout(0.5)]\n else:\n model = down + [submodule] + up\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n if self.outermost:\n return self.model(x)\n else:\n return torch.cat([x, self.model(x)], 1)\n\n\n# Defines the PatchGAN discriminator with the specified arguments.\nclass NLayerDiscriminator(nn.Module):\n def __init__(self, input_nc, ndf=64, n_layers=3, norm_layer=nn.BatchNorm2d, use_sigmoid=False):\n super(NLayerDiscriminator, self).__init__()\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n kw = 4\n padw = 1\n sequence = [\n nn.Conv2d(input_nc, ndf, kernel_size=kw, stride=2, padding=padw),\n nn.LeakyReLU(0.2, True)\n ]\n\n nf_mult = 1\n nf_mult_prev = 1\n for n in range(1, n_layers):\n nf_mult_prev = nf_mult\n nf_mult = min(2**n, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,\n kernel_size=kw, stride=2, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n nf_mult_prev = nf_mult\n nf_mult = min(2**n_layers, 8)\n sequence += [\n nn.Conv2d(ndf * nf_mult_prev, ndf * nf_mult,\n kernel_size=kw, stride=1, padding=padw, bias=use_bias),\n norm_layer(ndf * nf_mult),\n nn.LeakyReLU(0.2, True)\n ]\n\n sequence += [nn.Conv2d(ndf * nf_mult, 1, kernel_size=kw, stride=1, padding=padw)]\n\n if use_sigmoid:\n sequence += [nn.Sigmoid()]\n\n self.model = nn.Sequential(*sequence)\n\n def forward(self, input):\n return self.model(input)\n\n\nclass PixelDiscriminator(nn.Module):\n def __init__(self, input_nc, ndf=64, norm_layer=nn.BatchNorm2d, use_sigmoid=False):\n super(PixelDiscriminator, self).__init__()\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n self.net = [\n nn.Conv2d(input_nc, ndf, kernel_size=1, stride=1, padding=0),\n nn.LeakyReLU(0.2, True),\n nn.Conv2d(ndf, ndf * 2, kernel_size=1, stride=1, padding=0, bias=use_bias),\n norm_layer(ndf * 2),\n nn.LeakyReLU(0.2, True),\n nn.Conv2d(ndf * 2, 1, kernel_size=1, stride=1, padding=0, bias=use_bias)]\n\n if use_sigmoid:\n self.net.append(nn.Sigmoid())\n\n self.net = nn.Sequential(*self.net)\n\n def forward(self, input):\n return self.net(input)\n\n\n######## GANILLA #########\n\n\nmodel_urls = {\n 'resnet18': 'https://download.pytorch.org/models/resnet18-5c106cde.pth',\n 'resnet34': 'https://download.pytorch.org/models/resnet34-333f7ec4.pth',\n 'resnet50': 'https://download.pytorch.org/models/resnet50-19c8e357.pth',\n 'resnet101': 'https://download.pytorch.org/models/resnet101-5d3b4d8f.pth',\n 'resnet152': 'https://download.pytorch.org/models/resnet152-b121ed2d.pth',\n}\n\n\ndef conv3x3(in_planes, out_planes, stride=1):\n \"\"\"3x3 convolution with padding\"\"\"\n return nn.Conv2d(in_planes, out_planes, kernel_size=3, stride=stride,\n padding=0, bias=True)\n\n\nclass BasicBlock_orj(nn.Module):\n expansion = 1\n\n def __init__(self, inplanes, planes, stride=1, downsample=None):\n super(BasicBlock_orj, self).__init__()\n self.rp1 = nn.ReflectionPad2d(1)\n self.conv1 = conv3x3(inplanes, planes, stride)\n self.in1 = nn.InstanceNorm2d(planes)\n self.relu = nn.ReLU(inplace=True)\n self.rp2 = nn.ReflectionPad2d(1)\n self.conv2 = conv3x3(planes, planes)\n self.in2 = nn.InstanceNorm2d(planes)\n self.downsample = downsample\n self.stride = stride\n\n def forward(self, x):\n\n residual = x\n\n out = self.rp1(x)\n out = self.conv1(out)\n out = self.in1(out)\n out = self.relu(out)\n\n out = self.rp2(out)\n out = self.conv2(out)\n out = self.in2(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out += residual\n out = self.relu(out)\n\n return out\n\n\nclass BasicBlock_Ganilla(nn.Module):\n expansion = 1\n\n def __init__(self, in_planes, planes, use_dropout, stride=1):\n super(BasicBlock_Ganilla, self).__init__()\n self.rp1 = nn.ReflectionPad2d(1)\n self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, stride=stride, padding=0, bias=False)\n self.bn1 = nn.InstanceNorm2d(planes)\n self.use_dropout = use_dropout\n if use_dropout:\n self.dropout = nn.Dropout(0.5)\n self.rp2 = nn.ReflectionPad2d(1)\n self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, stride=1, padding=0, bias=False)\n self.bn2 = nn.InstanceNorm2d(planes)\n self.out_planes = planes\n\n self.shortcut = nn.Sequential()\n if stride != 1 or in_planes != self.expansion*planes:\n self.shortcut = nn.Sequential(\n nn.Conv2d(in_planes, self.expansion*planes, kernel_size=1, stride=stride, bias=False),\n nn.InstanceNorm2d(self.expansion*planes)\n )\n\n self.final_conv = nn.Sequential(\n nn.ReflectionPad2d(1),\n nn.Conv2d(self.expansion * planes * 2, self.expansion * planes, kernel_size=3, stride=1,\n padding=0, bias=False),\n nn.InstanceNorm2d(self.expansion * planes)\n )\n else:\n self.final_conv = nn.Sequential(\n nn.ReflectionPad2d(1),\n nn.Conv2d(planes*2, planes, kernel_size=3, stride=1, padding=0, bias=False),\n nn.InstanceNorm2d(planes)\n )\n\n def forward(self, x):\n out = F.relu(self.bn1(self.conv1(self.rp1(x))))\n if self.use_dropout:\n out = self.dropout(out)\n out = self.bn2(self.conv2(self.rp2(out)))\n inputt = self.shortcut(x)\n catted = torch.cat((out, inputt), 1)\n out = self.final_conv(catted)\n out = F.relu(out)\n return out\n\n\nclass PyramidFeatures_v3(nn.Module):\n def __init__(self, C3_size, C4_size, C5_size, feature_size=128):\n super(PyramidFeatures_v3, self).__init__()\n\n # upsample C5 to get P5 from the FPN paper\n self.P5_1 = nn.Conv2d(C5_size, feature_size, kernel_size=1, stride=1, padding=0)\n self.P5_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n #self.rp1 = nn.ReflectionPad2d(1)\n #self.P5_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=0)\n\n # add P5 elementwise to C4\n self.P4_1 = nn.Conv2d(C4_size, feature_size, kernel_size=1, stride=1, padding=0)\n self.P4_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n #self.rp2 = nn.ReflectionPad2d(1)\n #self.P4_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=0)\n\n # add P4 elementwise to C3\n self.P3_1 = nn.Conv2d(C3_size, feature_size, kernel_size=1, stride=1, padding=0)\n self.P3_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n # self.rp3 = nn.ReflectionPad2d(1)\n # self.P3_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=0)\n\n #self.P2_1 = nn.Conv2d(C2_size, feature_size, kernel_size=1, stride=1, padding=0)\n # self.P2_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n # self.rp4 = nn.ReflectionPad2d(1)\n # self.P2_2 = nn.Conv2d(feature_size, feature_size/2, kernel_size=3, stride=1, padding=0)\n\n self.P1_1 = nn.Conv2d(feature_size, feature_size, kernel_size=1, stride=1, padding=0)\n self.P1_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n self.rp5 = nn.ReflectionPad2d(1)\n self.P1_2 = nn.Conv2d(feature_size, feature_size/2, kernel_size=3, stride=1, padding=0)\n\n def forward(self, inputs):\n\n C3, C4, C5 = inputs\n\n P5_x = self.P5_1(C5)\n P5_upsampled_x = self.P5_upsampled(P5_x)\n\n P4_x = self.P4_1(C4)\n P4_x = P5_upsampled_x + P4_x\n P4_upsampled_x = self.P4_upsampled(P4_x)\n\n P3_x = self.P3_1(C3)\n P3_x = P3_x + P4_upsampled_x\n P3_upsampled_x = self.P3_upsampled(P3_x)\n\n P1_x = self.P1_1(P3_upsampled_x)\n P1_upsampled_x = self.P1_upsampled(P1_x)\n P2_x = self.rp5(P1_upsampled_x)\n P2_x = self.P1_2(P2_x)\n\n return P2_x\n\n\nclass PyramidFeatures(nn.Module):\n def __init__(self, C2_size, C3_size, C4_size, C5_size, fpn_weights, feature_size=128):\n super(PyramidFeatures, self).__init__()\n\n self.sum_weights = fpn_weights #[1.0, 0.5, 0.5, 0.5]\n\n # upsample C5 to get P5 from the FPN paper\n self.P5_1 = nn.Conv2d(C5_size, feature_size, kernel_size=1, stride=1, padding=0)\n self.P5_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n #self.rp1 = nn.ReflectionPad2d(1)\n #self.P5_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=0)\n\n # add P5 elementwise to C4\n self.P4_1 = nn.Conv2d(C4_size, feature_size, kernel_size=1, stride=1, padding=0)\n self.P4_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n #self.rp2 = nn.ReflectionPad2d(1)\n #self.P4_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=0)\n\n # add P4 elementwise to C3\n self.P3_1 = nn.Conv2d(C3_size, feature_size, kernel_size=1, stride=1, padding=0)\n self.P3_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n #self.rp3 = nn.ReflectionPad2d(1)\n #self.P3_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=0)\n\n self.P2_1 = nn.Conv2d(C2_size, feature_size, kernel_size=1, stride=1, padding=0)\n self.P2_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n self.rp4 = nn.ReflectionPad2d(1)\n self.P2_2 = nn.Conv2d(int(feature_size), int(feature_size/2), kernel_size=3, stride=1, padding=0)\n\n #self.P1_1 = nn.Conv2d(feature_size, feature_size, kernel_size=1, stride=1, padding=0)\n #self.P1_upsampled = nn.Upsample(scale_factor=2, mode='nearest')\n #self.rp5 = nn.ReflectionPad2d(1)\n #self.P1_2 = nn.Conv2d(feature_size, feature_size, kernel_size=3, stride=1, padding=0)\n\n def forward(self, inputs):\n\n C2, C3, C4, C5 = inputs\n\n i = 0\n P5_x = self.P5_1(C5) * self.sum_weights[i]\n P5_upsampled_x = self.P5_upsampled(P5_x)\n #P5_x = self.rp1(P5_x)\n # #P5_x = self.P5_2(P5_x)\n i += 1\n P4_x = self.P4_1(C4) * self.sum_weights[i]\n P4_x = P5_upsampled_x + P4_x\n P4_upsampled_x = self.P4_upsampled(P4_x)\n #P4_x = self.rp2(P4_x)\n # #P4_x = self.P4_2(P4_x)\n i += 1\n P3_x = self.P3_1(C3) * self.sum_weights[i]\n P3_x = P3_x + P4_upsampled_x\n P3_upsampled_x = self.P3_upsampled(P3_x)\n #P3_x = self.rp3(P3_x)\n #P3_x = self.P3_2(P3_x)\n i += 1\n P2_x = self.P2_1(C2) * self.sum_weights[i]\n P2_x = P2_x * self.sum_weights[2] + P3_upsampled_x\n P2_upsampled_x = self.P2_upsampled(P2_x)\n P2_x = self.rp4(P2_upsampled_x)\n P2_x = self.P2_2(P2_x)\n\n return P2_x\n\n\nclass ResNet(nn.Module):\n\n def __init__(self, input_nc, output_nc, ngf, fpn_weights, block, layers, use_dropout):\n self.inplanes = ngf\n super(ResNet, self).__init__()\n\n # first conv\n self.pad1 = nn.ReflectionPad2d(input_nc)\n self.conv1 = nn.Conv2d(input_nc, ngf, kernel_size=7, stride=1, padding=0, bias=True)\n self.in1 = nn.InstanceNorm2d(ngf)\n self.relu = nn.ReLU(inplace=True)\n self.pad2 = nn.ReflectionPad2d(1)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0)\n\n # Output layer\n self.pad3 = nn.ReflectionPad2d(output_nc)\n self.conv2 = nn.Conv2d(64, output_nc, 7)\n self.tanh = nn.Tanh()\n\n if block == BasicBlock_orj:\n # residuals\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 128, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 256, layers[3], stride=2)\n\n fpn_sizes = [self.layer1[layers[0] - 1].conv2.out_channels,\n self.layer2[layers[1] - 1].conv2.out_channels,\n self.layer3[layers[2] - 1].conv2.out_channels,\n self.layer4[layers[3] - 1].conv2.out_channels]\n\n elif block == BasicBlock_Ganilla:\n # residuals\n self.layer1 = self._make_layer_ganilla(block, 64, layers[0], use_dropout, stride=1)\n self.layer2 = self._make_layer_ganilla(block, 128, layers[1], use_dropout, stride=2)\n self.layer3 = self._make_layer_ganilla(block, 128, layers[2], use_dropout, stride=2)\n self.layer4 = self._make_layer_ganilla(block, 256, layers[3], use_dropout, stride=2)\n\n fpn_sizes = [self.layer1[layers[0] - 1].conv2.out_channels,\n self.layer2[layers[1] - 1].conv2.out_channels,\n self.layer3[layers[2] - 1].conv2.out_channels,\n self.layer4[layers[3] - 1].conv2.out_channels]\n\n else:\n print(\"Block Type is not Correct\")\n sys.exit()\n\n self.fpn = PyramidFeatures(fpn_sizes[0], fpn_sizes[1], fpn_sizes[2], fpn_sizes[3], fpn_weights)\n\n #for m in self.modules():\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 # elif isinstance(m, nn.BatchNorm2d):\n # m.weight.data.fill_(1)\n # m.bias.data.zero_()\n\n # self.freeze_bn()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=True),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def _make_layer_ganilla(self, block, planes, blocks, use_dropout, stride=1):\n strides = [stride] + [1] * (blocks - 1)\n layers = []\n for stride in strides:\n layers.append(block(self.inplanes, planes, use_dropout, stride))\n self.inplanes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def freeze_bn(self):\n '''Freeze BatchNorm layers.'''\n for layer in self.modules():\n if isinstance(layer, nn.BatchNorm2d):\n layer.eval()\n\n def forward(self, inputs):\n\n img_batch = inputs\n\n x = self.pad1(img_batch)\n x = self.conv1(x)\n x = self.in1(x)\n x = self.relu(x)\n x = self.pad2(x)\n x = self.maxpool(x)\n\n x1 = self.layer1(x)\n x2 = self.layer2(x1)\n x3 = self.layer3(x2)\n x4 = self.layer4(x3)\n\n out = self.fpn([x1, x2, x3, x4]) # use all resnet layers\n\n out = self.pad3(out)\n out = self.conv2(out)\n out = self.tanh(out)\n\n return out\n\n\nclass AblationModel1(nn.Module):\n def __init__(self, block, layers, ngf=64):\n self.inplanes = 64\n self.ngf = ngf\n super(AblationModel1, self).__init__()\n\n # first conv\n self.pad1 = nn.ReflectionPad2d(3)\n self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=1, padding=0, bias=True)\n self.in1 = nn.InstanceNorm2d(64)\n self.relu = nn.ReLU(inplace=True)\n self.pad2 = nn.ReflectionPad2d(1)\n self.maxpool = nn.MaxPool2d(kernel_size=3, stride=2, padding=0)\n\n if block == BasicBlock_orj:\n # residuals\n self.layer1 = self._make_layer(block, 64, layers[0])\n self.layer2 = self._make_layer(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer(block, 128, layers[2], stride=2)\n self.layer4 = self._make_layer(block, 256, layers[3], stride=2)\n\n fpn_sizes = [self.layer1[layers[0] - 1].conv2.out_channels,\n self.layer2[layers[1] - 1].conv2.out_channels,\n self.layer3[layers[2] - 1].conv2.out_channels,\n self.layer4[layers[3] - 1].conv2.out_channels]\n\n elif block == BasicBlock_Ganilla:\n # residuals\n self.layer1 = self._make_layer_ganilla(block, 64, layers[0])\n self.layer2 = self._make_layer_ganilla(block, 128, layers[1], stride=2)\n self.layer3 = self._make_layer_ganilla(block, 128, layers[2], stride=2)\n self.layer4 = self._make_layer_ganilla(block, 256, layers[3], stride=2)\n\n fpn_sizes = [self.layer1[layers[0] - 1].conv2.out_channels,\n self.layer2[layers[1] - 1].conv2.out_channels,\n self.layer3[layers[2] - 1].conv2.out_channels,\n self.layer4[layers[3] - 1].conv2.out_channels]\n\n else:\n print(\"Block Type is not Correct\")\n\n # self.fpn = PyramidFeatures(fpn_sizes[0], fpn_sizes[1], fpn_sizes[2], fpn_sizes[3])\n\n n_downsampling = 4\n\n model = []\n\n model += [nn.ReflectionPad2d(1)]\n model += [nn.Conv2d(256, self.ngf * 2 ** (n_downsampling), kernel_size=3, padding=0)]\n model += [nn.ReLU(inplace=True)]\n\n for i in range(n_downsampling):\n mult = 2 ** (n_downsampling - i)\n model += [nn.ConvTranspose2d(self.ngf * mult, int(self.ngf * mult / 2),\n kernel_size=3, stride=2,\n padding=1, output_padding=1,\n bias=False),\n nn.InstanceNorm2d(int(self.ngf * mult / 2)),\n nn.ReLU(True)]\n model += [nn.ReflectionPad2d(3)]\n model += [nn.Conv2d(self.ngf, 3, kernel_size=7, padding=0)]\n model += [nn.Tanh()]\n\n self.deconv_part = nn.Sequential(*model)\n\n #for m in self.modules():\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 # elif isinstance(m, nn.BatchNorm2d):\n # m.weight.data.fill_(1)\n # m.bias.data.zero_()\n\n # self.freeze_bn()\n\n def _make_layer(self, block, planes, blocks, stride=1):\n downsample = None\n if stride != 1 or self.inplanes != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.inplanes, planes * block.expansion,\n kernel_size=1, stride=stride, bias=True),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.inplanes, planes, stride, downsample))\n self.inplanes = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.inplanes, planes))\n\n return nn.Sequential(*layers)\n\n def _make_layer_ganilla(self, block, planes, blocks, stride=1):\n strides = [stride] + [1] * (blocks - 1)\n layers = []\n for stride in strides:\n layers.append(block(self.inplanes, planes, stride))\n self.inplanes = planes * block.expansion\n return nn.Sequential(*layers)\n\n def freeze_bn(self):\n '''Freeze BatchNorm layers.'''\n for layer in self.modules():\n if isinstance(layer, nn.BatchNorm2d):\n layer.eval()\n\n def forward(self, inputs):\n\n img_batch = inputs\n\n x = self.pad1(img_batch)\n x = self.conv1(x)\n x = self.in1(x)\n x = self.relu(x)\n x = self.pad2(x)\n x = self.maxpool(x)\n\n x1 = self.layer1(x)\n x2 = self.layer2(x1)\n x3 = self.layer3(x2)\n x4 = self.layer4(x3)\n\n out = self.deconv_part(x4)\n\n return out\n\n\nclass AblationModel2(nn.Module):\n def __init__(self, ngf=64, norm_layer=nn.BatchNorm2d, use_dropout=False, n_blocks=9, padding_type='reflect'):\n self.inplanes = 64\n self.ngf = ngf\n super(AblationModel2, self).__init__()\n\n if type(norm_layer) == functools.partial:\n use_bias = norm_layer.func == nn.InstanceNorm2d\n else:\n use_bias = norm_layer == nn.InstanceNorm2d\n\n self.input_nc = 3\n self.output_nc = 3\n\n fpn_sizes = []\n\n init_part = [nn.ReflectionPad2d(3),\n nn.Conv2d(self.input_nc, ngf, kernel_size=7, padding=0,\n bias=use_bias),\n nn.InstanceNorm2d(ngf),\n nn.ReLU(True)]\n\n self.init_part = nn.Sequential(*init_part)\n fpn_sizes.append(ngf)\n\n n_downsampling = 2\n # for i in range(n_downsampling):\n # mult = 2 ** i\n mult = 1\n down1 = [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3,\n stride=2, padding=1, bias=False),\n nn.InstanceNorm2d(ngf * mult * 2),\n nn.ReLU(True)]\n\n self.down1 = nn.Sequential(*down1)\n\n fpn_sizes.append(ngf * mult * 2)\n\n mult = 2\n down2 = [nn.Conv2d(ngf * mult, ngf * mult * 2, kernel_size=3,\n stride=2, padding=1, bias=False),\n nn.InstanceNorm2d(ngf * mult * 2),\n nn.ReLU(True)]\n self.down2 = nn.Sequential(*down2)\n\n # fpn_sizes.append(ngf * mult * 2)\n\n flat_part = []\n mult = 2 ** n_downsampling\n for i in range(n_blocks):\n flat_part += [ResnetBlock(ngf * mult, padding_type=padding_type, norm_layer=norm_layer, use_dropout=use_dropout,\n use_bias=use_bias)]\n self.flat_part = nn.Sequential(*flat_part)\n\n fpn_sizes.append(ngf * mult)\n\n self.fpn = PyramidFeatures_v3(fpn_sizes[0], fpn_sizes[1], fpn_sizes[2])\n\n final_part = [nn.ReflectionPad2d(3)]\n final_part += [nn.Tanh()]\n final_part += [nn.Conv2d(self.ngf, 3, kernel_size=7, padding=0)]\n\n self.final_part = nn.Sequential(*final_part)\n\n def forward(self, inputs):\n\n img_batch = inputs\n\n x = self.init_part(img_batch)\n\n x1 = self.down1(x)\n x2 = self.down2(x1)\n x3 = self.flat_part(x2)\n\n out = self.fpn([x, x1, x3])\n\n out = self.final_part(out)\n\n return out\n\n\ndef resnet18(input_nc, output_nc, ngf, fpn_weights, use_dropout, pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-18 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(input_nc, output_nc, ngf, fpn_weights, BasicBlock_Ganilla, [2, 2, 2, 2], use_dropout, **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet18'], model_dir='.'), strict=False)\n return model\n\n\ndef resnet34(input_nc, output_nc, ngf, fpn_weights, use_dropout=False, pretrained=False, **kwargs):\n \"\"\"Constructs a ResNet-34 model.\n Args:\n pretrained (bool): If True, returns a model pre-trained on ImageNet\n \"\"\"\n model = ResNet(input_nc, output_nc, ngf, fpn_weights, BasicBlock_Ganilla, [3, 4, 6, 3], use_dropout=use_dropout, **kwargs)\n if pretrained:\n model.load_state_dict(model_zoo.load_url(model_urls['resnet34'], model_dir='.'), strict=False)\n return model\n\n\n#### ORJ MODELS ######\nclass ResidualBlock(nn.Module):\n def __init__(self, in_features):\n super(ResidualBlock, self).__init__()\n\n conv_block = [ nn.ReflectionPad2d(1),\n nn.Conv2d(in_features, in_features, 3),\n nn.InstanceNorm2d(in_features),\n nn.ReLU(inplace=True),\n nn.ReflectionPad2d(1),\n nn.Conv2d(in_features, in_features, 3),\n nn.InstanceNorm2d(in_features) ]\n\n self.conv_block = nn.Sequential(*conv_block)\n\n def forward(self, x):\n return x + self.conv_block(x)\n\nclass Generator(nn.Module):\n def __init__(self, input_nc, output_nc, n_residual_blocks=9):\n super(Generator, self).__init__()\n\n # Initial convolution block\n model = [ nn.ReflectionPad2d(3),\n nn.Conv2d(input_nc, 64, 7),\n nn.InstanceNorm2d(64),\n nn.ReLU(inplace=True) ]\n\n # Downsampling\n in_features = 64\n out_features = in_features*2\n for _ in range(2):\n model += [ nn.Conv2d(in_features, out_features, 3, stride=2, padding=1),\n nn.InstanceNorm2d(out_features),\n nn.ReLU(inplace=True) ]\n in_features = out_features\n out_features = in_features*2\n\n # Residual blocks\n for _ in range(n_residual_blocks):\n model += [ResidualBlock(in_features)]\n\n # Upsampling\n out_features = in_features//2\n for _ in range(2):\n model += [ nn.ConvTranspose2d(in_features, out_features, 3, stride=2, padding=1, output_padding=1),\n nn.InstanceNorm2d(out_features),\n nn.ReLU(inplace=True) ]\n in_features = out_features\n out_features = in_features//2\n\n # Output layer\n model += [ nn.ReflectionPad2d(3),\n nn.Conv2d(64, output_nc, 7),\n nn.Tanh() ]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n return self.model(x)\n\nclass Discriminator(nn.Module):\n def __init__(self, input_nc):\n super(Discriminator, self).__init__()\n\n # A bunch of convolutions one after another\n model = [ nn.Conv2d(input_nc, 64, 4, stride=2, padding=1),\n nn.LeakyReLU(0.2, inplace=True) ]\n\n model += [ nn.Conv2d(64, 128, 4, stride=2, padding=1),\n nn.InstanceNorm2d(128),\n nn.LeakyReLU(0.2, inplace=True) ]\n\n model += [ nn.Conv2d(128, 256, 4, stride=2, padding=1),\n nn.InstanceNorm2d(256),\n nn.LeakyReLU(0.2, inplace=True) ]\n\n model += [ nn.Conv2d(256, 512, 4, padding=1),\n nn.InstanceNorm2d(512),\n nn.LeakyReLU(0.2, inplace=True) ]\n\n # FCN classification layer\n model += [nn.Conv2d(512, 1, 4, padding=1)]\n\n self.model = nn.Sequential(*model)\n\n def forward(self, x):\n x = self.model(x)\n # Average pooling and flatten\n return F.avg_pool2d(x, x.size()[2:]).view(x.size()[0], -1)\n","repo_name":"giddyyupp/ganilla","sub_path":"models/networks.py","file_name":"networks.py","file_ext":"py","file_size_in_byte":41129,"program_lang":"python","lang":"en","doc_type":"code","stars":478,"dataset":"github-code","pt":"52"} +{"seq_id":"43326569590","text":"def part1():\n data = open(\"data.in\", \"r\")\n\n data_in = []\n increased = 0\n\n for line in data:\n data_in.append(int(line))\n\n for i in range(len(data_in) - 1):\n if data_in[i] < data_in[i+1]:\n increased += 1\n \n return increased\n\ndef part2():\n data = open(\"data.in\", \"r\")\n\n data_in = []\n windows = []\n increased = 0\n\n for line in data:\n data_in.append(int(line))\n \n for i in range(len(data_in)-3 + 1):\n windows.append(sum(data_in[i:i+3]))\n\n for i in range(len(windows)-1):\n if windows[i] < windows[i+1]:\n increased += 1\n\n return increased\n\nif __name__ == \"__main__\":\n print(part1())\n print(part2())","repo_name":"theleteron/advent-of-code","sub_path":"2021/Day 1/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"31982118668","text":"import wikipedia\nimport sys\nimport re\n\nfrom document import WikipediaDocument\n\nquery = \"Ukrainian War\"\n\nwikipages = wikipedia.search(query)\nif len(wikipages) == 0:\n print('No relevant wikipedia articles found')\n sys.exit(0)\n\nprint(f'Pages found:', \", \".join(wikipages))\nprint(f'Getting the contents of \"{wikipages[0]}\"')\n\npage = None\n\nfor result in wikipages:\n try:\n page = wikipedia.page(result).content\n break\n except wikipedia.DisambiguationError as de:\n # Handle disambiguation pages by attempting to get the first option\n try:\n page = wikipedia.page(de.options[0]).content\n break\n except:\n continue\n except wikipedia.exceptions.PageError:\n # If the page doesn't exist, move to the next result\n continue\n\n#print(page)\ndocument = WikipediaDocument(page)\n\nprint(document.first_chunk())\n#section_list = \"\\n\".join(list(map(lambda section: f' - {section}', sections)))\n\n","repo_name":"zby/answerbot","sub_path":"archive/wikipedia_by_api.py","file_name":"wikipedia_by_api.py","file_ext":"py","file_size_in_byte":966,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"34825440777","text":"import os\r\n\r\nimport random\r\nfrom flask import Blueprint, request, jsonify, session, abort\r\n\r\nfrom myapp.ext import cache, db\r\nfrom myapp.models import User, Blog, Collection\r\nfrom myapp.settings import BASE_DIR\r\nfrom myapp.status_code import *\r\n\r\nfrom myapp.utils import enc_pwd, send_mail, create_rand_str\r\n\r\nblue = Blueprint(\"haha\", __name__)\r\n\r\ndef init_blue(app):\r\n #注册蓝图\r\n app.register_blueprint(blue)\r\n\r\n\"\"\"\r\n用户Api\r\n- 用户手机号注册\r\n- 用户登录(删除用户不可得登录)\r\n- 验证码和密码登录(密码实现数据安全)\r\n- 用户信息修改\r\n- 用户逻辑删除\r\n\r\n\"\"\"\r\n@blue.route(\"/register/\", methods=[\"GET\", \"POST\"])\r\ndef register_api():\r\n if request.method == \"GET\":\r\n #此处可以重定向到登录页面\r\n return \"注册成功\"\r\n else:\r\n #解析参数\r\n params = request.form\r\n u_phone = params.get(\"u_phone\")\r\n u_name = params.get(\"u_name\")\r\n u_password = params.get(\"u_password\")\r\n email = params.get(\"email\")\r\n u_icon = request.form.get(\"u_icon\", None)\r\n #校验参数\r\n if u_name and u_password and u_phone and len(u_name) > 3 and len(str(u_phone)) == 11:\r\n #校验手机号\r\n enc_phone = User.query.filter(User.u_phone == u_phone).all()\r\n #若为True 则手机号注册过\r\n if len(enc_phone) == 0:\r\n # 给密码加密\r\n enc_pwd_str = enc_pwd(u_password)\r\n #实例化\r\n u = User()\r\n u.u_name = u_name\r\n u.u_password = enc_pwd_str\r\n #校验用户头像,若为None,则没上传\r\n if u_icon == None:\r\n return \"没上传头像,请上传头像\"\r\n else:\r\n #生成唯一头像名字\r\n file_name = create_rand_str() + \".jpg\"\r\n #拼接文保存路径\r\n file_path = os.path.join(BASE_DIR, 'static/icon' + file_name)\r\n #保存文件\r\n file = open(file_path, \"wb\")\r\n for i in u_icon.chunks():\r\n u.u_icon = file_path\r\n #保存文件路径\r\n #将用户对象保存到数据库\r\n db.session.add(u)\r\n db.session.commit()\r\n\r\n res = send_mail(email, request.host)\r\n # 设置缓存\r\n cache.set(res, u.id, 60 * 60)\r\n data = {\r\n \"code\": SUCCESS,\r\n \"msg\": '注册成功',\r\n \"data\": []\r\n }\r\n return jsonify(data)\r\n else:\r\n #手机号已被注册\r\n return jsonify({\"code\": FAIL, \"msg\": \"手机号已被注册,请换个手机号重新注册\", \"data\":[]})\r\n else:\r\n #参数不合适\r\n return jsonify({\"code\":NOT_LOGIN, \"msg\":\"参数不对,请核对\", \"data\":[]})\r\n\r\n# - 用户登录(删除用户不可得登录)\r\n@blue.route(\"/login/\", methods=[\"GET\", \"POST\"])\r\ndef login_api():\r\n if request.method == \"GET\":\r\n data = {\r\n \"code\": SUCCESS\r\n }\r\n return jsonify(data)\r\n elif request.method == \"POST\":\r\n #解析参数\r\n params = request.form\r\n u_phone = params.get(\"u_phone\")\r\n u_password = params.get(\"u_password\")\r\n # print(u_name)\r\n # print(u_password)\r\n #校验数据\r\n #去数据库拿到用户名\r\n u = User.query.filter(User.u_phone == u_phone).all()\r\n if len(u) == 0 or u[0].is_delete == True:\r\n data = {\r\n \"code\":NOT_LOGIN,\r\n \"msg\":\"用户名不存在\",\r\n \"data\":[]\r\n }\r\n return jsonify(data)\r\n else:\r\n #校验用户密码\r\n if u[0].u_password == enc_pwd(u_password):\r\n #写入session\r\n session[u_phone] = u_phone\r\n data = {\r\n \"code\":SUCCESS,\r\n \"msg\":\"登录成功\",\r\n \"data\":{\r\n \"user\":u[0].u_phone,\r\n \"u_icon_url\":u[0].u_icon\r\n }\r\n }\r\n return jsonify(data)\r\n else:\r\n data = {\r\n \"code\":NOT_LOGIN,\r\n \"msg\":\"登录失败\",\r\n \"data\":[]\r\n }\r\n return jsonify(data)\r\n\r\n\r\n#- 密码登录(密码实现数据安全)\r\n@blue.route(\"/enc_pwd_login\", methods=[\"POST\"])\r\ndef enc_pwd_login():\r\n #解析参数\r\n u_phone = request.form.get(\"u_phone\")\r\n #校验参数\r\n if u_phone:\r\n u = User.query.filter(User.u_phone == u_phone).all()\r\n if len(u) == 0:\r\n #用户不存在\r\n data = {\r\n \"code\":PERMISSION_DENY,\r\n \"msg\":\"用户名不存在\",\r\n \"data\":[]\r\n }\r\n return jsonify(data)\r\n else:\r\n #随机生成一个六位数\r\n random_num = random.randrange(100000, 1000000)\r\n #发短信,此处不会写,跳过\r\n #设置缓存, 60*60秒过期\r\n cache.set(u_phone, random_num,60*60)\r\n data = {\r\n \"code\":SUCCESS,\r\n \"msg\":\"用户登录验证码,请查收\",\r\n \"data\":u_phone\r\n }\r\n return jsonify(data)\r\n else:\r\n #参数错误\r\n data = {\r\n \"code\":NOT_LOGIN,\r\n \"msg\":\"参数有误,无法操作\",\r\n \"data\":[]\r\n }\r\n return jsonify(data)\r\n\r\n#- 用户信息修改\r\n@blue.route(\"/user_info_modify/\", methods=[\"GET\", \"POST\"])\r\ndef user_info_modify():\r\n if request.method == \"GET\":\r\n data = {\r\n \"code\":FAIL,\r\n \"msg\":\"lele\",\r\n \"data\":[]\r\n }\r\n return jsonify(data)\r\n else:\r\n #解析参数\r\n params = request.form\r\n u_name = params.get(\"u_name\")\r\n u_password = params.get(\"u_password\")\r\n u_phone = params.get(\"u_phone\")\r\n #加密密码\r\n enc_pwd_two = enc_pwd(u_password)\r\n #去数据库那对象\r\n user = User.query.filter(User.u_name == u_name).first()\r\n user.u_password = enc_pwd_two\r\n user.u_phone = u_phone\r\n # 把数据保存到数据库\r\n db.session.add(user)\r\n db.session.commit()\r\n data = {\r\n \"code\": SUCCESS,\r\n \"msg\": \"ok\",\r\n \"data\": {}\r\n }\r\n return jsonify(data)\r\n\r\n\r\n#用户逻辑删除\r\n@blue.route(\"/user_delete/\", methods=[\"GET\", \"POST\"])\r\ndef user_delete():\r\n if request.method == \"GET\":\r\n data = {\r\n \"code\": FAIL,\r\n \"msg\": \"lele\",\r\n \"data\": []\r\n }\r\n return jsonify(data)\r\n else:\r\n #解析参数\r\n param = request.form\r\n u_name = param.get(\"u_name\")\r\n if User.query.filter(User.name == u_name).first():\r\n # 从数据里获取用户对象\r\n user = User.query.filter(User.u_name == u_name).first()\r\n if user.is_delete == 0:\r\n # 修改用户状态\r\n user.is_delete = 1\r\n # 保存到数据库\r\n db.session.add(user)\r\n db.session.commit()\r\n data = {\r\n \"code\": SUCCESS,\r\n \"msg\": \"ok\",\r\n \"data\": {}\r\n }\r\n return jsonify(data)\r\n else:\r\n data = {\r\n \"code\": FAIL,\r\n \"msg\": \"用户已经是删除状态\",\r\n \"data\": {}\r\n }\r\n return jsonify(data)\r\n else:\r\n data = {\r\n \"code\": FAIL,\r\n \"msg\": \"用户不存在\",\r\n \"data\": {}\r\n }\r\n return jsonify(data)\r\n\r\n\r\n\"\"\"- 博客Api\r\n - 博客创建\r\n - 博客修改\r\n - 博客删除\r\n- 用户,博客结合操作\r\n - 收藏博客\r\n - 获取某用户的所有收藏\r\n - 获取收藏某博客的所有用户\r\n\"\"\"\r\n\r\n\r\n#博客创建\r\n@blue.route(\"/create_blog/\")\r\ndef create_blog():\r\n b = Blog()\r\n b.b_title = \"flask很难受\"\r\n b.b_content = \"django更难受\"\r\n\r\n #添加博客到数据库\r\n db.session.add(b)\r\n #提交\r\n db.session.commit()\r\n return b.b_title, b.b_content\r\n\r\n#博客修改\r\n@blue.route(\"/modify/\")\r\ndef modify():\r\n res = Blog.query.filter_by(id=1)\r\n res.b_title = \"lala\"\r\n res.b_content = \"hehe\"\r\n return \"ok\"\r\n\r\n#博客删除\r\n@blue.route(\"/delete/\")\r\ndef blog_delete_one():\r\n #先做查询,在做删除\r\n blog = Blog.query.filter_by(id=1).first()\r\n db.session.delete(blog)\r\n #提交操作\r\n db.session.commit()\r\n return \"fire吼\"\r\n\r\n#收藏博客\r\n@blue.route(\"/collect_one//\")\r\ndef collect_one(uid, bid):\r\n data = Collection(\r\n user = uid,\r\n blog = bid\r\n )\r\n db.session.add(data)\r\n db.session.commit()\r\n return \"收藏成功\"\r\n\r\n# 获取某用户 的所有收藏\r\n@blue.route(\"/get_user_all_collect/\")\r\ndef get_user_all_collect(cid):\r\n collection = Collection.query.get(cid)\r\n cols = collection.cols\r\n return \"前端你给我把数据赶快送过来\"\r\n\r\n#获取收藏某博客 的所有用户\r\n@blue.route(\"/get_collect_all_user/\")\r\ndef get_collect_all_user(uid):\r\n res = Collection.query.filter(Collection.my_user == uid)\r\n print(res[0])\r\n return \"buxiaodeduibudui\"\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"fengkuangdadie/gitTestDemo","sub_path":"FlaskTestCode/myapp/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19377739003","text":"import random\r\nimport tensorflow as tf\r\nclass DataAccessor:\r\n def __init__(self, fname, numberOfSets=4096, hitsPercentage=1.3, nonceTarget=1048575, nonceSizeBits=32, fieldSizeBits=20):\r\n self.fname = fname\r\n self.numberOfSets = numberOfSets\r\n self.hitsPercentage = hitsPercentage\r\n self.nonceTarget = nonceTarget\r\n self.nonceSizeBits = nonceSizeBits\r\n self.fieldSizeBits = fieldSizeBits\r\n \r\n def __decompressTargetSet(self, targets):\r\n ret = [[0]]*self.numberOfSets\r\n for target in targets:\r\n ret[target] = [1]\r\n return ret\r\n \r\n def __decompressInp(self, inp):\r\n return [int(inp[i:i+8],16) for i in range(0, len(inp), 8)]\r\n \r\n \r\n def __genData(self, ignoreHitsPercentage=False, ignoreNonceTarget=False, ignoreNonceSizeBits=False, ignoreFieldSizeBits=False):\r\n file = open(self.fname)\r\n for line in file.readlines():\r\n try:\r\n elems = eval(line)\r\n if elems[3] == self.numberOfSets \\\r\n and (True if ignoreHitsPercentage else elems[4] == self.hitsPercentage) \\\r\n and (True if ignoreNonceTarget else elems[5] == self.nonceTarget) \\\r\n and (True if ignoreNonceSizeBits else elems[6] == self.nonceSizeBits) \\\r\n and (True if ignoreFieldSizeBits else elems[7] == self.fieldSizeBits) \\\r\n and len(elems[0]) == 128 \\\r\n and len(elems[1]) == 24 \\\r\n and isinstance(elems[2], list):\r\n elems[0] = self.__decompressInp(elems[0]+elems[1])\r\n elems[2] = self.__decompressTargetSet(elems[2])\r\n yield elems\r\n except GeneratorExit:\r\n raise GeneratorExit\r\n except:\r\n pass\r\n \r\n \r\n \r\n def genTrainingData(self, ignoreHitsPercentage=False, ignoreNonceTarget=False, ignoreNonceSizeBits=False, ignoreFieldSizeBits=False):\r\n data = list(self.__genData(ignoreHitsPercentage,ignoreNonceTarget,ignoreNonceSizeBits,ignoreFieldSizeBits))\r\n while True:\r\n temp = random.choice(data)\r\n yield (tf.constant([temp[0]],dtype=\"uint32\"),tf.constant([temp[2]],dtype=\"uint32\"))\r\n \r\n ","repo_name":"sLucas27/AnalysisWithAI","sub_path":"pythonfiles/DataManagement.py","file_name":"DataManagement.py","file_ext":"py","file_size_in_byte":2296,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"41901641709","text":"from __future__ import division, print_function\n\nimport os\nimport argparse\n\nimport pandas\nfrom scipy.stats import poisson\nfrom numpy import median\n\nimport matplotlib\nmatplotlib.use(\"Agg\")\n\nimport seaborn\n\nfrom ddd_4k.constants import ALPHA, NUM_GENES\nfrom mupit.mutation_rates import get_default_rates\n\n# define the plot style\nseaborn.set_context(\"notebook\", font_scale=2)\nseaborn.set_style(\"white\", {\"ytick.major.size\": 10, \"xtick.major.size\": 10})\n\ndef get_options():\n \"\"\"\n \"\"\"\n \n parser = argparse.ArgumentParser(description=\".\")\n parser.add_argument(\"--output-haploinsufficiency\", \\\n default=\"haploinsufficiency_power.pdf\", \\\n help=\"Path to plot graph to.\")\n parser.add_argument(\"--output-exome\", \\\n default=\"exome_vs_genome.simulated.pdf\", \\\n help=\"Path to plot graph to.\")\n \n args = parser.parse_args()\n \n return args\n\ndef get_gene_probabilities(lof_rates, expected, threshold, cohort_n, population_n, disorder_freq):\n \"\"\" estimate probabilities of a significant result, at a cohort size\n \n Args:\n lof_rates: mutation rates per gene\n expected: list of number of mutations expected per gene in the UK +\n Ireland population.\n threshold: a significance threshold, genomewide corrected.\n cohort_n: size of the cohort being checked\n population_n: size of the population of the UK and Ireland.\n disorder_freq: expected frequency of developmental disorders\n \n Returns:\n pandas Series of probabilities for each gene\n \"\"\"\n \n # estimate the expected number of mutations under the null mutation model,\n # given the cohort size.\n cohort_null = [ x * cohort_n for x in lof_rates ]\n \n # estimate individuals in UK + Ireland with developmental disorders\n disorder_n = population_n * disorder_freq\n \n # estimate the number of lof mutation per gene required to cross the\n # significance threshold, given the expected mutations in the cohort size\n mutations = [ x - 1 for x in poisson.isf(threshold, cohort_null) ]\n \n # determine the number of mutations expected for the cohort size, given the\n # proportion that the cohort size is to the number of individuals with\n # developmental disorders\n cohort_expected = [ x * cohort_n/disorder_n for x in expected ]\n \n return poisson.sf(mutations, cohort_expected)\n\ndef check_haploinsufficiency_power(rates, threshold, population_n, disorder_freq, plot_path):\n \"\"\" check power to detect lof enrichment of develop in UK\n \n Args:\n rates: dataframe of null mutation rates per gene, for different\n functional types.\n threshold: a significance threshold, genomewide corrected.\n population_n: size of the population of the UK and Ireland.\n disorder_freq: expected frequency of developmental disorders\n plot_path: path to send ouput plot to\n \"\"\"\n \n # estimate the number of mutations expected per gene in the UK + Ireland population\n expected = [ x * population_n for x in rates[\"lof\"] ]\n \n cohorts = range(1000, 13000, 1000)\n \n combined = pandas.DataFrame(columns=[\"hgnc\", \"cohort_n\", \"probability\"])\n for cohort_n in cohorts:\n probabilities = get_gene_probabilities(rates[\"lof\"], expected,\n threshold, cohort_n, population_n, disorder_freq)\n temp = pandas.DataFrame({\"hgnc\": list(rates[\"hgnc\"]),\n \"cohort_n\": [cohort_n] * len(probabilities),\n \"probability\": list(probabilities)})\n \n combined = combined.append(temp, ignore_index=True)\n \n probabilities = get_gene_probabilities(rates[\"lof\"], expected,\n threshold, 4295, population_n, disorder_freq)\n print(median(probabilities))\n \n combined[\"probability\"] = combined[\"probability\"].astype(float)\n fig = seaborn.factorplot(x=\"cohort_n\", y=\"probability\", data=combined, \\\n kind=\"box\", size=6, aspect=1.8, fliersize=0, color=\"gray\")\n fig.savefig(plot_path, format=\"pdf\", bbox_inches='tight', pad_inches=0,\n transparent=True)\n\ndef exome_vs_genome(rates, threshold, population_n, disorder_freq, plot_path):\n \"\"\" compare power of exome and genome sequencing\n \n Args:\n rates: dataframe of null mutation rates per gene, for different\n functional types.\n threshold: a significance threshold, genomewide corrected.\n population_n: size of the population of the UK and Ireland.\n disorder_freq: expected frequency of developmental disorders\n plot_path: path to send ouput plot to\n \"\"\"\n \n # estimate the number of mutations expected per gene in the UK + Ireland\n # population\n expected = [ x * population_n for x in rates[\"lof\"] ]\n \n # define a range of amounts of money for sequencing\n budgets = [1e6, 2e6, 3e6]\n genome_cost = 1000 * 3\n exome_relative_cost = [ (x+1)/10.0 for x in range(10) ]\n genome_sensitivity = [ (x/20.0)+1 for x in range(5) ]\n \n power = pandas.DataFrame(columns=[\"budget\", \"exome_cost\", \"sensitivity\", \"sequence\", \"power\"])\n for budget in budgets:\n sensitivity = 1\n for relative_cost in exome_relative_cost:\n n_exomes = budget/(genome_cost * relative_cost)\n exome_probs = get_gene_probabilities(rates[\"lof\"], expected, \\\n threshold, n_exomes, population_n, disorder_freq)\n exome_median = median(exome_probs)\n power = power.append({\"budget\": budget,\n \"exome_cost\": relative_cost, \"sensitivity\": sensitivity,\n \"sequence\": \"exome\", \"power\": exome_median}, ignore_index=True)\n \n for sensitivity in genome_sensitivity:\n n_genomes = (budget/genome_cost) * sensitivity\n genome_probs = get_gene_probabilities(rates[\"lof\"], expected, \\\n threshold, n_genomes, population_n, disorder_freq)\n \n genome_median = median(genome_probs)\n power = power.append({\"budget\": budget,\n \"exome_cost\": relative_cost, \"sensitivity\": sensitivity,\n \"sequence\": \"genome-{}\".format(sensitivity),\n \"power\": genome_median}, ignore_index=True)\n \n fig = seaborn.factorplot(x=\"exome_cost\", y=\"power\", hue=\"sequence\", \\\n col=\"budget\", data=power, size=8, aspect=0.4)\n fig.savefig(plot_path, format=\"pdf\", bbox_inches='tight', pad_inches=0,\n transparent=True)\n\ndef main():\n \n args = get_options()\n \n # the DDD is sampling from the population of the UK and Ireland, which is about\n # 50 million people\n population_n = 50e6\n \n # the prevalence of developmental disorders is 0.5% of the general population\n disorder_freq = 0.005\n \n rates = get_default_rates()\n # determine the summed loss-of-function mutation rate for each gene\n rates[\"lof\"] = rates[[\"non\", \"splice_site\", \"frameshift\" ]].sum(axis=1)\n \n # estimate a genome-wide significance threshold\n threshold = ALPHA/NUM_GENES\n \n check_haploinsufficiency_power(rates, threshold, population_n, disorder_freq, \\\n args.output_haploinsufficiency)\n exome_vs_genome(rates, threshold, population_n, disorder_freq, \\\n args.output_exome)\n\nif __name__ == '__main__':\n main()\n","repo_name":"jeremymcrae/ddd_4k","sub_path":"scripts/exome_vs_genome_simulations.py","file_name":"exome_vs_genome_simulations.py","file_ext":"py","file_size_in_byte":7262,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"29939687835","text":"import os\nfrom datetime import datetime\nfrom operator import itemgetter\n\nfrom powerhub.directories import directories\nfrom powerhub.tools import decrypt_aes\n\n\ndef save_file(file, dir=directories.UPLOAD_DIR, key=None):\n \"\"\"Save a file to the upload directory and return the filename\n\n If it already exists, append a counter.\n \"\"\"\n filename = os.path.join(dir, os.path.basename(file.filename))\n if os.path.exists(filename):\n count = 1\n while os.path.isfile(\"%s.%d\" % (filename, count)):\n count += 1\n filename += \".%d\" % count\n if key:\n data = file.read()\n data = decrypt_aes(data, key)\n with open(filename, 'bw') as f:\n f.write(data)\n else:\n file.save(filename)\n return filename\n\n\ndef get_filelist():\n \"\"\"Return a list of files in the upload directory\"\"\"\n onlyfiles = [f for f in os.listdir(directories.UPLOAD_DIR)\n if os.path.isfile(os.path.join(directories.UPLOAD_DIR, f))]\n result = [{\n \"name\": f,\n \"size\": os.path.getsize(os.path.join(directories.UPLOAD_DIR, f)),\n \"date\": datetime.fromtimestamp(os.path.getmtime(\n os.path.join(directories.UPLOAD_DIR, f)\n )).strftime('%Y-%m-%d %H:%M:%S'),\n } for f in onlyfiles]\n result = sorted(result, key=itemgetter('name'))\n return result\n","repo_name":"AdrianVollmer/PowerHub","sub_path":"powerhub/upload.py","file_name":"upload.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":680,"dataset":"github-code","pt":"52"} +{"seq_id":"35753555338","text":"\n# Linting script for cpp files\n# run locally\n\nimport os\nimport subprocess\nimport sys\n\nprint(\"Python {}.{}.{}\".format(*sys.version_info)) # Python 3.8\n\n\nfiles = []\nfor dirname, _, filenames in os.walk('../Target-450'):\n if \".git\" not in dirname and \".vscode\" not in dirname:\n for filename in filenames:\n fileName = os.path.join(dirname, filename).split('\\\\')[-1] # Get the file name\n files.append(fileName)\n\n\ncpp_exts = tuple(\".c .c++ .cc .cpp .cu .cuh .cxx .h .h++ .hh .hpp .hxx\".split())\ncpp_files = [file for file in files if file.lower().endswith(cpp_exts)]\n\nif not cpp_files:\n sys.exit(0)\n\nsubprocess.run([\"clang-tidy-10\", \"--fix\", \"-p=build\", \"--extra-arg=-std=c++17\", *cpp_files, \"--\"], \n check=True, text=True, stderr=subprocess.STDOUT)\n\nsubprocess.run([\"clang-format-10\", \"-i\", \"-style=file\", *cpp_files], \n check=True, text=True, stderr=subprocess.STDOUT)\n\nspace_files = [file for file in cpp_files if \" \" in file or \"-\" in file]\nif space_files:\n print(f\"{len(space_files)} files contain space or dash characters:\")\n print(\"\\n\".join(space_files) + \"\\n\")\n\nnodir_files = [file for file in cpp_files if file.count(os.sep) != 1]\nif nodir_files:\n print(f\"{len(nodir_files)} files are not in one and only one directory:\")\n print(\"\\n\".join(nodir_files) + \"\\n\")\n\nbad_files = len( space_files + nodir_files)\nif bad_files:\n sys.exit(bad_files)","repo_name":"Gopal-Dahale/scripts","sub_path":"clang.py","file_name":"clang.py","file_ext":"py","file_size_in_byte":1370,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"2799172244","text":"# from spyre import server\nimport server\n\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.dates import DateFormatter\nimport urllib2\nimport json\nfrom datetime import datetime\n\nclass MyLaunch(server.Launch):\n\ttemplateVars = {\"title\" : \"Historical Stock Prices\",\n\t\t\t\t\t\"inputs\" : [\n\t\t\t\t\t\t{\t\"input_type\":'dropdown',\n\t\t\t\t\t\t\t\"label\": 'Company', \n\t\t\t\t\t\t\t\"options\" : [\n\t\t\t\t\t\t\t\t{\"label\": \"Google\", \"value\":\"GOOG\"},\n\t\t\t\t\t\t\t\t{\"label\": \"Yahoo\", \"value\":\"YHOO\"},\n\t\t\t\t\t\t\t\t{\"label\": \"Apple\", \"value\":\"AAPL\"}\n\t\t\t\t\t\t\t],\n\t\t\t\t\t\t\t\"variable_name\": 'ticker', \n\t\t\t\t\t\t}\n\t\t\t\t\t\t],\n\t\t\t\t\t\"controls\" : [\n\t\t\t\t\t\t{\t\"control_type\" : \"button\",\n\t\t\t\t\t\t\t\"control_name\" : \"button1\",\n\t\t\t\t\t\t\t\"button_label\" : \"get historical stock prices\",\n\t\t\t\t\t\t\t\"control_id\" : \"submit_plot\",\n\t\t\t\t\t\t\t\"text_fields\" : []\n\t\t\t\t\t\t}\n\t\t\t\t\t],\n\t\t\t\t\t\"tabs\" : [\"Plot\", \"Table\"],\n\t\t\t\t\t\"outputs\" : [\n\t\t\t\t\t\t{\t\"output_type\" : \"image\",\n\t\t\t\t\t\t\t\"output_id\" : \"plot\",\n\t\t\t\t\t\t\t\"control_name\" : \"button1\",\n\t\t\t\t\t\t\t\"tab\" : \"Plot\",\n\t\t\t\t\t\t\t\"on_page_load\" : \"true\",\n\t\t\t\t\t\t},\n\t\t\t\t\t\t{\t\"output_type\" : \"table\",\n\t\t\t\t\t\t\t\"output_id\" : \"table_id\",\n\t\t\t\t\t\t\t\"control_name\" : \"button1\",\n\t\t\t\t\t\t\t\"tab\" : \"Table\",\n\t\t\t\t\t\t\t\"on_page_load\" : \"true\",\n\t\t\t\t\t\t}\n\t\t\t\t\t]\n\t\t\t\t}\n\n\t# cache values within the Launch object to avoid reloading the data each time\n\tdata_params = None\n\tdata = pd.DataFrame()\n\n\tdef getData(self, params):\n\t\tif params != self.data_params:\n\t\t\tticker = params['ticker']\n\t\t\t# make call to yahoo finance api to get historical stock data\n\t\t\tapi_url = 'https://chartapi.finance.yahoo.com/instrument/1.0/{}/chartdata;type=quote;range=3m/json'.format(ticker)\n\t\t\tresult = urllib2.urlopen(api_url)\n\t\t\tr = result.read()\n\t\t\tdata = json.loads(r.replace('finance_charts_json_callback( ','')[:-1]) # strip away the javascript and load json\n\t\t\t# make call to yahoo finance api to get historical stock data\n\t\t\tself.company_name = data['meta']['Company-Name']\n\t\t\tdf = pd.DataFrame.from_records(data['series'])\n\t\t\tdf['Date'] = pd.to_datetime(df['Date'],format='%Y%m%d')\n\t\t\tself.data = df\n\t\t\tself.data_params = ticker\n\t\treturn self.data\n\n\tdef getPlot(self, params):\n\t\tdf = self.getData(params) # get data\n\t\tdates = pd.DatetimeIndex(df['Date'])\n\t\tfig = plt.figure()\n\t\tsplt = fig.add_subplot(1,1,1)\n\t\tsplt.plot_date(dates, df['close'], fmt='-', label=\"close\")\n\t\tsplt.plot_date(dates, df['high'], fmt='-', label=\"high\")\n\t\tsplt.plot_date(dates, df['low'], fmt='-', label=\"low\")\n\t\tsplt.set_ylabel('Price')\n\t\tsplt.set_xlabel('Date')\n\t\tsplt.set_title(self.company_name)\n\t\tsplt.legend(loc=2)\n\t\tsplt.xaxis.set_major_formatter( DateFormatter('%m-%d-%Y') )\n\t\tfig.autofmt_xdate()\n\t\treturn fig\n\nml = MyLaunch()\nml.launch(port=9093)\n","repo_name":"rybo449/spyre","sub_path":"build/lib/spyre/example_stocks.py","file_name":"example_stocks.py","file_ext":"py","file_size_in_byte":2636,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"27604869967","text":"class RingQueue:\n def __init__(self, max_size):\n self._data = [None] * max_size\n self._begin = 0\n self._size = 0\n\n def push(self, elm):\n if self._size == len(self._data): raise Exception('Queue is full')\n pos = (self._begin + self._size) % len(self._data)\n self._data[pos] = elm\n self._size += 1\n\n def pop(self):\n if self._size == 0: return None\n res = self._data[self._begin]\n self._begin = (self._begin + 1) % len(self._data)\n self._size -= 1\n return res\n\n def is_empty(self):\n return self._size == 0\n\nqueue = RingQueue(5)\nfor i in range(5):\n queue.push(i)\n\nwhile not queue.is_empty():\n print(queue.pop())\n","repo_name":"slashvar/algolia-back-to-school","sub_path":"DataStructures/lists/ring_buffer.py","file_name":"ring_buffer.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"73989234404","text":"# -*-coding-*-: utf-8\n# autor: honggao.zhang\n# update: 2019-07-09\n# function: 癌症检测训练并测试程序\n# problem: 二分类问题\n\n# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load in\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the \"../input/\" directory.\n# For example, running this (by clicking run or pressing Shift+Enter) will list the files in the input directory\n\nimport os\nfrom os.path import isfile\nfrom tqdm import tqdm\nimport time\nimport re\nimport sys\nfrom glob import glob\nfrom random import shuffle\nimport cv2\nimport matplotlib.pyplot as plt\nfrom sklearn.model_selection import train_test_split\n\nimport keras\nfrom keras import backend as K\nfrom keras.utils import Sequence\nfrom keras.applications.inception_resnet_v2 import InceptionResNetV2, preprocess_inputt152V2\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau, TensorBoard\nfrom imgaug import augmenters as iaa\nimport imgaug as ia\nfrom skimage import io\nfrom skimage.transform import resize\nimport matplotlib.pyplot as plt\n\nsys.path.append('./')\nfrom model import *\n# from sklearn.utils import class_weight, shuffle\n# from iterstrat.ml_stratifiers import MultilabelStratifiedKFold\n# from iterstrat.ml_stratifiers import MultilabelStratifiedShuffleSplit\n\nbase_name = 'ResNet101_Epoch40'\n\ninput_shape = (96, 96, 3)\nlearning_late_base = 1e-03\nbatch_size_base = 16\nepochs_base = 2\nnum_classes = 1\n\nprint(os.listdir(\"./\"))\nsrc_dir = os.getcwd()\nsrc_dir = src_dir.replace('\\\\', '/')\nprint(os.listdir(src_dir))\nsrc_dir = './'\n\nSUBMIT = os.path.join(src_dir, 'submit')\nTTA_OUTPUT = os.path.join(src_dir, 'submit/tta_submissions')\nDATASET = os.path.join(src_dir, 'dataset')\nTRAIN = os.path.join(src_dir, 'dataset/train')\nTEST = os.path.join(src_dir, 'dataset/test')\nLOG = os.path.join(src_dir, 'logs')\nMODEL = os.path.join(src_dir, 'logs/models')\nmodel_path = os.path.join(MODEL, '%s.h5' % base_name)\nlabel_path = os.path.join(DATASET, 'train_labels.csv')\n\ndf_train = pd.read_csv(os.path.join(DATASET, \"train_labels.csv\"))\nid_label_map = {k: v for k, v in zip(df_train.id.values, df_train.label.values)}\nprint(df_train.head())\n\n# 返回符合TRAIN目录下*.tif特征的所有文件路径\n# labeled_files = glob(os.path.join(TRAIN, '*.tif'))\nlabeled_files = [os.path.join(TRAIN, x + '.tif') for x in df_train['id']]\nlabeled_id = df_train['id']\n\n# 返回符合TEST目录下*.tif特征的所有文件路径\n# test_files = glob(os.path.join(TEST, '*.tif'))\n\ntest_id = pd.read_csv(os.path.join(DATASET, 'sample_submission.csv'))['id']\ntest_files = []\nfor id in test_id:\n id = id + '.tif'\n image_path = os.path.join(TEST, id)\n test_files.append(image_path)\n\nprint(\"labeled_files size :\", len(labeled_files))\nprint(\"test_files size :\", len(test_files))\n\n\ndef get_id_from_file_path(file_path):\n return file_path.split(os.path.sep)[-1].replace('.tif', '')\n\n\ndef chunker(seq, size):\n return (seq[pos:pos + size] for pos in range(0, len(seq), size))\n\n\ndef get_seq():\n seq = iaa.Sometimes(0.2,\n iaa.Noop(),\n iaa.OneOf([\n iaa.Fliplr(0.5),\n iaa.Flipud(0.5),\n # scale images to 90-110% of their size, individually per axis\n iaa.Affine(scale=(0.9, 1.1)),\n # iaa.CoarseDropout(0.02, size_percent=0.5),\n # iaa.WithChannels(0, iaa.Add((10, 100))),\n # either change the brightness of the whole image(sometimes per channel)\n # or change the brightness of subareas\n # iaa.Multiply((0.9, 1.1)),\n # iaa.Multiply((0.5, 1.5), per_channel=0.5),\n iaa.Affine(shear=(-5, 5)), # shear by -5 to +5 degrees\n iaa.Affine(rotate=(-5, 5)), # rotate by -5 to +5 degrees\n iaa.PiecewiseAffine(scale=(0.01, 0.05))\n ]))\n return seq\n\n# 将图像尺寸固定为(224, 224)\ndef resized_image(file_path):\n img = cv2.imread(file_path) # cv2读取图片速度比pillow快\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # cv2读取通道顺序为BGR,所以要转换成RGB\n img = cv2.resize(img, (96, 96))\n # img -= np.mean(img, keepdims=True)\n # img /= np.std(img, keepdims=True) + K.epsilon()\n return img\n\ndef data_gen(list_files, id_label_map, batch_size, augment=False):\n seq = get_seq()\n while True:\n shuffle(list_files)\n for batch in chunker(list_files, batch_size):\n X = [resized_image(x) for x in batch]\n Y = [id_label_map[get_id_from_file_path(x)] for x in batch]\n if augment:\n X = seq.augment_images(X)\n X = [preprocess_input(x) for x in X]\n\n yield np.array(X), np.array(Y)\n\n# Cancer dataset generator\nclass CancerDataset(Sequence):\n \"\"\"input data generator, a sequence object\n # Argument:\n label_path: The path of train_label.csv, file\n batch_size: The size of input_data's batch, int\n target_size: The image size, tuple\n mode: default is to 'train', str\n aug: default is to True, bool\n # Returns:\n A batch of input_data sequence\n\n \"\"\"\n def __init__(self, label_path, batch_size, target_size, mode='train', aug=True, one_hot=False):\n # 初始化类实例参数\n self.label_path = label_path\n # self.df_train = df_train\n self.batch_size = batch_size\n self.target_size = target_size\n # self.num_class = num_class\n self.mode = mode\n self.aug = aug\n self.one_hot = one_hot\n if isfile(self.label_path):\n self.df_train = pd.read_csv(self.label_path)\n self.id_label_map = {k: v for k, v in zip(self.df_train.id.values, self.df_train.label.values)}\n else:\n print('The train_labels.csv is not exist!')\n self.train_id, self.val_id = train_test_split(self.df_train['id'], test_size=0.15,\n random_state=8, shuffle=True)\n self.data = []\n if self.mode == \"train\":\n self.data = self.train_id\n self.data = [x for x in self.train_id]\n if self.mode == \"val\":\n self.data = self.val_id\n self.data = [x for x in self.val_id]\n\n def __len__(self):\n \"\"\"Number of batch in the Sequence.\n \"\"\"\n return len(self.data) // self.batch_size\n\n def __getitem__(self, index):\n \"\"\"Gets batch at position `index`.\n \"\"\"\n start = self.batch_size * index\n size = min(len(self.data) - start, self.batch_size)\n X = []\n Y = []\n for i in range(size):\n img = self.resize_image(self.data[start + i])\n img = self.augment_img(img)\n img = img.astype(np.uint8)\n label = self.id_label_map[self.data[start + i]]\n X.append(img)\n Y.append(label)\n # Y = [self.id_label_map[x] for x in self.data[start: start + size]]\n X = [preprocess_input(x) for x in X]\n\n return np.array(X), np.array(Y)\n def augment_img(self, image):\n \"\"\"\n Return the array of augment image\n :param image: image id\n :return: image array\n \"\"\"\n seq = iaa.Sequential([\n iaa.OneOf([\n iaa.Affine(rotate=90),\n iaa.Affine(rotate=180),\n iaa.Affine(rotate=270),\n iaa.Fliplr(0.5),\n iaa.Flipud(0.5),\n iaa.Multiply((0.8, 1.2), per_channel=0.5),\n iaa.Affine(shear=(-5, 5)), # shear by -5 to +5 degrees\n iaa.Affine(rotate=(-5, 5)), # rotate by -5 to +5 degrees\n ])], random_order=True)\n\n image_aug = seq.augment_image(image)\n return image_aug\n def resize_image(self, x):\n # 将图像尺寸固定为target_size\n try:\n x_file = self.expand_path(x)\n img = cv2.imread(x_file) # cv2读取图片速度比pillow快\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) # cv2读取通道顺序为BGR,所以要转换成RGB\n img = cv2.resize(img, self.target_size[:2])\n # Normalize to zero mean and unit variance\n # img -= np.mean(img, keepdims=True)\n # img /= np.std(img, keepdims=True) + K.epsilon()\n img = img.astype(np.uint8)\n\n except Exception as e:\n print(e)\n\n return img\n def expand_path(self, id):\n # 根据图像id,获取文件完整路径\n if isfile(os.path.join(TRAIN, id + '.tif')):\n return os.path.join(TRAIN, id + '.tif')\n if isfile(os.path.join(TEST, id + '.tif')):\n return os.path.join(TEST, id + '.tif')\n\n return id\n\ndef train_model(label_path, batch_size, input_shape, epochs, model,\n model_path=os.path.join(MODEL, '%s.h5' % base_name)):\n \"\"\"create model and train model\n # Parameters:\n @label_path: the path of train.csv file\n @input_shape: the shape of input image\n @epochs: Integer. Number of epochs to train the model\n @model: model object\n @model_path: the path of saved model\n # Return:\n A `History` object. Its `History.history` attribute is a record of \n training loss values and metrics values at successive epochs, \n as well as validation loss values and validation metrics values (if applicable).\n \"\"\"\n # save the best model when train\n checkpoint = ModelCheckpoint(model_path, monitor='val_acc',\n verbose=1, mode='max', save_weights_only=True)\n # reduce learning rate when a metric has stopped improving\n reduceLROnPlat = ReduceLROnPlateau(monitor='val_acc', factor=0.5,\n patience=2, verbose=1,\n mode='max', min_lr=1e-06)\n # stop training when a monitored quantity has stopped improving\n early = EarlyStopping(monitor=\"val_acc\", mode=\"max\",\n patience=6, restore_best_weights=True)\n # callback tensorboard class\n tbCallBack = TensorBoard(log_dir='./logs', histogram_freq=0,\n write_graph=True, write_images=True)\n\n train_gen = CancerDataset(label_path, batch_size, input_shape, mode=\"train\", aug=True)\n val_gen = CancerDataset(label_path, batch_size * 2, input_shape, mode=\"val\", aug=False)\n\n # fit model\n history = model.fit_generator(\n generator=train_gen,\n # generator=data_gen(train, id_label_map, batch_size, augment=True),\n steps_per_epoch=len(train_gen.data) // train_gen.batch_size,\n epochs=epochs,\n verbose=2,\n callbacks=[checkpoint, reduceLROnPlat, early, tbCallBack],\n validation_data=val_gen,\n validation_steps=len(val_gen.data) // val_gen.batch_size\n )\n return history\n\ndef visualization_history(history):\n \"\"\"visualization train acc and loss\n \"\"\"\n # Plot training & validation accuracy values\n acc = history.history['acc']\n epochs = range(1,len(acc)+1)\n plt.figure(figsize=(16, 6), dpi=200) \n plt.plot(epochs, history.history['acc'], 'bo', label='Train acc')\n plt.plot(epochs, history.history['val_acc'], 'b',label='Validation acc')\n plt.title('Model train and validation accuracy')\n plt.ylabel('Accuracy')\n plt.xlabel('Epoch')\n plt.legend(['Train_acc', 'val_acc'], loc='upper right')\n plt.show()\n plt.savefig('cancer_train_history_acc.jpg')\n\n # Plot training & validation loss values\n plt.figure(figsize=(16, 6), dpi=200) \n plt.plot(epochs, history.history['loss'], 'bo', label='Train loss')\n plt.plot(epochs, history.history['val_loss'], 'b', label='Validation loss')\n plt.title('Model train and validation loss')\n plt.ylabel('Loss')\n plt.xlabel('Epoch')\n plt.legend(['Train_loss', 'val_loss'], loc='upper right')\n plt.show()\n plt.savefig('cancer_train_history_loss.jpg')\n\nif __name__ == \"__main__\":\n start = time.time()\n # Start train model\n model = get_model_classif_ResNet101(input_shape, learning_late_base, num_classes, 0) # Create and compile model\n _ = train_model(label_path, batch_size_base, input_shape, epochs_base, model, model_path)\n model = get_model_classif_ResNet101(input_shape, learning_late_base, num_classes, 1)\n history = train_model(label_path, batch_size_base, input_shape, epochs_base * 10, model, model_path)\n print(model.metrics_names)\n # visualization training history\n visualization_history(history)\n\n # Load the trained model\n model = get_model_classif_ResNet101(input_shape, learning_late_base, num_classes, 1)\n model.load_weights(model_path)\n\n # Start predict\n preds = []\n ids = []\n for batch in chunker(test_files, batch_size_base):\n X = [preprocess_input(resized_image(x)) for x in batch]\n ids_batch = [get_id_from_file_path(x) for x in batch]\n X = np.array(X)\n preds_batch = ((model.predict(X).ravel() * model.predict(X[:, ::-1, :, :]).ravel() * model.predict(\n X[:, ::-1, ::-1, :]).ravel() * model.predict(X[:, :, ::-1, :]).ravel()) ** 0.25).tolist()\n preds += preds_batch\n ids += ids_batch\n # print(preds)\n df = pd.DataFrame({'id': ids, 'label': preds})\n df.to_csv(\"./submit/%s.csv\" % base_name, index=False)\n df.head()\n end = time.time()\n print(\"Program run %d hours\" % (end-start)/60/60)\n print(\"Program run success!\")","repo_name":"HarleysZhang/image_classification_project","sub_path":"histopathologic_cancer_detection/main_all.py","file_name":"main_all.py","file_ext":"py","file_size_in_byte":13856,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"16790206482","text":"\n'''\nPart of the code is drawn from \nhttps://github.com/usc-sail/gard-adversarial-speaker-id\nPaper: \nJati et al. Adversarial attack and defense strategies for deep speaker recognition systems\n'''\nimport torch.nn as nn\nimport time\nimport sys\n\nfrom model.Preprocessor import Preprocessor\n\nfrom defense.defense import *\nfrom defense.time_domain import *\nfrom defense.frequency_domain import *\nfrom defense.speech_compression import *\nfrom defense.feature_level import *\n\nBITS = 16\n\nclass AudioNetOri(nn.Module):\n \"\"\"Adaption of AudioNet (arXiv:1807.03418).\"\"\"\n def __init__(self, num_class, transform_layer=None, transform_param=None):\n super().__init__()\n self.prep = Preprocessor()\n self.num_spks = num_class\n \n assert transform_layer in (Input_Transformation + [None])\n self.wav_transform = False\n self.feat_transform = False\n self.transform_layer = None\n self.param = None\n self.other_param = None\n \n if transform_layer == 'FEATURE_COMPRESSION' or transform_layer == 'FC':\n self.transform_layer = FEATURE_COMPRESSION\n self.feat_transform = True\n assert isinstance(transform_param, list) and len(transform_param) == 4\n self.cl_m, self.feat_point, self.param, self.other_param = transform_param\n assert self.cl_m in ['kmeans', 'warped_kmeans']\n assert self.feat_point in ['raw'] # AudioNet not uses delta, cmvn and final\n if self.cl_m == 'kmeans':\n assert self.other_param in [\"L2\", \"cos\"]\n elif self.cl_m == 'warped_kmeans':\n assert self.other_param in ['ts', 'random']\n else:\n raise NotImplementedError('Currently FEATURE COMPRESSION only suppots kmeans and warped_kmeans')\n assert 0 < self.param <= 1\n elif transform_layer:\n self.wav_transform = True\n if transform_layer == 'BPF':\n assert isinstance(transform_param, list) and len(transform_param) == 2\n self.param = transform_param\n self.transform_layer = getattr(sys.modules[__name__], transform_layer)\n \n print(self.wav_transform,\n self.feat_transform,\n self.transform_layer,\n self.param,\n self.other_param)\n\n # =========== EXPERIMENTAL pre-filtering ======\n # 32 x 100\n self.conv1 = nn.Sequential(\n nn.Conv2d(1, 1, kernel_size=[5, 5], stride=1, padding=[2, 2]),\n nn.BatchNorm2d(1),\n )\n # =========== ============= ======\n\n # 32 x 100\n self.conv2 = nn.Sequential( \n nn.Conv1d(32, 64, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm1d(64),\n nn.ReLU(),\n nn.MaxPool1d(2, stride=2)\n )\n # 64 x 100\n self.conv3 = nn.Sequential(\n nn.Conv1d(64, 128, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm1d(128),\n nn.ReLU(),\n )\n # 128 x 100\n self.conv4 = nn.Sequential(\n nn.Conv1d(128, 128, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm1d(128),\n nn.ReLU(),\n )\n # 128 x 50\n self.conv5 = nn.Sequential(\n nn.Conv1d(128, 128, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm1d(128),\n nn.ReLU(),\n nn.MaxPool1d(2, stride=2)\n )\n # 128 x 50\n self.conv6 = nn.Sequential(\n nn.Conv1d(128, 128, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm1d(128),\n nn.ReLU(),\n )\n # 128 x 25\n self.conv7 = nn.Sequential(\n nn.Conv1d(128, 64, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm1d(64),\n nn.ReLU(),\n nn.MaxPool1d(2, stride=2)\n )\n self.conv8 = nn.Sequential(\n nn.Conv1d(64, 32, kernel_size=3, stride=1, padding=0),\n nn.BatchNorm1d(32),\n nn.ReLU(),\n )\n\n # 32 x 30\n self.fc = nn.Linear(32, num_class)\n \n\n def make_feature(self, x):\n\n if self.wav_transform:\n x = self.transform_layer(x.squeeze(1), param=self.param).unsqueeze(1)\n \n x = self.prep(x.squeeze(1))\n if self.feat_transform:\n x = self.apply_feat_filter(x)\n \n return x\n \n def apply_feat_filter(self, x_batch):\n \n y_batch = None\n start_t = time.time()\n #### Naive Loop, since it is hard to parallel ###\n for index, x in enumerate(x_batch):\n t1 = time.time()\n # y = self.transform_layer(x.T, param=self.param, other_param=self.other_param)\n y = self.transform_layer(x.T, self.cl_m, param=self.param, other_param=self.other_param)\n t2 = time.time()\n if index == 0:\n y_batch = y.T.view(1, y.shape[1], -1) \n else:\n y_batch = torch.cat([y_batch, y.T.view(1, y.shape[1], -1)], dim=0)\n end_t = time.time()\n return y_batch \n \n def encode_feat(self, x):\n # ===== pre-filtering ========\n # [B, F, T]\n x = x.unsqueeze(1)\n x = self.conv1(x)\n x = x.squeeze(1)\n # ===== pre-filtering ========\n\n x = self.conv2(x)\n x = self.conv3(x)\n x = self.conv4(x)\n x = self.conv5(x)\n x = self.conv6(x)\n x = self.conv7(x)\n\n target_len = 3\n real_len = x.shape[2]\n if real_len < target_len:\n n = target_len // real_len\n if target_len % real_len == 0:\n n = n\n else:\n n = n + 1\n x = x.repeat(1, 1, n)\n\n x = self.conv8(x)\n x, _ = x.max(2)\n return x\n\n def encode(self, x):\n x = self.make_feature(x)\n return self.encode_feat(x)\n\n def predict_from_embeddings(self, x):\n return self.fc(x)\n\n def forward(self, x):\n \"\"\"\n Inputs:\n x: [B, 1, T] waveform\n Outputs:\n x: [B, 1, T] waveform\n \"\"\"\n # \n lower = -1\n upper = 1\n if not (x.max() <= 2 * upper and x.min() >= 2 * lower): # 2*lower and 2*upper due to floating point issue, e.g., sometimes will have 1.0002\n x = x / (2 ** (BITS-1)) \n embedding = self.encode(x)\n logits = self.predict_from_embeddings(embedding)\n return logits\n \n def score(self, x):\n logits = self.forward(x)\n scores = F.softmax(logits, dim=1)\n return scores\n \n def make_decision(self, x):\n scores = self.score(x)\n decisions = torch.argmax(scores, dim=1)\n return decisions, scores","repo_name":"mmwan101010/DeafBackdoor","sub_path":"model/AudioNetOri.py","file_name":"AudioNetOri.py","file_ext":"py","file_size_in_byte":6703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3224856678","text":"# Задача 2: Найдите сумму цифр трехзначного числа.\n# *Пример:*\n# 123 -> 6 (1 + 2 + 3)\n# 100 -> 1 (1 + 0 + 0)\n\n\nwhile True:\n a = int(input('введите трехзначное число: '))\n if 100 <= a <= 999:\n print(a % 10 + a // 10 % 10 + a // 100)\n break\n else:\n print('это не трехзначное число')\n","repo_name":"SergeyMihalich/GB_homework","sub_path":"Python/one/sem_1/homework_1.py","file_name":"homework_1.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"36338441945","text":"from io import BufferedReader\nfrom logging import getLogger as get_logger\nfrom typing import Iterable\nfrom urllib.parse import urlsplit\n\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom urllib3.util.retry import Retry\n\nfrom megfile.errors import http_should_retry, patch_method, translate_http_error\nfrom megfile.interfaces import PathLike\nfrom megfile.lib.compat import fspath\nfrom megfile.utils import binary_open\n\n__all__ = [\n 'is_http',\n 'http_open',\n]\n\n_logger = get_logger(__name__)\n\nmax_retries = 10\n\n\ndef get_http_session(\n timeout: int = 10, status_forcelist: Iterable[int] = (502, 503, 504)):\n session = requests.Session()\n session.timeout = timeout\n\n def after_callback(response):\n if response.status_code in status_forcelist:\n response.raise_for_status()\n return response\n\n def before_callback(method, url, **kwargs):\n _logger.debug(\n 'send http request: %s %r, with parameters: %s', method, url,\n kwargs)\n\n session.request = patch_method(\n session.request,\n max_retries=max_retries,\n should_retry=http_should_retry,\n before_callback=before_callback,\n after_callback=after_callback,\n )\n return session\n\n\ndef is_http(path: PathLike) -> bool:\n '''http scheme definition: http(s)://domain/path\n\n :param path: Path to be tested\n :returns: True if path is http url, else False\n '''\n\n path = fspath(path)\n if not isinstance(path, str) or not (path.startswith('http://') or\n path.startswith('https://')):\n return False\n\n parts = urlsplit(path)\n return parts.scheme == 'http' or parts.scheme == 'https'\n\n\n@binary_open\ndef http_open(http_url: str, mode: str = 'rb') -> BufferedReader:\n '''Open a BytesIO to read binary data of given http(s) url\n\n .. note ::\n\n Essentially, it reads data of http(s) url to memory by requests, and then return BytesIO to user.\n\n :param http_url: http(s) url, e.g.: http(s)://domain/path\n :param mode: Only supports 'rb' mode now\n :return: BytesIO initialized with http(s) data\n '''\n if mode not in ('rb',):\n raise ValueError('unacceptable mode: %r' % mode)\n\n try:\n response = requests.get(http_url, stream=True, timeout=10.0)\n response.raise_for_status()\n except Exception as error:\n raise translate_http_error(error, http_url)\n\n response.raw.auto_close = False\n return BufferedReader(response.raw)\n","repo_name":"leavers/megfile","sub_path":"megfile/http.py","file_name":"http.py","file_ext":"py","file_size_in_byte":2509,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"52"} +{"seq_id":"16840221736","text":"import sys\n\nfrom utils.alphabet import Alphabet\nfrom utils.functions import *\nfrom utils.gazetteer import Gazetteer\n\nSTART = \"\"\nUNKNOWN = \"\"\nPADDING = \"\"\nNULLKEY = \"-null-\"\n\n\nclass Data:\n def __init__(self):\n self.MAX_SENTENCE_LENGTH = 250\n self.MAX_WORD_LENGTH = -1\n self.number_normalized = True\n self.norm_char_emb = True\n self.norm_bichar_emb = True\n self.norm_gaz_emb = False\n self.use_single = False\n self.char_alphabet = Alphabet('char')\n self.bichar_alphabet = Alphabet('bichar')\n self.label_alphabet = Alphabet('label', True)\n self.gaz_lower = False\n self.gaz = Gazetteer(self.gaz_lower, self.use_single)\n self.gaz_alphabet = Alphabet('gaz')\n self.HP_fix_gaz_emb = False\n self.HP_use_gaz = True\n\n self.tagScheme = \"NoSeg\"\n\n self.train_texts = []\n self.dev_texts = []\n self.test_texts = []\n self.raw_texts = []\n\n self.train_Ids = []\n self.dev_Ids = []\n self.test_Ids = []\n self.raw_Ids = []\n self.use_bichar = False\n self.char_emb_dim = 50\n self.bichar_emb_dim = 50\n self.gaz_emb_dim = 50\n self.posi_emb_dim = 30\n self.gaz_dropout = 0.5\n self.pretrain_char_embedding = None\n self.pretrain_bichar_embedding = None\n self.pretrain_gaz_embedding = None\n self.label_size = 0\n self.char_alphabet_size = 0\n self.bichar_alphabet_size = 0\n self.character_alphabet_size = 0\n self.label_alphabet_size = 0\n # hyper parameters\n self.HP_iteration = 100\n self.HP_batch_size = 1\n # self.HP_char_hidden_dim = 50 # int. Character hidden vector dimension for character sequence layer.\n self.HP_hidden_dim = 200 # int. Char hidden vector dimension for word sequence layer.\n self.HP_dropout = 0.5 # float. Dropout probability.\n self.HP_lstm_layer = 1 # int. LSTM layer number for word sequence layer.\n self.HP_bilstm = True # boolen. If use bidirection lstm for word seuquence layer.\n self.HP_gpu = False\n # Word level LSTM models (e.g. char LSTM + word LSTM + CRF) would prefer a `lr` around 0.015.\n # Word level CNN models (e.g. char LSTM + word CNN + CRF) would prefer a `lr` around 0.005 and with more iterations.\n self.HP_lr = 0.015\n self.HP_lr_decay = 0.05 # float. Learning rate decay rate, only works when optimizer=SGD.\n self.HP_clip = 1.0 # float. Clip the gradient which is larger than the setted number.\n self.HP_momentum = 0 # float. Momentum\n\n self.HP_use_posi = False\n self.HP_num_layer = 4\n self.HP_rethink_iter = 2\n self.model_name = 'CNN_model'\n self.posi_alphabet_size = 0\n\n def show_data_summary(self):\n print(\"DATA SUMMARY START:\")\n print(\" Tag scheme: %s\" % (self.tagScheme))\n print(\" MAX SENTENCE LENGTH: %s\" % (self.MAX_SENTENCE_LENGTH))\n print(\" MAX WORD LENGTH: %s\" % (self.MAX_WORD_LENGTH))\n print(\" Number normalized: %s\" % (self.number_normalized))\n print(\" Use bigram: %s\" % (self.use_bichar))\n print(\" Char alphabet size: %s\" % (self.char_alphabet_size))\n print(\" Bichar alphabet size: %s\" % (self.bichar_alphabet_size))\n print(\" Gaz alphabet size: %s\" % (self.gaz_alphabet.size()))\n print(\" Label alphabet size: %s\" % (self.label_alphabet_size))\n print(\" Word embedding size: %s\" % (self.char_emb_dim))\n print(\" Bichar embedding size: %s\" % (self.bichar_emb_dim))\n print(\" Gaz embedding size: %s\" % (self.gaz_emb_dim))\n print(\" Norm word emb: %s\" % (self.norm_char_emb))\n print(\" Norm bichar emb: %s\" % (self.norm_bichar_emb))\n print(\" Norm gaz emb: %s\" % (self.norm_gaz_emb))\n print(\" Norm gaz dropout: %s\" % (self.gaz_dropout))\n print(\" Train instance number: %s\" % (len(self.train_texts)))\n print(\" Dev instance number: %s\" % (len(self.dev_texts)))\n print(\" Test instance number: %s\" % (len(self.test_texts)))\n print(\" Raw instance number: %s\" % (len(self.raw_texts)))\n print(\" Hyperpara iteration: %s\" % (self.HP_iteration))\n print(\" Hyperpara batch size: %s\" % (self.HP_batch_size))\n print(\" Hyperpara lr: %s\" % (self.HP_lr))\n print(\" Hyperpara lr_decay: %s\" % (self.HP_lr_decay))\n print(\" Hyperpara HP_clip: %s\" % (self.HP_clip))\n print(\" Hyperpara momentum: %s\" % (self.HP_momentum))\n print(\" Hyperpara hidden_dim: %s\" % (self.HP_hidden_dim))\n print(\" Hyperpara dropout: %s\" % (self.HP_dropout))\n print(\" Hyperpara lstm_layer: %s\" % (self.HP_lstm_layer))\n print(\" Hyperpara bilstm: %s\" % (self.HP_bilstm))\n print(\" Hyperpara GPU: %s\" % (self.HP_gpu))\n print(\" Hyperpara use_gaz: %s\" % (self.HP_use_gaz))\n print(\" Hyperpara fix gaz emb: %s\" % (self.HP_fix_gaz_emb))\n print(\"DATA SUMMARY END.\")\n sys.stdout.flush()\n\n def refresh_label_alphabet(self, input_file):\n old_size = self.label_alphabet_size\n self.label_alphabet.clear(True)\n in_lines = open(input_file, 'r').readlines()\n for line in in_lines:\n if len(line) > 2:\n pairs = line.strip().split()\n label = pairs[-1]\n self.label_alphabet.add(label)\n self.label_alphabet_size = self.label_alphabet.size()\n start_s = False\n start_b = False\n for label, _ in self.label_alphabet.iteritems():\n if \"S-\" in label.upper():\n start_s = True\n elif \"B-\" in label.upper():\n start_b = True\n if start_b:\n if start_s:\n self.tagScheme = \"BMES\"\n else:\n self.tagScheme = \"BIO\"\n self.fix_alphabet()\n print(\"Refresh label alphabet finished: old:%s -> new:%s\" % (old_size, self.label_alphabet_size))\n\n # \"陈 B-PER\"\n def build_alphabet(self, input_file):\n if input_file is None or not os.path.isfile(input_file):\n # print('[' + sys._getframe().f_code.co_name + '] file ' + str(input_file) + \"can not be found or is not a file address\")\n return\n with codecs.open(input_file, 'r', 'utf-8') as fr:\n in_lines = fr.readlines()\n seqlen = 0\n for idx in range(len(in_lines)):\n line = in_lines[idx] # '陈 B-PER\\n'\n # 行不空 则加入label word bichar char\n if len(line) > 2:\n # if sequence labeling data format i.e. CoNLL 2003\n pairs = line.strip().split() # list ['陈','B-PER']\n char = pairs[0] # '陈'\n if self.number_normalized: # 数字转0\n char = normalize_char(char)\n label = pairs[-1] # \"B-PER\"\n # build feature alphabet\n self.label_alphabet.add(label)\n self.char_alphabet.add(char)\n if idx < len(in_lines) - 1 and len(in_lines[idx + 1]) > 2:\n bichar = char + in_lines[idx + 1].strip().split()[0] # 陈元\n else:\n bichar = char + NULLKEY\n self.bichar_alphabet.add(bichar)\n seqlen += 1\n else:\n self.posi_alphabet_size = max(seqlen, self.posi_alphabet_size)\n seqlen = 0\n self.char_alphabet_size = self.char_alphabet.size()\n self.bichar_alphabet_size = self.bichar_alphabet.size()\n self.label_alphabet_size = self.label_alphabet.size()\n start_s = False\n start_b = False\n for label, _ in self.label_alphabet.iteritems():\n if \"S-\" in label.upper():\n start_s = True\n elif \"B-\" in label.upper():\n start_b = True\n if start_b:\n if start_s:\n self.tagScheme = \"BMES\"\n else:\n self.tagScheme = \"BIO\"\n\n def build_gaz_file(self, gaz_file):\n # build gaz file, initial read gaz embedding file\n if gaz_file:\n with codecs.open(gaz_file, 'r', 'utf-8') as fr:\n fins = fr.readlines()\n for fin in fins:\n fin = fin.strip().split()[0]\n if fin:\n self.gaz.insert(fin, \"one_source\")\n print(\"Load gaz file: \", gaz_file, \" total size:\", self.gaz.size())\n else:\n print('[' + sys._getframe().f_code.co_name + '] ' + \"Gaz file is None, load nothing\")\n\n def build_gaz_alphabet(self, input_file):\n if input_file is None or not os.path.isfile(input_file):\n # print('[' + sys._getframe().f_code.co_name + '] file ' + str(input_file) + \"can not be found or is not a file address\")\n return\n with codecs.open(input_file, 'r', 'utf-8') as fr:\n in_lines = fr.readlines()\n word_list = []\n for line in in_lines:\n if len(line) > 3:\n word = line.split()[0]\n if self.number_normalized:\n word = normalize_char(word)\n word_list.append(word)\n else:\n w_length = len(word_list)\n for idx in range(w_length):\n matched_entity = self.gaz.enumerateMatchList(word_list[idx:])\n for entity in matched_entity:\n # print entity, self.gaz.searchId(entity),self.gaz.searchType(entity)\n self.gaz_alphabet.add(entity)\n word_list = []\n print(\"gaz alphabet size:\", self.gaz_alphabet.size())\n\n # Alphabet\n def fix_alphabet(self):\n self.char_alphabet.close() # alphabet.keep_growing=False\n self.bichar_alphabet.close()\n self.label_alphabet.close()\n self.gaz_alphabet.close()\n\n def build_char_pretrain_emb(self, emb_path):\n print(\"build char pretrain emb...\")\n self.pretrain_char_embedding, self.char_emb_dim = build_pretrain_embedding(emb_path, self.char_alphabet, self.char_emb_dim, self.norm_char_emb)\n\n def build_bichar_pretrain_emb(self, emb_path):\n print(\"build bichar pretrain emb...\")\n self.pretrain_bichar_embedding, self.bichar_emb_dim = build_pretrain_embedding(emb_path, self.bichar_alphabet, self.bichar_emb_dim,\n self.norm_bichar_emb)\n\n def build_gaz_pretrain_emb(self, emb_path):\n print(\"build gaz pretrain emb...\")\n self.pretrain_gaz_embedding, self.gaz_emb_dim = build_pretrain_embedding(emb_path, self.gaz_alphabet, self.gaz_emb_dim, self.norm_gaz_emb)\n\n def generate_instance(self, input_file, name):\n self.fix_alphabet()\n if name == \"train\":\n self.train_texts, self.train_Ids = read_seg_instance(input_file, self.char_alphabet, self.bichar_alphabet,\n self.label_alphabet, self.number_normalized, self.MAX_SENTENCE_LENGTH)\n elif name == \"dev\":\n self.dev_texts, self.dev_Ids = read_seg_instance(input_file, self.char_alphabet, self.bichar_alphabet,\n self.label_alphabet, self.number_normalized, self.MAX_SENTENCE_LENGTH)\n elif name == \"test\":\n self.test_texts, self.test_Ids = read_seg_instance(input_file, self.char_alphabet, self.bichar_alphabet,\n self.label_alphabet, self.number_normalized, self.MAX_SENTENCE_LENGTH)\n else:\n print(\"Error: you can only generate train/dev/test instance! Illegal input:%s\" % name)\n\n def generate_instance_with_gaz(self, input_file, name):\n self.fix_alphabet()\n if name == \"train\":\n self.train_texts, self.train_Ids = read_instance_with_gaz(input_file, self.gaz, self.char_alphabet, self.bichar_alphabet,\n self.gaz_alphabet, self.label_alphabet, self.number_normalized, self.MAX_SENTENCE_LENGTH)\n elif name == \"dev\":\n self.dev_texts, self.dev_Ids = read_instance_with_gaz(input_file, self.gaz, self.char_alphabet, self.bichar_alphabet,\n self.gaz_alphabet, self.label_alphabet, self.number_normalized, self.MAX_SENTENCE_LENGTH)\n elif name == \"test\":\n self.test_texts, self.test_Ids = read_instance_with_gaz(input_file, self.gaz, self.char_alphabet, self.bichar_alphabet,\n self.gaz_alphabet, self.label_alphabet, self.number_normalized, self.MAX_SENTENCE_LENGTH)\n else:\n print(\"Error: you can only generate train/dev/test instance! Illegal input:%s\" % name)\n\n def generate_instance_with_gaz_2(self, input_file, name):\n self.fix_alphabet()\n if name == \"train\":\n self.train_texts, self.train_Ids = read_instance_with_gaz_2(self.HP_num_layer, input_file, self.gaz, self.char_alphabet, self.bichar_alphabet,\n self.gaz_alphabet, self.label_alphabet, self.number_normalized,\n self.MAX_SENTENCE_LENGTH)\n elif name == \"dev\":\n self.dev_texts, self.dev_Ids = read_instance_with_gaz_2(self.HP_num_layer, input_file, self.gaz, self.char_alphabet, self.bichar_alphabet,\n self.gaz_alphabet, self.label_alphabet, self.number_normalized,\n self.MAX_SENTENCE_LENGTH)\n elif name == \"test\":\n self.test_texts, self.test_Ids = read_instance_with_gaz_2(self.HP_num_layer, input_file, self.gaz, self.char_alphabet, self.bichar_alphabet,\n self.gaz_alphabet, self.label_alphabet, self.number_normalized,\n self.MAX_SENTENCE_LENGTH)\n else:\n print(\"Error: you can only generate train/dev/test instance! Illegal input:%s\" % (name))\n def generate_instance_with_gaz_3(self, input_file, name):\n self.fix_alphabet()\n if name == \"train\":\n self.train_texts, self.train_Ids = read_instance_with_gaz_3(input_file, self.gaz, self.char_alphabet, self.bichar_alphabet,\n self.gaz_alphabet, self.label_alphabet, self.number_normalized,\n self.MAX_SENTENCE_LENGTH, self.use_single)\n elif name == \"dev\":\n self.dev_texts, self.dev_Ids = read_instance_with_gaz_3(input_file, self.gaz, self.char_alphabet, self.bichar_alphabet,\n self.gaz_alphabet, self.label_alphabet, self.number_normalized,\n self.MAX_SENTENCE_LENGTH, self.use_single)\n elif name == \"test\":\n self.test_texts, self.test_Ids = read_instance_with_gaz_3(input_file, self.gaz, self.char_alphabet, self.bichar_alphabet,\n self.gaz_alphabet, self.label_alphabet, self.number_normalized,\n self.MAX_SENTENCE_LENGTH, self.use_single)\n else:\n print(\"Error: you can only generate train/dev/test instance! Illegal input:%s\" % (name))\n def write_decoded_results(self, output_file, predict_results, name):\n fout = open(output_file, 'w')\n sent_num = len(predict_results)\n content_list = []\n if name == 'test':\n content_list = self.test_texts\n elif name == 'dev':\n content_list = self.dev_texts\n elif name == 'train':\n content_list = self.train_texts\n else:\n print(\"Error: illegal name during writing predict result, name should be within train/dev/test/raw !\")\n assert (sent_num == len(content_list))\n for idx in range(sent_num):\n sent_length = len(predict_results[idx])\n for idy in range(sent_length):\n ## content_list[idx] is a list with [word, char, label]\n fout.write(content_list[idx][0][idy].encode('utf-8') + \" \" + predict_results[idx][idy] + '\\n')\n\n fout.write('\\n')\n fout.close()\n print(\"Predict %s result has been written into file. %s\" % (name, output_file))\n","repo_name":"zerohd4869/Chinese-NER","sub_path":"utils/data.py","file_name":"data.py","file_ext":"py","file_size_in_byte":17283,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"52"} +{"seq_id":"16830274122","text":"import os\nimport time\nfrom converter import Converter\n\n\ndef prepareTextFile(pdf_file_destination, text_file_destination):\n \"\"\"This function prepares data\"\"\"\n # Initialize converter object\n\n if pdf_file_destination.endswith(\".pdf\"):\n PDF = Converter()\n PDF.pdfToImage(pdf_file_destination)\n PDF.imageToText(text_file_destination)\n PDF.removeImages()\n else:\n print(\"Unknown Extension we only except [png,jpg,jpeg and pdf] extensions\")\n\n\npfdf_files = [\n \"2005-08.pdf\",\n \"2005-12.pdf\",\n \"2005-17.pdf\",\n \"2005-18.pdf\",\n \"2005-24.pdf\",\n \"2005-29.pdf\",\n \"2005-32.pdf\",\n \"2005-34.pdf\",\n \"2005-38.pdf\",\n]\n\n\n# Remove exesting text files in corpus/text that are similar to the pdf files in corpus/pdf\n\n\ndef remove_text_files(file: str):\n if os.path.exists(f\"corpus/text/{file[:-4]}.txt\"):\n os.remove(f\"corpus/text/{file[:-4]}.txt\")\n\n\ndef main(files):\n for file in files:\n # Remove test fiels if they exist\n # Otherwise the converter will append to the existing file\n # and we dont wanna do that :)\n remove_text_files(file)\n prepareTextFile(f\"corpus/pdf/{file}\", f\"corpus/text/{file[:-4]}.txt\")\n print(f\"Converted {file} to text\")\n\n\nif __name__ == \"__main__\":\n start_time = time.time()\n main(pfdf_files)\n print(f\"--- {time.time() - start_time} seconds ---\")\n","repo_name":"AminAbdisamad/tc_bank_docs_downloader","sub_path":"src/converter/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1384,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"6609581367","text":"import csv\n\n# Đọc dữ liệu từ file CSV gốc\nwith open('Clean_Dataset.csv', 'r') as f:\n reader = csv.reader(f)\n rows = list(reader)\n\nfirst_1000_rows = rows[10000:]\n\n# Ghi kết quả vào tệp CSV mới\nwith open('output.csv', 'w', newline='') as f:\n writer = csv.writer(f)\n writer.writerows(first_1000_rows)","repo_name":"VuQuyenHD/FlightFarePrediction","sub_path":"Dataset/take_data.py","file_name":"take_data.py","file_ext":"py","file_size_in_byte":329,"program_lang":"python","lang":"vi","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"9757303876","text":"import numpy as np\n\nimport torch.nn.functional as F\nimport torch\nimport torch.nn as nn\nfrom torchvision.models.segmentation import deeplabv3_resnet50, fcn_resnet50, fcn_resnet101\nimport requests\nfrom PIL import Image\nfrom torchvision import transforms\nimport cv2\nimport matplotlib.pyplot as plt\nimport matplotlib\n#matplotlib.use('TkAgg') # Necessary to run matplotlib\nfrom tqdm import tqdm\n\nfrom pytorch_grad_cam.utils.image import show_cam_on_image\n\nimport skimage\n\nfrom collections import OrderedDict\n\nclass TorchSegmentationWrapper(nn.Module):\n def __init__(self, model):\n super().__init__()\n self.model = model\n def forward(self, x):\n return self.model(x)['out']\n\ndef vis_predict(image, model, preprocess_transform, DEVICE = 'cpu', mask = None, box = None, fig_name = None, vis = True):\n if preprocess_transform is None:\n input_tensor = image.clone()\n image = image.permute(1, 2, 0).numpy()\n else:\n input_tensor = preprocess_transform(image)\n \n \n if mask is not None:\n input_tensor = input_tensor * mask\n output = model(input_tensor.unsqueeze(0).to(DEVICE))[0].detach().cpu()\n output = output.argmax(axis = 0)\n\n if box is None:\n box = (0, 0, 0, 0)\n rect_image = image.copy()\n rect_image = cv2.rectangle(rect_image, (box[2], box[0]), (box[3], box[1]), 255, 10)\n\n plt.figure()\n plt.subplot(1, 3, 1)\n plt.imshow(image)\n plt.subplot(1, 3, 2)\n plt.imshow(output)\n plt.title('To Explain')\n plt.subplot(1, 3, 3)\n plt.imshow(rect_image)\n if fig_name is not None:\n plt.savefig(fig_name, bbox_inches = 'tight')\n if vis is True:\n plt.show()\n plt.close()\n return image, output, rect_image\n\ndef dice(a, b):\n return 2*(a & b).sum()/(a.sum() + b.sum())\n\ndef generate_masks(n_masks, input_size, p1 = 0.1, initial_mask_size = (7, 7), binary = True):\n # cell size in the upsampled mask\n Ch = np.ceil(input_size[0] / initial_mask_size[0])\n Cw = np.ceil(input_size[1] / initial_mask_size[1])\n\n resize_h = int((initial_mask_size[0] + 1) * Ch)\n resize_w = int((initial_mask_size[1] + 1) * Cw)\n\n masks = []\n\n for _ in range(n_masks):\n # generate binary mask\n binary_mask = torch.randn(\n 1, 1, initial_mask_size[0], initial_mask_size[1])\n binary_mask = (binary_mask < p1).float()\n\n # upsampling mask\n if binary:\n mask = F.interpolate(\n binary_mask, (resize_h, resize_w), mode='nearest')#, align_corners=False)\n else:\n mask = F.interpolate(\n binary_mask, (resize_h, resize_w), mode='bilinear', align_corners=False)\n\n # random cropping\n i = np.random.randint(0, Ch)\n j = np.random.randint(0, Cw)\n mask = mask[:, :, i:i+input_size[0], j:j+input_size[1]]\n\n masks.append(mask)\n\n masks = torch.cat(masks, dim=0) # (N_masks, 1, H, W)\n\n return masks\n\ndef rise_segmentation(masks, image, model, preprocess_transform, target = None, n_masks = None, box = None, DEVICE = 'cpu', vis = True, vis_skip = 1):\n if preprocess_transform is None:\n input_tensor = image.clone()\n image = image.permute(1, 2, 0).numpy()\n else:\n input_tensor = preprocess_transform(image)\n\n \n if box is None:\n y_start, y_end, x_start, x_end = 0, image.shape[0], 0, image.shape[1]\n else:\n y_start, y_end, x_start, x_end = box[0], box[1], box[2], box[3]\n\n coef = []\n\n if n_masks is None:\n n_masks = len(masks)\n\n output = model(input_tensor.unsqueeze(0).to(DEVICE))[0].detach().cpu()\n output_1 = output.argmax(axis = 0)\n output_a = output_1[y_start:y_end, x_start:x_end]\n \n if target is None:\n target = output_a.max().item()\n \n for index, mask in tqdm(enumerate(masks[:n_masks])):\n #input_tensor = preprocess_transform(image)\n #output = model(input_tensor.unsqueeze(0).to(DEVICE))[0].detach().cpu()\n #output_1 = output.argmax(axis = 0)\n\n input_tensor_1 = input_tensor * mask\n output = model(input_tensor_1.unsqueeze(0).to(DEVICE))[0].detach().cpu()\n output_2 = output.argmax(axis = 0)\n \n #output_a = output_1[y_start:y_end, x_start:x_end]\n# if target is None:\n# target = output_a.max().item()\n output_b = output_2[y_start:y_end, x_start:x_end]\n \n DICE = dice(output_a == target, output_b == target)\n coef.append(DICE)\n\n if vis == True:\n if index % vis_skip == 0:\n plt.figure()\n plt.subplot(1, 3, 1)\n plt.imshow(output_1)\n plt.subplot(1, 3, 2)\n plt.imshow(output_2)\n plt.subplot(1, 3, 3)\n plt.imshow(mask[0])\n plt.show()\n return coef\n\ndef rise_aggregated(image, masks, coef, fig_name = None, vis = True):\n aggregated_mask = np.zeros(masks[0][0].shape)\n\n for i, j in zip(masks[:len(coef)], coef):\n aggregated_mask += i[0].detach().cpu().numpy() * j.item()\n\n max_, min_ = aggregated_mask.max(), aggregated_mask.min() \n aggregated_mask = np.uint8(255 * (aggregated_mask - min_) / (max_ - min_))\n overlaid = show_cam_on_image(image/255, aggregated_mask/255, use_rgb=True)\n\n title = 'RISE'\n\n plt.figure()\n plt.subplot(1, 3, 1)\n plt.imshow(image)\n plt.subplot(1, 3, 2)\n plt.imshow(aggregated_mask)\n plt.title(title)\n plt.subplot(1, 3, 3)\n plt.imshow(overlaid)\n if fig_name is not None:\n plt.savefig(fig_name, bbox_inches = 'tight')\n if vis is True:\n plt.show()\n plt.close() \n\n return aggregated_mask, overlaid\n\ndef save_grad(x, gradients):\n x.register_hook(lambda z: gradients.append(z))\n\ndef seg_grad_cam(image, model, preprocess_transform, target = None, target_layer = None, box = None, DEVICE = 'cpu', method_index = 0, fig_base_name = None, fig_name = None, vis_base = True, vis = True, negative_gradient = False, pool_size = None, pool_mode = np.max, reshape_transformer = False):\n if preprocess_transform is None:\n input_tensor = image.clone()\n image = image.permute(1, 2, 0).numpy()\n max_, min_ = image.max(), image.min()\n image = np.uint8(255 * (image - min_) / (max_ - min_))\n\n else:\n input_tensor = preprocess_transform(image)\n\n activations, gradients = [], []\n\n handle_1 = target_layer.register_forward_hook(lambda x, y, z: activations.append(z))\n handle_2 = target_layer.register_forward_hook(lambda x, y, z: save_grad(z, gradients))\n\n model.zero_grad()\n output = model(input_tensor.unsqueeze(0).to(DEVICE))\n\n if box is None:\n y_start, y_end, x_start, x_end = 0, image.shape[0], 0, image.shape[1]\n else:\n y_start, y_end, x_start, x_end = box[0], box[1], box[2], box[3]\n\n if target is None:\n target = output[0].argmax(0).max().item()\n\n mask = output[0].argmax(0).detach().cpu().numpy()\n mask_uint8 = 255 * np.uint8(mask == target)\n mask_float = np.float32(mask == target)\n mask_mask = np.zeros(mask_float.shape)\n mask_mask[y_start:y_end, x_start:x_end] = 1\n mask_float = mask_float * mask_mask\n mask_uint8 = np.uint8(mask_uint8 * mask_mask)\n\n if negative_gradient == True:\n loss = -(output[0, target, :, :] * torch.tensor(mask_float).to(DEVICE)).sum()\n else:\n loss = (output[0, target, :, :] * torch.tensor(mask_float).to(DEVICE)).sum()\n loss.backward()\n\n activations = activations[0][0].detach().cpu().numpy()\n gradients = gradients[0][0].detach().cpu().numpy()\n \n if reshape_transformer == True:\n activations = np.reshape(activations, (14, 14, activations.shape[1]))\n gradients = np.reshape(gradients, (14, 14, gradients.shape[1]))\n activations = np.transpose(activations, (2, 0, 1))\n gradients = np.transpose(gradients, (2, 0, 1))\n \n if method_index == 0:\n coef = gradients.sum(axis = (1, 2))\n coef = coef[:, None, None]\n grayscale_cam = coef * activations\n grayscale_cam = grayscale_cam.sum(axis = 0)\n elif method_index == 1:\n if pool_size is not None:\n pooled = skimage.measure.block_reduce(gradients, (1, pool_size, pool_size), pool_mode)\n pooled = np.transpose(pooled, (1, 2, 0))\n #gradients = cv2.resize(pooled, (gradients.shape[1], gradients.shape[0]), interpolation = cv2.INTER_NEAREST)\n gradients = skimage.transform.resize(pooled, (gradients.shape[1], gradients.shape[2]), order = 0)\n gradients = np.transpose(gradients, (2, 0, 1))\n \n grayscale_cam = gradients * activations\n grayscale_cam = grayscale_cam.sum(axis = 0)\n \n grayscale_cam = np.maximum(grayscale_cam, 0)\n grayscale_cam = cv2.resize(grayscale_cam, (image.shape[1], image.shape[0]))\n max_, min_ = grayscale_cam.max(), grayscale_cam.min() \n grayscale_cam = np.uint8(255 * (grayscale_cam - min_) / (max_ - min_))\n grayscale_cam = grayscale_cam / 255.0\n \n overlaid = show_cam_on_image(image/255, grayscale_cam, use_rgb=True)\n \n title = 'Seg-Grad-CAM' if method_index == 0 else 'Seg-HiResCAM'\n \n plt.figure()\n plt.subplot(1, 2, 1)\n plt.imshow(image)\n plt.subplot(1, 2, 2)\n plt.imshow(np.repeat(mask_uint8[:, :, None], 3, axis=-1))\n\n if fig_base_name is not None:\n plt.savefig(fig_name, bbox_inches = 'tight')\n if vis_base is True:\n plt.show()\n plt.close()\n\n plt.figure()\n plt.subplot(1, 3, 1)\n plt.imshow(image)\n plt.subplot(1, 3, 2)\n plt.imshow(grayscale_cam)\n plt.title(title)\n plt.subplot(1, 3, 3)\n plt.imshow(overlaid)\n \n if fig_name is not None:\n plt.savefig(fig_name, bbox_inches = 'tight')\n if vis is True:\n plt.show()\n plt.close() \n \n handle_1.remove()\n handle_2.remove()\n\n return grayscale_cam, overlaid\n\n\n\ndef utility_dilation(image, model, preprocess_transform, target = None, box = None, DEVICE = 'cpu', vis = True):\n if preprocess_transform is None:\n input_tensor = image.clone()\n image = image.permute(1, 2, 0).numpy()\n max_, min_ = image.max(), image.min()\n image = np.uint8(255 * (image - min_) / (max_ - min_))\n else:\n input_tensor = preprocess_transform(image)\n\n output = model(input_tensor.unsqueeze(0).to(DEVICE))\n\n if box is None:\n y_start, y_end, x_start, x_end = 0, image.shape[0], 0, image.shape[1]\n else:\n y_start, y_end, x_start, x_end = box[0], box[1], box[2], box[3]\n\n if target is None:\n target = output[0].argmax(0).max().item()\n\n mask = output[0].argmax(0).detach().cpu().numpy()\n mask_uint8 = 255 * np.uint8(mask == target)\n mask_float = np.float32(mask == target)\n mask_mask = np.zeros(mask_float.shape)\n mask_mask[y_start:y_end, x_start:x_end] = 1\n mask_float = mask_float * mask_mask\n mask_uint8 = np.uint8(mask_uint8 * mask_mask)\n\n plt.figure()\n plt.subplot(1, 2, 1)\n plt.imshow(image)\n plt.subplot(1, 2, 2)\n plt.imshow(np.repeat(mask_uint8[:, :, None], 3, axis=-1))\n if vis is True:\n plt.show()\n plt.close()\n \n return image, mask_float\n\ndef dc(result, reference, label):\n result = result == label\n reference = reference == label\n #result = np.atleast_1d(result.astype(np.bool))\n #reference = np.atleast_1d(reference.astype(np.bool))\n intersection = np.count_nonzero(result & reference)\n size_i1 = np.count_nonzero(result)\n size_i2 = np.count_nonzero(reference)\n dc = 2. * intersection / float(size_i1 + size_i2)\n return dc\n\ndef dilation(image, model, preprocess_transform, target = None, box = None, DEVICE = 'cpu',\n mask = None, kernel_size = 5, threshold = 0.2, iterations = 100, original_prediction = None, skip_vis = 10):\n dil_mask = mask.copy() \n dil_mask[dil_mask < threshold] = 0\n dil_mask[dil_mask > threshold] = 1\n images, masks = [], []\n kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))\n for i in range(0, iterations):\n dil_mask = cv2.dilate(dil_mask.astype(np.uint8), kernel, iterations = i)\n if image.shape[0] <= 3:\n im = image * dil_mask[None, :, :]\n else:\n im = image * dil_mask[:, :, None]\n if i % skip_vis == 0:\n vis = True\n else:\n vis = False\n im_iter, mask_iter = utility_dilation(image = im, model = model, preprocess_transform = \n preprocess_transform, target = target, box = box, \n DEVICE = DEVICE, vis = vis)\n images.append(im_iter)\n masks.append(mask_iter)\n\n \n if box is None:\n if image.shape[0] <= 3:\n y_start, y_end, x_start, x_end = 0, image.shape[1], 0, image.shape[2]\n else:\n y_start, y_end, x_start, x_end = 0, image.shape[0], 0, image.shape[1]\n else:\n y_start, y_end, x_start, x_end = box[0], box[1], box[2], box[3]\n\n mask_float = np.float32(original_prediction == target)\n mask_mask = np.zeros(mask_float.shape)\n print(y_start, y_end, x_start, x_end)\n mask_mask[y_start:y_end, x_start:x_end] = 1\n mask_float = mask_float * mask_mask\n\n a = []\n for i in masks:\n\n print(dc(mask_float, i, 1))\n a.append(dc(mask_float, i, 1))\n \n plt.figure()\n plt.scatter(range(len(a)), a)\n \n return images, masks, a\n","repo_name":"Nouman97/Seg_XRes_CAM","sub_path":"seg_xres_cam.py","file_name":"seg_xres_cam.py","file_ext":"py","file_size_in_byte":13422,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"30198543760","text":"# uncompyle6 version 3.7.4\n# Python bytecode 3.6 (3379)\n# Decompiled from: Python 3.8.5 (default, Sep 4 2020, 07:30:14) \n# [GCC 7.3.0]\n# Embedded file name: /home/uzair/Desktop/nlp-api/ranking_cvs.py\n# Compiled at: 2021-10-17 06:20:11\n# Size of source mod 2**32: 23560 bytes\nimport os, re, random, numpy as np, pandas as pd\nfrom collections import Counter\nfrom joblib import Parallel, delayed\nimport cv2, PIL, pytesseract\nfrom pdfminer3.pdfpage import PDFPage\nfrom pdfminer3.layout import LAParams, LTTextBox\nfrom pdfminer3.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer3.converter import PDFPageAggregator, TextConverter\nfrom pdf2image import convert_from_path\nfrom datetime import date, datetime\nfrom dateparser.search import search_dates\nfrom matplotlib import pyplot as plt\nplt.rcParams['figure.figsize'] = (50, 50)\nfrom detectron2 import model_zoo\nfrom detectron2.config import get_cfg\nfrom detectron2.engine import DefaultPredictor\nfrom detectron2.data import DatasetCatalog, MetadataCatalog\nfrom detectron2.data.datasets import register_coco_instances\nfrom nltk.corpus import stopwords\nfrom nltk.stem import WordNetLemmatizer\nfrom fuzzywuzzy import fuzz\nfrom constants import *\n\ndef clean_text(raw_text):\n text = ' '.join(raw_text.split())\n unwanted_chars = [\n '\"', \"'\", '‘', '’', '~', '|', '\\n', '\\xa0', '\\x0c']\n for uc in unwanted_chars:\n text = text.replace(uc, ' ')\n\n text = ' '.join(text.split())\n text = text.lower()\n return text\n\n\ndef extract_text_from_image(img):\n try:\n text = pytesseract.image_to_string(img)\n text = clean_text(text)\n return text\n except Exception as e:\n print('Error while Extracting Text from OCR:')\n print('Error:', e)\n\n\ndef pdf_to_imgs(pdf_file_path, img_size=(900, 1200)):\n imgs = convert_from_path(pdf_file_path)\n images = [np.array(img.resize(img_size, PIL.Image.BICUBIC)) for img in imgs]\n return images\n\n\ndef extract_email(text):\n regex = '\\\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\\\.[A-Z|a-z]{2,}\\\\b'\n email = re.findall(regex, text)\n if email:\n return email[0]\n else:\n return\n\n\ndef get_labels(labels_file_path):\n f = open(labels_file_path, 'r')\n labels = f.read().split()\n f.close()\n return labels\n\n\ndef get_detectron_predictor(labels):\n cfg = get_cfg()\n cfg.merge_from_file(model_zoo.get_config_file(model_config_file))\n cfg.MODEL.DEVICE = 'cpu'\n cfg.MODEL.WEIGHTS = model_file\n cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5\n cfg.MODEL.ROI_HEADS.NUM_CLASSES = len(labels)\n predictor = DefaultPredictor(cfg)\n return predictor\n\n\ndef get_model_predictions(images, predictor):\n all_preds = dict()\n for i, img in enumerate(images):\n outputs = predictor(img)\n pred_boxes = outputs['instances'].pred_boxes.to('cpu').tensor.numpy().astype(int)\n pred_classes = outputs['instances'].pred_classes.to('cpu').numpy()\n pred_scores = outputs['instances'].scores.to('cpu').numpy()\n page_preds = dict()\n page_preds['bboxes'] = pred_boxes\n page_preds['classes'] = pred_classes\n page_preds['scores'] = pred_scores\n all_preds[i + 1] = page_preds\n\n return all_preds\n\n\ndef generate_colors(n):\n rgb_values = []\n hex_values = []\n r = int(random.random() * 256)\n g = int(random.random() * 256)\n b = int(random.random() * 256)\n step = 256 / n\n for _ in range(n):\n r += step\n g += step\n b += step\n r = int(r) % 256\n g = int(g) % 256\n b = int(b) % 256\n rgb_values.append((r, g, b))\n\n return rgb_values\n\n\ndef visualize_model_predictions(images, labels, model_predictions, conf_thresh=0.8):\n imgs = []\n cls_colors = generate_colors(len(labels))\n for k, image in enumerate(images):\n curr_img_preds = model_predictions[(k + 1)]\n img = image.copy()\n for pred_box, pred_cls, pred_score in zip(curr_img_preds['bboxes'], curr_img_preds['classes'], curr_img_preds['scores']):\n if pred_score >= conf_thresh:\n pt = (\n pred_box[0] - 5, pred_box[1])\n pt1 = tuple(pred_box[:2])\n pt2 = tuple(pred_box[2:])\n cls = labels[pred_cls]\n color = cls_colors[pred_cls]\n conf = round(pred_score, 3)\n img = cv2.rectangle(img, pt1, pt2, color, 1)\n img = cv2.putText(img, cls + ' ' + str(conf), pt, cv2.FONT_HERSHEY_SIMPLEX, 0.4, color, 1, cv2.LINE_AA)\n\n imgs.append(img)\n\n for i, img in enumerate(imgs):\n (plt.subplot(len(imgs), 1, i + 1), plt.imshow(img, cmap='gray'))\n plt.title('Page ' + str(i + 1))\n\n plt.show()\n\n\ndef get_dates_from_text(text):\n start_date, end_date = (0, 0)\n searched_dates = search_dates(text)\n unneeded_dates_strs = 'today present still on in to from between then before after start end next new day % +'.split()\n required_dates = []\n for dt in searched_dates:\n unneeded_dates_str_present = False\n for uds in unneeded_dates_strs:\n if uds in dt[0]:\n unneeded_dates_str_present = True\n\n if not unneeded_dates_str_present:\n if dt[1] < datetime.today() and dt[1].year > 1950:\n required_dates.append(dt)\n\n present_len = 15\n present_strs = ['present', 'still', 'today']\n present_date = False\n for dt in required_dates:\n dt_text_start_idx = text.index(dt[0])\n dt_text_end_idx = dt_text_start_idx + len(dt[0])\n if dt_text_end_idx < len(text):\n dt_text_next_str = text[dt_text_end_idx:dt_text_end_idx + present_len]\n else:\n dt_text_next_str = text[dt_text_end_idx:]\n for ps in present_strs:\n if ps in dt_text_next_str:\n present_date = True\n\n dates = [dt[1] for dt in required_dates]\n if not dates:\n return\n else:\n start_date = min(dates)\n if present_date:\n end_date = date.today()\n else:\n end_date = max(dates)\n return (start_date, end_date)\n\n\ndef get_experience(images, model_predictions, labels, conf_thresh=0.9):\n exp_idx = labels.index('Experience')\n exp_found = False\n for k in model_predictions:\n if exp_idx in model_predictions[k]['classes']:\n exp_found = True\n\n if not exp_found:\n return\n else:\n imgs = []\n for k, image in enumerate(images):\n curr_img_preds = model_predictions[(k + 1)]\n img = image.copy()\n for pred_box, pred_cls, pred_score in zip(curr_img_preds['bboxes'], curr_img_preds['classes'], curr_img_preds['scores']):\n if pred_cls == exp_idx and pred_score >= conf_thresh:\n img_chunk = image[pred_box[1]:pred_box[3], pred_box[0]:pred_box[2], :]\n imgs.append(img_chunk)\n\n text = ''\n for img in imgs:\n text += pytesseract.image_to_string(img)\n\n text = clean_text(text)\n dates_result = get_dates_from_text(text)\n total_experience_num_months = 0\n if dates_result:\n start_date, end_date = dates_result\n total_experience_num_months = (end_date.year - start_date.year) * 12 + (end_date.month - start_date.month)\n return total_experience_num_months\n\n\ndef get_name(images, model_predictions, labels, conf_thresh=0.5):\n pd_idx = labels.index('Name')\n pd_found = False\n for k in model_predictions:\n if pd_idx in model_predictions[k]['classes']:\n pd_found = True\n\n if not pd_found:\n return\n else:\n imgs, conf_scores = [], []\n for k, image in enumerate(images):\n curr_img_preds = model_predictions[(k + 1)]\n img = image.copy()\n for pred_box, pred_cls, pred_score in zip(curr_img_preds['bboxes'], curr_img_preds['classes'], curr_img_preds['scores']):\n if pred_cls == pd_idx and pred_score >= conf_thresh:\n img_chunk = image[pred_box[1]:pred_box[3], pred_box[0]:pred_box[2], :]\n imgs.append(img_chunk)\n conf_scores.append(pred_score)\n\n img = imgs[np.argmax(conf_scores)]\n text = pytesseract.image_to_string(img)\n name = clean_text(text)\n return name\n\n\ndef get_location(images, model_predictions, labels, conf_thresh=0.5):\n loc_idx = labels.index('Location')\n loc_found = False\n for k in model_predictions:\n if loc_idx in model_predictions[k]['classes']:\n loc_found = True\n\n if not loc_found:\n return\n else:\n imgs, conf_scores = [], []\n for k, image in enumerate(images):\n curr_img_preds = model_predictions[(k + 1)]\n img = image.copy()\n for pred_box, pred_cls, pred_score in zip(curr_img_preds['bboxes'], curr_img_preds['classes'], curr_img_preds['scores']):\n if pred_cls == loc_idx and pred_score >= conf_thresh:\n img_chunk = image[pred_box[1]:pred_box[3], pred_box[0]:pred_box[2], :]\n imgs.append(img_chunk)\n conf_scores.append(pred_score)\n\n img = imgs[np.argmax(conf_scores)]\n text = pytesseract.image_to_string(img)\n location = clean_text(text)\n return location\n\n\ndef get_professional_domain(images, model_predictions, labels, conf_thresh=0.5):\n pd_idx = labels.index('Professional_Domain')\n pd_found = False\n for k in model_predictions:\n if pd_idx in model_predictions[k]['classes']:\n pd_found = True\n\n if not pd_found:\n return\n else:\n imgs, conf_scores = [], []\n for k, image in enumerate(images):\n curr_img_preds = model_predictions[(k + 1)]\n img = image.copy()\n for pred_box, pred_cls, pred_score in zip(curr_img_preds['bboxes'], curr_img_preds['classes'], curr_img_preds['scores']):\n if pred_cls == pd_idx and pred_score >= conf_thresh:\n img_chunk = image[pred_box[1]:pred_box[3], pred_box[0]:pred_box[2], :]\n imgs.append(img_chunk)\n conf_scores.append(pred_score)\n\n img = imgs[np.argmax(conf_scores)]\n text = pytesseract.image_to_string(img)\n professional_domain = clean_text(text)\n return professional_domain\n\n\ndef get_experience_months(experience_string, range_num_months=12):\n if type(experience_string) is str:\n if '-' in experience_string:\n num_years, year_str = experience_string.split()\n years_split = num_years.split('-')\n min_years, max_years = num_years.split('-')\n return int((int(min_years) + int(max_years)) / 2 * range_num_months)\n else:\n num_years, year_str = experience_string.split()\n return int(num_years) * 12\n else:\n if type(experience_string) is int:\n return experience_string * 12\n print(\"Unexpected Type for 'Required experience'\")\n\n\ndef get_string_matching(str1, str2, partial=True):\n if type(str1) is str and type(str2) is str and str1 and str2:\n if partial:\n matching_percentage = round(fuzz.partial_ratio(str1, str2))\n else:\n matching_percentage = round(fuzz.ratio(str1, str2))\n return matching_percentage\n else:\n print('Unexpected Variable type for string Matching')\n return\n\n\ndef get_model_results(predictor, labels, id, email, pdf_file_path, s3_path):\n images = pdf_to_imgs(pdf_file_path, img_size=(900, 1200))\n model_predictions = get_model_predictions(images, predictor)\n experience = get_experience(images, model_predictions, labels, 0.5)\n name = get_name(images, model_predictions, labels, 0.5)\n location = get_location(images, model_predictions, labels, 0.5)\n professional_domain = get_professional_domain(images, model_predictions, labels, 0.5)\n return [\n id, name, email, s3_path, experience, location, professional_domain]\n\n\ndef get_cv_details_df(emails_dict, pdfs_dict, s3_dict, multithreading=False):\n labels = get_labels(model_labels_file)\n predictor = get_detectron_predictor(labels)\n if multithreading:\n predictor_ = [predictor for _ in range(len(pdfs_dict))]\n labels_ = [labels for _ in range(len(pdfs_dict))]\n ids_ = [k for k in emails_dict]\n emails_ = [emails_dict[k] for k in emails_dict]\n pdf_file_paths_ = [pdfs_dict[k] for k in pdfs_dict]\n s3_paths_ = [s3_dict[k] for k in pdfs_dict]\n model_results = Parallel(n_jobs=2, backend='multiprocessing')(map(delayed(get_model_results), predictor_, labels_, ids_, emails_, pdf_file_paths_, s3_paths_))\n cvs_df = pd.DataFrame(model_results, columns=cvs_col_names)\n return cvs_df\n else:\n cvs_df = pd.DataFrame(columns=cvs_col_names)\n for i, k in enumerate(pdfs_dict):\n email = emails_dict[k]\n pdf_file_path = pdfs_dict[k]\n s3_path = s3_dict[k]\n cvs_df.loc[i] = get_model_results(predictor, labels, k, email, pdf_file_path, s3_path)\n\n return cvs_df\n\n\ndef get_cvs_closest_experiences(cvs_df, required_experience_months, experience_range_threshold=12):\n if required_experience_months < 12:\n print('Unexpected Experience Required')\n return\n else:\n cvs_df['Experience Difference'] = np.abs(cvs_df['Total Experience (months)'] - required_experience_months)\n closest_cvs = cvs_df[(cvs_df['Experience Difference'] <= experience_range_threshold)].copy(deep=True)\n closest_cvs.reset_index(drop=True, inplace=True)\n return closest_cvs\n\n\ndef get_closest_location_cvs(cvs_df, location, matching_ratio=80):\n cvs_df['Location Matched'] = cvs_df.apply((lambda cv: get_string_matching(cv['Location'], location)), axis=1) > matching_ratio\n closest_cvs = cvs_df[(cvs_df['Location Matched'] == True)].copy(deep=True)\n closest_cvs.reset_index(drop=True, inplace=True)\n cvs_df.pop('Location Matched')\n return closest_cvs\n\n\ndef get_closest_job_title_cvs(cvs_df, job_title, matching_ratio=80):\n cvs_df['Domain Matched'] = cvs_df.apply((lambda cv: get_string_matching(cv['Domain'], job_title)), axis=1) > matching_ratio\n closest_cvs = cvs_df[(cvs_df['Domain Matched'] == True)].copy(deep=True)\n closest_cvs.reset_index(drop=True, inplace=True)\n cvs_df.pop('Domain Matched')\n return closest_cvs\n\n\ndef preprocess_text(text, remove_stop_words=True, lemmatization=True):\n main_words = re.sub('[^a-zA-Z]', ' ', str(text))\n main_words = main_words.lower().split()\n if remove_stop_words:\n main_words = [w for w in main_words if w not in set(stopwords.words('english'))]\n if lemmatization:\n main_words = [WordNetLemmatizer().lemmatize(w) for w in main_words if len(w) > 1]\n main_words = [w for w in main_words if len(w) > 1]\n return main_words\n\n\ndef get_jd_text(jd):\n jd_text = ''\n jd_text += jd['Industry'] + ' ' if jd['Industry'] is not None else ''\n jd_text += jd['Soft Skills'] + ' ' if jd['Soft Skills'] is not None else ''\n jd_text += jd['Job Title'] + ' ' if jd['Job Title'] is not None else ''\n jd_text += jd['Tools Handling Experience'] + ' ' if jd['Tools Handling Experience'] is not None else ''\n jd_text += jd['Mandatory Requirement'] + ' ' if jd['Mandatory Requirement'] is not None else ''\n jd_text += jd['Certification'] + ' ' if jd['Certification'] is not None else ''\n jd_text += jd['Detailed Job Description'] + ' ' if jd['Detailed Job Description'] is not None else ''\n jd_text = jd_text.replace('\\xa0', ' ')\n jd_words = preprocess_text(jd_text)\n sorted_jd_words = sorted(jd_words)\n jd_words = Counter(sorted_jd_words)\n return jd_words\n\n\ndef get_cv_text(cv):\n cv_text = ''\n cv_text += cv['Domain'] + ' ' if cv['Domain'] is not None else ''\n cv_text += cv['Summary'] + ' ' if cv['Summary'] is not None else ''\n if type(cv['Experience']) is list and len(cv['Experience']) > 0 and type(cv['Experience']) is list and type(cv['Experience'][0]) is dict:\n cv_exp = ''\n for exp in cv['Experience']:\n if 'Designation' in exp:\n cv_exp += exp['Designation'] + ' ' if exp['Designation'] is not None else ''\n else:\n cv_exp += exp['Designation/Organization'] + ' ' if exp['Designation/Organization'] is not None else ''\n cv_exp += exp['Description'] + ' ' if exp['Description'] is not None else ''\n\n cv_text += cv_exp\n else:\n if type(cv['Experience']) is list:\n if len(cv['Experience']) > 0:\n if type(cv['Experience'][0]) is str:\n cv_exp = ' '.join(cv['Experience'])\n cv_text = cv_text.replace('\\xa0', ' ')\n cv_words = preprocess_text(cv_text)\n sorted_cv_words = sorted(cv_words)\n cv_words = Counter(sorted_cv_words)\n return cv_words\n\n\ndef get_jd_cv_similarity(jd_words, cv_words):\n word_count = 0\n for cv_word in cv_words:\n if cv_word in jd_words:\n word_count += cv_words[cv_word]\n\n return word_count\n\n\ndef rank_cvs(jd, cvs_dict, cvs_df, check_location=False, check_job_title=False, check_required_experience_months=False):\n if type(jd) in [dict, pd.Series, pd.DataFrame]:\n jd_text = get_jd_text(jd)\n closest_cvs = cvs_df\n if check_location:\n closest_cvs = get_closest_location_cvs(cvs_df, jd['Location'])\n if check_job_title:\n closest_cvs = get_closest_job_title_cvs(closest_cvs, jd['Job Title'])\n if check_required_experience_months:\n required_experience_months = get_experience_months(jd['Required Experience'])\n closest_cvs = get_cvs_closest_experiences(closest_cvs, required_experience_months)\n sims = []\n for i in range(len(closest_cvs)):\n cv_id = closest_cvs.loc[i].ID\n cv_text = cvs_dict[cv_id]\n word_count = get_jd_cv_similarity(jd_text, cv_text)\n sims.append(word_count)\n\n closest_cvs['Similarity Score'] = sims\n closest_cvs = closest_cvs.sort_values('Similarity Score', ascending=False)\n closest_cvs.reset_index(drop=True, inplace=True)\n closest_cvs.pop('ID')\n return closest_cvs\n else:\n print('Unexpected type for Job Description (JD)')\n return","repo_name":"MuhammadHamzaAhmed/3cixModel","sub_path":"pyFiles/ranking.py","file_name":"ranking.py","file_ext":"py","file_size_in_byte":18355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"73016687524","text":"import zmq\n\n\ncontext = zmq.Context()\nsocket = context.socket(zmq.SUB)\n\nsocket.bind(\"tcp://172.21.5.138:5555\")\n\nsocket.setsockopt_string(zmq.SUBSCRIBE, '')\n\nprint(\"ZMQ Socket (5555) is now listening...\\n\")\n\nwhile(True):\n message = socket.recv().decode(\"utf-8\")\n\n if message:\n print(f\"Recieved {message}\")\n else:\n print(\"No message recieved\")\n\n\n","repo_name":"thinker-bell/CPS-IOT-SYSTEM","sub_path":"Server Setup/BD_ZeroMQ_server(2).py","file_name":"BD_ZeroMQ_server(2).py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"14401443525","text":"import time\r\nstart=time.time()\r\nlongest=0\r\nwhich=0\r\nfor n in range(1,1000000):\r\n counter=0\r\n num=n\r\n while num>1:\r\n if num//2==num/2:\r\n num=num/2\r\n else:\r\n num=3*num+1\r\n counter=counter+1 \r\n if counter>longest:\r\n longest=counter\r\n which=n\r\nprint(which,time.time()-start,\" seconds\")\r\n","repo_name":"Dyonn/Euler_Project","sub_path":"euler14.py","file_name":"euler14.py","file_ext":"py","file_size_in_byte":315,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"41947089253","text":"import tkinter as tk\r\nfrom tkinter import ttk\r\nimport os\r\nfrom tkinter import messagebox as msgbox\r\nimport json\r\nimport glob\r\n\r\nLARGEFONT = (\"Verdana\", 24)\r\n\r\nclass RunTimePage(tk.Frame):\r\n\r\n config_file = ''\r\n \r\n def __init__(self, parent, controller): \r\n \r\n def execute():\r\n if (len(self.targetsListBox.get_children())):\r\n controller.show_testPage()\r\n else:\r\n msgbox.showerror(\"check your files\", \"Please, check the .tdl file and try again.\")\r\n self.controller.show_mainPage()\r\n \r\n style = ttk.Style()\r\n style.configure('CustomButton.TButton', font=('Arial', 19)) \r\n\r\n self.controller = controller\r\n\r\n tk.Frame.__init__(self, parent)\r\n self.grid_columnconfigure(0, weight=1)\r\n \r\n buttonFrame = tk.Frame(self)\r\n\r\n homeButton = ttk.Button(buttonFrame, text =\"Home\",\r\n command = lambda : controller.show_mainPage(), style='CustomButton.TButton')\r\n homeButton.grid(row = 0, column = 0, padx = 10, pady = 10)\r\n \r\n exectueButton = ttk.Button(buttonFrame, text= \"EXECUTE\", command= execute, style='CustomButton.TButton')\r\n exectueButton.grid(row= 0, column= 1, padx= 10, pady= 10)\r\n\r\n buttonFrame.grid(column=0, row= 5, pady= 50)\r\n \r\n servicesLabel = ttk.Label (self, text = \"SERVICES:\")\r\n servicesLabel.grid(row =1, column=0, pady= 50)\r\n\r\n targetsLabel = ttk.Label ( self, text= \"TARGETS:\")\r\n targetsLabel.grid(row = 3, column= 0, pady=10)\r\n\r\n self.servicesListBox = ttk.Treeview(self, height=12, columns=(\"Name\", \"Validity\"), show='headings', padding= 5)\r\n self.servicesListBox.grid(row = 2, column= 0, padx= 15, pady= 2)\r\n \r\n self.targetsListBox = ttk.Treeview(self, height=2, columns=(\"Name\", \"Validity\") , show='headings', padding= 5)\r\n self.targetsListBox.grid(row = 4, column= 0, padx= 15, pady=20)\r\n\r\n\r\n def set_files(self):\r\n if self.config_file == \"\":\r\n msgbox.showerror(\"File config\", \"You need to select a config file.\")\r\n self.controller.show_mainPage()\r\n return\r\n\r\n with open(self.config_file) as json_file:\r\n data = json.load(json_file)\r\n\r\n folder_name = data[\"folder\"]\r\n \r\n self.setColumnsNames(self.servicesListBox)\r\n self.setColumnsNames(self.targetsListBox)\r\n\r\n self.loadListBoxs(folder_name)\r\n\r\n\r\n def loadListBoxs(self, folder_name):\r\n service_list = [file for file in os.listdir(folder_name) if file.endswith(\".sdl\")] \r\n target_list = [file for file in os.listdir(folder_name) if file.endswith(\".tdl\")]\r\n \r\n for file in service_list:\r\n self.servicesListBox.insert('', 'end', text=\"0\", values=(str(file), 'ok!')) #for now, the validity is not implemented, it just shows ok for everyone\r\n for file in target_list:\r\n self.targetsListBox.insert('', 'end', text=\"0\", values=( str(file), 'ok!'))# validity is not implemented yet\r\n\r\n\r\n def setColumnsNames(self, listBox): #This method create headings names, and change text size to be bigger\r\n style1 = ttk.Style()\r\n style1.configure(\"Treeview.Heading\", font=(None, 22), ) #changing heading text size\r\n style1.configure(\"Treeview\", font=(None, 16), rowheight = 20) #changing elements text size\r\n\r\n listBox.column( \"#1\", anchor= \"center\" , width = 400)\r\n listBox.heading(\"#1\", text=\"Name\")\r\n listBox.column( \"#2\", anchor= \"center\", width = 200)\r\n listBox.heading(\"#2\", text=\"Validity\")\r\n\r\n \r\n def check_files_config(self):\r\n if self.config_file == \"\":\r\n msgbox.showerror(\"File config\", \"You need to select a config file.\")\r\n print(\"1\")\r\n self.controller.show_mainPage()\r\n return\r\n\r\n with open(self.config_file) as json_file:\r\n data = json.load(json_file)\r\n\r\n folder_name = data[\"folder\"]\r\n services = [service[\"name_file\"] for service in data[\"services\"]]\r\n\r\n files = glob.glob(f\"{folder_name}/*.sdl\") + glob.glob(f'{folder_name}/*.tdl')\r\n print(files)\r\n\r\n for f in files:\r\n service_name = f.split(\"/\")[-1]\r\n if service_name not in services:\r\n # ERROR\r\n msgbox.showerror(\"check your files\", \"Please, check the files in folder and try again. They are not coherent with the config file.\")\r\n print(\"1\")\r\n self.controller.show_mainPage()\r\n break\r\n","repo_name":"theiari/AdaptiveGUI","sub_path":"RunTimePageClass.py","file_name":"RunTimePageClass.py","file_ext":"py","file_size_in_byte":4605,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"23428386734","text":"# prime.py\n# Ryan Jensen\n# 2019-01-19\n\"\"\"Provide functions to satisfy some curiosity around prime numbers!\"\"\"\n\n#===============================================================================\n# module importation\nimport math\nimport time\n\n#===============================================================================\ndef gen(n,report_gen_time=0):\n \"\"\"Generate the first [n] prime numbers starting at 2.\n \n The second argument [report_gen_time] is optional. If you choose to send a\n value for [report_gen_time], this function will print the amount of time\n (seconds) it takes to generate [report_gen_time] prime numbers.\n \n Returns a tuple:\n ([list_of_prime_numbers],[list_of_generation_times])\"\"\"\n \n i = 2\n primes = []\n primes_found = 0\n time_start = time.time()\n time_last = time_start\n time_per_batch = []\n \n while primes_found < n:\n # assume i is a prime; then try to prove this assumption is wrong.\n i_is_prime = 1\n i_sqrt_floor = math.floor(math.sqrt(i))\n for p in primes:\n if p > i_sqrt_floor:\n i_is_prime = 1\n break\n quotient = i/p\n if int(quotient) == quotient:\n i_is_prime = 0\n break\n \n if i_is_prime:\n primes.append(i)\n primes_found += 1\n if primes_found and primes_found % report_gen_time == 0:\n time_now = time.time()\n time_elapsed = time_now - time_last\n time_per_batch.append(time_elapsed)\n print(\n \"primes_found=\" + str(primes_found)\n + \"\\ttime since last report=\" + str(time_now-time_last))\n time_last = time_now\n \n i += 1\n return (primes,time_per_batch)\n#\n\n \n#===============================================================================\ndef test():\n \"\"\"Run some arbitrary test involving prime numbers.\"\"\"\n # generate some prime numbers\n n = 1e6\n report_gen_time = 1e3\n my_primes = gen(n,report_gen_time)\n # write the prime numbers to a file\n output_file = open('primes.csv','w')\n output_file.write(\"prime\\n\")\n i = 1;\n for p in my_primes:\n output_file.write(str(p) + \"\\n\")\n #print(str(i) + \": \\t\" + str(p))\n i += 1\n output_file.close()\n#\ntest();\n","repo_name":"jensenr30/experiments","sub_path":"python_learning/prime.py","file_name":"prime.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"25602791741","text":"'''Project Euler problem 17: number letter counts\n\nIf the numbers 1 to 5 are written out in words: one, two, three, four, five,\nthen there are 3 + 3 + 5 + 4 + 4 = 19 letters used in total.\n\nIf all the numbers from 1 to 1000 (one thousand) inclusive were written out in words,\nhow many letters would be used?\n\nNOTE: Do not count spaces or hyphens. For example, 342 (three hundred and forty-two)\ncontains 23 letters and 115 (one hundred and fifteen) contains 20 letters.\nThe use of \"and\" when writing out numbers is in compliance with British usage.'''\n\n# Dictionary for looking up words\nenglishNums ={\n 1: 'one',\n 2: 'two',\n 3: 'three',\n 4: 'four',\n 5: 'five',\n 6: 'six',\n 7: 'seven',\n 8: 'eight',\n 9: 'nine',\n 10: 'ten',\n 11: 'eleven',\n 12: 'twelve',\n 13: 'thirteen',\n 14: 'fourteen',\n 15: 'fifteen',\n 16: 'sixteen',\n 17: 'seventeen',\n 18: 'eighteen',\n 19: 'nineteen',\n 20: 'twenty',\n 30: 'thirty',\n 40: 'forty',\n 50: 'fifty',\n 60: 'sixty',\n 70: 'seventy',\n 80: 'eighty',\n 90: 'ninety',\n 1000: 'one thousand'\n }\n \ndef transLetters(n):\n '''Translates integer n into a string of english words, then counts the letters in them'''\n #if it's in the dictionary, just return it\n if n in englishNums:\n return englishNums[n]\n # otherwise break it up into hundreds and tens if it's over 100. Tens component needs further processing\n elif n>=100:\n #if this is a round hundred, just return x hundred\n if n % 100 == 0:\n return englishNums[n//100] + ' hundred'\n else:\n return englishNums[n//100] + ' hundred and ' + transLetters(n % 100)\n # or if it's less than one hundred break it up by tens and ones\n else:\n return englishNums[(n//10)*10] + '-' + englishNums[n % 10]\n\n### testing transLetters\n##print(transLetters(5))\n##print(transLetters(1000))\n##print(transLetters(213))\n##print(transLetters(543))\n##\n\ndef countLetters(n):\n '''counts the letters in a number, ignoring hyphens and spaces'''\n numString = transLetters(n)\n shortString = numString.replace(' ','') #removing spaces\n shorterString = shortString.replace('-','') # removing hyphens\n return len(shorterString)\n\n# main loop, counts total letters in all numbers from 1 to 1 thousand inclusive\nletterSum = 0\nfor i in range(1, 1001):\n letterSum += countLetters(i)\n\nprint(\"Total sum of letters is %s\" % letterSum)\n\n\n###Test Cases\n##print(\"There are %s letters in the phrase '342'\" % countLetters(342))\n###should be 23\n##\n##print(\"There are %s letters in the phrase '115'\" % countLetters(115))\n###should be 20\n","repo_name":"ronniegane/Project-Euler","sub_path":"ProjectEuler_Python/Euler_0017_counting_letters_in_numbers.py","file_name":"Euler_0017_counting_letters_in_numbers.py","file_ext":"py","file_size_in_byte":2639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"70246129445","text":"\nfrom aiogram import Bot, Dispatcher, types, executor\nfrom config import BOT_TOKEN\n\n\nbot = Bot(token=BOT_TOKEN)\ndp = Dispatcher(bot=bot)\n\n\n# checks specified chat\n@dp.message_handler(is_chat_admin=-1001241113577)\nasync def handle_specified(msg: types.Message):\n await msg.answer(\"You are an admin of the specified chat!\")\n\n\n# checks multiple chats\n@dp.message_handler(is_chat_admin=[-1001241113577, -320463906])\nasync def handle_multiple(msg: types.Message):\n await msg.answer(\"You are an admin of multiple chats!\")\n\n\n# checks current chat\n@dp.message_handler(is_chat_admin=True)\nasync def handler3(msg: types.Message):\n await msg.answer(\"You are an admin of the current chat!\")\n\n\nif __name__ == '__main__':\n executor.start_polling(dp)","repo_name":"alyorjon/Aiogram-lesson","sub_path":"AIOGRAM Filters/admin_filter_example.py","file_name":"admin_filter_example.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"40121348684","text":"import argparse\nimport json\n\nfrom flask import Flask, request, jsonify\nfrom flask_cors import CORS\nfrom kafka import KafkaConsumer, KafkaProducer, errors\n\nfrom ace_logger import Logging\n\napp = Flask(__name__)\nCORS(app)\nlogging = Logging()\n\nKAFKA_BROKER_URL = 'broker:9092'\nTRANSACTIONS_TOPIC = 'test.topic'\nconsumer = None\n\n@app.route('/produce', methods=['POST', 'GET'])\ndef produce():\n try:\n logging.info('Sending...')\n data = request.json\n topic = data.pop('topic', None)\n\n if topic is None:\n return 'No topic was given.'\n\n # Producer send data to a topic\n producer = KafkaProducer(\n bootstrap_servers=KAFKA_BROKER_URL,\n value_serializer=lambda value: json.dumps(value).encode(),\n api_version=(0, 10, 1)\n )\n logging.debug('Created producer object.')\n\n if type(topic) is list:\n for t in topic:\n logging.debug(f'Producing to topic `{t}`')\n producer.send(t, value=data)\n producer.flush()\n elif type(topic) is str:\n logging.debug(f'Producing to topic `{topic}`')\n producer.send(topic, value=data)\n producer.flush()\n\n logging.info('Message sent.')\n return 'Sent'\n except Exception as e:\n logging.exeption('Could not produce. Check trace.')\n pass\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-p', '--port', type=int, help='Port Number', default=6061)\n parser.add_argument('--host', type=str, help='Host', default='0.0.0.0')\n\n args = parser.parse_args()\n\n host = args.host\n port = args.port\n\n app.run(host=host, port=port, debug=False)\n","repo_name":"gopiteja/digi","sub_path":"kafka/producer/producer.py","file_name":"producer.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"27985720350","text":"H0_dt = -1.2454e6*q0_dt**2 + 7.4959e3*q0_dt + 9.5970e2;\nH0_dt = CH*H0_dt*(f0/f0)**2;\nH0_ut = -1.2454e6*q0_ut**2 + 7.4959e3*q0_ut + 9.5970e2;\nH0_ut = CH*H0_ut*(f0/f0)**2;\n\nf0=60\nf = np.linspace(30,70,1000); #% Hz\nH_ut = H0_ut*(f/f0)**2;\nH_dt = H0_dt*(f/f0)**2;\n\nQdt = q0_dt*f/f0;\nQut = q0_ut*f/f0;\n\n\n\nflim = np.arange(35,70,5);\nqop = np.linspace(0,q0_ut*flim[-1]/f0,1000); # m3/s\n#qop=np.transpose(qop);\n\n\nHop = np.zeros((len(flim),len(qop)));\n\n\nfor i in range(0,len(flim)):\n q0 = qop/Cq*(f0/flim[i]);\n H0 = -1.2454e6*q0**2 + 7.4959e3*q0 + 9.5970e2;\n Hop[i,:] = CH*H0*(flim[i]/f0)**2;\n #print(i)\n \n\n\nfrom shapely.geometry import LineString,Point,MultiPoint\n\n# Calculo dos pontos de interse��o para delimita��o da regi�o\n#points1=np.zeros((1000,1));\npoints1=[];points2=[];points4=[];points6=[];#points8=[];\n\nfor ind in range(0,999):\n points1.append((qop[ind]*3600,Hop[0,ind]));\n points2.append((Qdt[ind]*3600,H_dt[ind]));#2 e 3 são iguais\n #points3.append((Qdt[ind]*3600,H_dt[ind]));#2 e 3 são iguais\n points4.append((qop[ind]*3600,Hop[-1,ind])); # igual a 5\n #points5.append((qop[ind]*3600,Hop[-1,ind]));\n points6.append((Qut[ind]*3600,H_ut[ind]));\n #points7.append((Qut[ind]*3600,H_ut[ind])); #Igual ao 6\n #points8.append((qop[ind]*3600,Hop[1,ind])); #Igual ao 1\n \nline1=LineString(points1); \nline2=LineString(points2); #igual a line3\nline4=LineString(points4);\nline6=LineString(points6);\n\n\nip=np.zeros((4,2)); \n[ip[0,0],ip[0,1]] = [line2.intersection(line1).x, line2.intersection(line1).y];\n[ip[1,0],ip[1,1]] = [line4.intersection(line2).x, line4.intersection(line2).y];\n[ip[2,0],ip[2,1]] = [line6.intersection(line4).x, line6.intersection(line4).y];\n[ip[3,0],ip[3,1]] = [line6.intersection(line1).x, line6.intersection(line1).y];\n \n\n# Ajuste do polinomio de frequencia maxima 65 Hz\np_35hz = np.polyfit(qop*3600,Hop[0,:],3);\nH_35hz = lambda qk: p_35hz@np.vstack((cumprod_reverse(np.tile(qk,(len(p_35hz)-1,1)),0),np.ones((1,len(qk)))));\nq_35hz = np.linspace(ip[0,0],ip[3,0],100);\n# Ajuste do polinomio de frequencia minima 35 Hz\np_65hz = np.polyfit(qop*3600,Hop[-1,:],3);\nH_65hz = lambda qk: p_65hz@np.vstack((cumprod_reverse(np.tile(qk,(len(p_65hz)-1,1)),0),np.ones((1,len(qk)))));\nq_65hz = np.linspace(ip[1,0],ip[2,0],100);\n# Ajuste do polinomio de Downtrhust\np_dt = np.polyfit(Qdt*3600,H_dt,2);\nH_dt = lambda qk: p_dt@np.vstack((cumprod_reverse(np.tile(qk,(len(p_dt)-1,1)),0),np.ones((1,len(qk)))));\nq_dt = np.linspace(ip[0,0],ip[1,0],100);\n# Ajuste do polinomio de Uptrhust\np_ut = np.polyfit(Qut*3600,H_ut,2);\nH_ut = lambda qk: p_ut@np.vstack((cumprod_reverse(np.tile(qk,(len(p_ut)-1,1)),0),np.ones((1,len(qk)))));\nq_ut = np.linspace(ip[3,0],ip[2,0],100);\n\n# % Constu��o da figura\n# BCS.Envelope.fig = @(aux) plot(q_35hz,H_35hz(q_35hz),':r',q_65hz,H_65hz(q_65hz),':r',q_ut,H_ut(q_ut),':r',q_dt,H_dt(q_dt),':r','LineWidth',2);\n# BCS.Envelope.ip = ip;\n# BCS.Envelope.fBounds = struct('H_35hz',H_35hz,'H_65hz',H_65hz,'H_dt',H_dt,'H_ut',H_ut);\n# % Funa��o para a avalia��o dos limites dada uma vaz�o.\n# BCS.Envelope.Hlim = @(qk) BoundHead(qk*3600,ip,BCS.Envelope.fBounds);\n\n\ndef grafico_envelope(ax):\n ax.plot(q_35hz,H_35hz(q_35hz),':r'); \n ax.plot(q_65hz,H_65hz(q_65hz),':r');\n ax.plot(q_ut,H_ut(q_ut),':r');\n ax.plot(q_dt,H_dt(q_dt),':r');\n ax.set_xlabel(r'$q_p (m^3/h)$')\n ax.set_ylabel('H (m)')\n\n#% Constu��o da figura\n#figBCS=lambda aux: pyplot(q_35hz,H_35hz(q_35hz),':r',q_65hz,H_65hz(q_65hz),':r',q_ut,H_ut(q_ut),':r',q_dt,H_dt(q_dt),':r','LineWidth',2)\nfBounds = {'H_35hz': H_35hz,\n 'H_65hz': H_65hz,\n 'H_dt': H_dt,\n 'H_ut': H_ut}\nBCS['Envelope'] = {'fig': grafico_envelope, #lambda aux: plt.plot(q_35hz,H_35hz(q_35hz),':r',q_65hz,H_65hz(q_65hz),':r',q_ut,H_ut(q_ut),':r',q_dt,H_dt(q_dt),':r','LineWidth',2),\n 'ip': ip,\n 'fbounds': fBounds}\n\n \n \n\n# % Funa��o para a avalia��o dos limites dada uma vaz�o.\nBCS['Envelope']['Hlim']= lambda qk: BoundHead(qk,ip,BCS['Envelope']['fBounds']);\n#\n\n\n#%% Subrotina\ndef BoundHead(qk,ip,bounds):\n if qk < ip[0,0]:\n Hlim = [ip[0,1],ip[0,1]];\n elif qk < ip[1,0]:\n Hlim = [[bounds['H_35hz'][qk]],[bounds['H_dt'][qk]]];\n elif qk < ip[3,0]:\n Hlim = [[bounds['H_35hz'][qk]],[bounds['H_65hz'][qk]]];\n elif qk < ip[2,0]:\n Hlim = [[bounds['H_ut'][qk]],[[bounds['H_65hz'][qk]]]];\n else:\n Hlim = [ip[2,1],ip[2,1]];\n \n return Hlim\n\ndef cumprod_reverse (A,n):\n #Como não havia cumprod reverse no python tivemos que contornar\n if n==0:\n return np.flipud(np.cumprod(np.flipud(A),n));\n elif n==1:\n return np.fliplr(np.cumprod(np.fliplr(A),n));\n else:\n print('Erro em n - cumprod reverse')\n\nprint('Envelope carregado')","repo_name":"tanielfranklin/NMPC_PINN","sub_path":"nmpc/__pycache__/envelope.py","file_name":"envelope.py","file_ext":"py","file_size_in_byte":4827,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"2169878940","text":"import os\nimport numpy as np\nimport PIL.Image as Image\nimport torch\nfrom .base_data import BaseData\nimport pdb\n\n\nclass ImageFolders(BaseData):\n def __init__(self, root, size=256, training=True,\n crop=None, rotate=None, flip=False, mean=None, std=None):\n super(ImageFolders, self).__init__(size=size, crop=crop, rotate=rotate, flip=flip, mean=mean, std=std)\n self.root = root\n self.training = training\n folders = os.listdir(root)\n self.img_filenames = [os.path.join(root, os.path.join(f, n))\n for f in folders for n in os.listdir(os.path.join(root, f))]\n\n def __len__(self):\n return len(self.img_filenames)\n\n def __getitem__(self, index):\n # load image\n img_file = self.img_filenames[index]\n img = Image.open(img_file).convert('RGB')\n if self.crop is not None:\n img, = self.random_crop(img)\n if self.rotate is not None:\n img, = self.random_rotate(img)\n if self.flip:\n img, = self.random_flip(img)\n img = img.resize(self.size)\n img = np.array(img, dtype=np.float64) / 255.0\n if len(img.shape) < 3:\n img = np.stack((img, img, img), 2)\n if img.shape[2] > 3:\n img = img[:, :, :3]\n if self.mean is not None:\n img -= self.mean\n if self.std is not None:\n img /= self.std\n img = img.transpose(2, 0, 1)\n img = torch.from_numpy(img).float()\n return img\n\n\nclass ImageFiles(BaseData):\n def __init__(self, root, size=256, training=True,\n crop=None, rotate=None, flip=False, mean=None, std=None):\n super(ImageFiles, self).__init__(size=size, crop=crop, rotate=rotate, flip=flip, mean=mean, std=std)\n self.root = root\n names = os.listdir(root)\n self.img_filenames = list(map(lambda x: os.path.join(root, x), names))\n names = list(map(lambda x: '.'.join(x.split('.')[:-1]), names))\n self.names = names\n\n def __len__(self):\n return len(self.names)\n\n def __getitem__(self, index):\n # load image\n img_file = self.img_filenames[index]\n img = Image.open(img_file).convert('RGB')\n if self.crop is not None:\n img, = self.random_crop(img)\n if self.rotate is not None:\n img, = self.random_rotate(img)\n if self.flip:\n img, = self.random_flip(img)\n img = img.resize(self.size)\n img = np.array(img, dtype=np.float64) / 255.0\n if len(img.shape) < 3:\n img = np.stack((img, img, img), 2)\n if img.shape[2] > 3:\n img = img[:, :, :3]\n if self.mean is not None:\n img -= self.mean\n if self.std is not None:\n img /= self.std\n img = img.transpose(2, 0, 1)\n img = torch.from_numpy(img).float()\n return img\n\n\nclass ImageNetDetCls(BaseData):\n def __init__(self, pathimg, path_devkit, size=256, training=True,\n crop=None, rotate=None, flip=False, mean=None, std=None):\n super(ImageNetDetCls, self).__init__(size=size, crop=crop, rotate=rotate, flip=flip, mean=mean, std=std)\n self.pathimg = pathimg\n txts = os.listdir(os.path.join(path_devkit, 'data', 'det_lists'))\n txts = filter(lambda x: x.startswith('train_pos') #or x.startswith('train_part')\n , txts)\n file2lbl = {}\n for txt in txts:\n files = open(os.path.join(path_devkit, 'data', 'det_lists', txt)).readlines()\n for f in files:\n f = f.strip('\\n')+'.JPEG'\n if f in file2lbl:\n file2lbl[f] += [int(txt.split('.')[0].split('_')[-1])]\n else:\n file2lbl[f] = [int(txt.split('.')[0].split('_')[-1])]\n list_filenames = []\n labels = []\n\n for filename, lbl in file2lbl.items():\n list_filenames.append(filename)\n onehot = np.zeros(200)\n lbl = np.array(lbl)-1\n onehot[lbl] = 1\n onehot = torch.from_numpy(onehot).float()\n labels.append(onehot)\n labels = torch.stack(labels, 0)\n self.labels = labels\n self.list_filenames = list_filenames\n\n def __len__(self):\n return len(self.list_filenames)\n\n def __getitem__(self, index):\n # load image\n img_file = self.list_filenames[index]\n onehot = self.labels[index]\n img = Image.open(os.path.join(self.pathimg, img_file)).convert('RGB')\n\n if self.crop is not None:\n img, = self.random_crop(img)\n if self.rotate is not None:\n img, = self.random_rotate(img)\n if self.flip:\n img, = self.random_flip(img)\n img = img.resize(self.size)\n\n img = np.array(img, dtype=np.float64) / 255.0\n if len(img.shape) < 3:\n img = np.stack((img, img, img), 2)\n if img.shape[2] > 3:\n img = img[:, :, :3]\n if self.mean is not None:\n img -= self.mean\n if self.std is not None:\n img /= self.std\n img = img.transpose(2, 0, 1)\n img = torch.from_numpy(img).float()\n\n return img, onehot\n\n\nif __name__ == \"__main__\":\n sb = ImageNetDetCls('../../data/datasets/ILSVRC2014_devkit')\n img, gt = sb.__getitem__(0)\n pdb.set_trace()\n","repo_name":"ZHongshuang/mws","sub_path":"datasets/imagenet.py","file_name":"imagenet.py","file_ext":"py","file_size_in_byte":5368,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"24073516064","text":"import random\ndef llenarLista(tam,rango):\n lista=[random.randrange(rango) for i in range(tam)] \n return lista\n\ndef sumaLista(lista):\n sum=0\n for x in lista:\n sum+=x\n return sum\n\ndef promedioLista(lista):\n return sumaLista(lista)/len(lista)\nl1=llenarLista(3,10)\n\ndef mayor_menor (lista):\n mayor = lista[0]\n menor = lista[0]\n for numero in lista:\n if numero > mayor:\n mayor = numero\n if numero < menor:\n menor = numero\n return mayor, menor\nmayor, menor = mayor_menor(l1)\n\ndef calcular_media(lista):\n suma = 0\n for elemento in lista:\n suma += elemento\n media = suma / len(lista)\n return media\n\nmedia = calcular_media(l1)\n\ndef calcular_moda(lista):\n # Crear un diccionario para contar la frecuencia de cada valor en la lista\n frecuencias = {}\n for valor in lista:\n if valor in frecuencias:\n frecuencias[valor] += 1\n else:\n frecuencias[valor] = 1\n\n # Encontrar el valor con la frecuencia máxima\n moda = lista\n max_frecuencia = 0\n for valor, frecuencia in frecuencias.items():\n if frecuencia > max_frecuencia:\n moda = valor\n max_frecuencia = frecuencia\n\n return moda\n\nmoda=calcular_moda(l1)\n\nprint(l1)\nprint(\"la suma de la lista\",sumaLista(l1))\nprint(\"el promedio es\",round(promedioLista(l1),2))\nprint(\"el valor maximo es\",mayor)\nprint(\"el valor minimo\",menor)\nprint(\"La media de la lista es:\", media)\nprint(\"La moda de la lista\", l1, \"es:\", calcular_moda(l1))\n","repo_name":"Diego1229/Gonzalez2693629","sub_path":"tarea/ciclos/funfiones.py","file_name":"funfiones.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"19969436961","text":"from configs.dataset_config import DatasetConfig\nimport librosa as lb\nimport tensorflow as tf\nimport numpy as np\n# print(DatasetConfig.positive_data_path)\n\nclass Preprocess:\n def load_wav_16k_mono(filename):\n wave, sr = lb.load(filename, sr = 16000, mono = True)\n return wave\n\n def get_spectrogram(file_path, label=None): \n wav = Preprocess.load_wav_16k_mono(file_path)\n wav = wav[:48000]\n zero_padding = tf.zeros([48000] - tf.shape(wav), dtype=tf.float32)\n wav = tf.concat([zero_padding, wav],0)\n spectrogram = tf.signal.stft(wav, frame_length=320, frame_step=32)\n spectrogram = tf.abs(spectrogram)\n spectrogram = tf.expand_dims(spectrogram, axis=2)\n # spectrogram = tf.image.resize(spectrogram, [350,50])\n return spectrogram, label\n\n def split_waveform(waveform, frame_size=3, sample_rate=16000):\n # Calculate the number of samples in each frame\n frame_length = frame_size * sample_rate\n\n # Split the waveform into frames\n num_frames = len(waveform) // frame_length\n waveform_frames = np.array_split(waveform[:num_frames * frame_length], num_frames)\n\n return waveform_frames\n\n def wave_to_spectrogram(wav):\n spectrogram = tf.signal.stft(wav, frame_length=320, frame_step=32)\n spectrogram = tf.abs(spectrogram)\n spectrogram = tf.expand_dims(spectrogram, axis=2)\n spectrogram = tf.image.resize(spectrogram, [350,50])\n return spectrogram\n\n def mp3_to_spectrograms(filename):\n wave = Preprocess.load_wav_16k_mono(filename)\n splits = Preprocess.split_waveform(wave, frame_size=3, sample_rate=16000)\n spectrograms = list(map(Preprocess.wave_to_spectrogram, splits))\n return spectrograms","repo_name":"gnbasyal/Count-Bird-Calls-in-an-Audio-Clip","sub_path":"preprocess/preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":1779,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"26326092571","text":"#!/usr/bin/python3\n\nimport argparse\nimport sys\nimport os\nimport subprocess\n\nfrom tempfile import NamedTemporaryFile\nfrom relatorio.templates.opendocument import Template\nfrom datetime import datetime\nfrom dateutil.parser import parse\nfrom Database import *\nfrom pprint import pprint\nfrom pathlib import Path\n\nfrom tempfile import NamedTemporaryFile\n\ndef printf(fmtstr, args):\n sys.stdout.write(fmtstr % tuple(args))\n\ndef invoice(args):\n invoices = []\n # fetch part\n if args.from_date or args.to_date or not args.invoice_no:\n startdate = parse(args.from_date) if args.from_date else parse('01-01-1970')\n enddate = parse(args.to_date) if args.to_date else datetime.now()\n invoices = Invoice.get_inDateRange(startdate, enddate)\n if args.invoice_no:\n invoices = [Invoice.get_byNo(args.invoice_no)]\n\n # action part\n if args.action == 'print':\n create_invoice(args, invoices)\n if args.action == 'list':\n ilist = []\n for i in invoices:\n ilist.append({\n \"Inv. No.\": i.No,\n \"Client Name\": i.client.Name,\n \"Date\": i.InvDate,\n \"Total Sum\": i.Total\n })\n print_table(ilist, ilist[0].keys())\n\ndef print_table(list_of_objects, fields):\n lengths = { f : len(f) for f in fields }\n for o in list_of_objects:\n for f in fields:\n val = str(o[f])\n if len(val) > lengths[f]:\n lengths[f] = len(val)\n\n pattern = \" | \".join([f\"%-{lengths[l]}s\" for l in lengths.keys()])\n pattern = pattern + \"\\n\"\n\n printf(pattern, fields) # print header\n for o in list_of_objects:\n printf(pattern, [o[f] for f in fields])\n\ndef create_invoice(args, invoices):\n for inv in invoices:\n class Obj(object):\n pass\n o = Obj()\n setattr(o, 'invoice', inv)\n setattr(o, 'customer', inv.client)\n\n if args.verbose:\n print(\"Client: \" + o.customer.Name)\n print(\"Invoice: \" + inv.No)\n print(\"Date: \" + inv.InvDate.strftime(\"%d.%m.%Y\"))\n for item in inv.items:\n print(\"%d | %d | %d | %30s\" % (item.Quantity, item.Value, item.Total, item.Title))\n print(\"Grand Total: \" + str(inv.Total))\n\n tpl = Template(source='', filepath=\"invoice_template.odt\")\n generated = tpl.generate(o=o).render()\n temp_odt_file = NamedTemporaryFile(suffix='.odt', delete=True)\n temp_odt_file.write(generated.getvalue())\n subprocess.call(['libreoffice', '--headless', '--convert-to', 'pdf', temp_odt_file.name, '--outdir', 'files'])\n #fname = re.sub(r'.odt$', '', temp_odt_file.name)\n fname = Path(temp_odt_file.name).stem\n os.rename(\"./files/\" + fname + \".pdf\", \"./files/\" + inv.No + \".pdf\")\n temp_odt_file.close()\n\ndef invoice_help():\n print(\"Usage: tim invoice ACTION --invoice-no \")\n print(\"\\tACTION\\n\\t\\tCan be 'print'.\")\n print(\"\\tINVOICE_NO\\n\\t\\tThe invoice number to work on.\")\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--verbose', '-v', action='count', default=0)\nsubparsers = parser.add_subparsers(help='sub-command help')\n\np_invoice = subparsers.add_parser('invoice', aliases=['inv'], help='invoice help')\np_invoice.set_defaults(func=invoice)\np_invoice.add_argument('action')\np_invoice.add_argument('--invoice-no', type=str)\np_invoice.add_argument('--from', dest='from_date', type=str)\np_invoice.add_argument('--to', dest='to_date', type=str)\n\nargs = parser.parse_args()\nif not len(sys.argv) > 1:\n invoice_help()\n exit(0)\nargs.func(args)\n","repo_name":"wullxz/pytim","sub_path":"tim.py","file_name":"tim.py","file_ext":"py","file_size_in_byte":3372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"71155062566","text":"def f(n,k,s): # n: n번 공장에 대해 만들 물건을 결정, k: 전체 공장 수, s: n-1 공장까지 생산 비용 \n global MIN\n if n == k:\n # 모든 결정이 끝나면,\n if MIN > s:\n MIN = s\n elif s >= MIN:\n return\n else:\n for i in range(k): # 아직 결정되지 않은 물건이면,\n if not used[i]:\n used[i] = 1\n f(n+1, k, s+plant[i][n])\n used[i] = 0\n\n\nT = int(input())\nfor t in range(1, T+1):\n N = int(input())\n plant = [ list(map(int, input().split())) for _ in range(N)]\n MIN = float('inf')\n used = [0]*N","repo_name":"chloe-codes1/algorithm","sub_path":"Algorithm-Class/algo2/0515_Backtracking/5209_T.py","file_name":"5209_T.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"8635439197","text":"# Chicken Coop Exercise Solution:\n#\n# Here's my implementation of the Chicken class. Notice the total_eggs class attribute.\n\n\nclass Chicken:\n total_eggs = 0\n\n def __init__(self, name, species):\n self.name = name\n self.species = species\n self.eggs = 0\n\n def lay_egg(self):\n self.eggs += 1\n Chicken.total_eggs += 1\n return self.eggs\n","repo_name":"syurskyi/Python_Topics","sub_path":"070_oop/001_classes/examples/The_Modern_Python_3_Bootcamp/Coding Exercise 79 Chicken Coop Exercise.py","file_name":"Coding Exercise 79 Chicken Coop Exercise.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"39238907640","text":"\"\"\"Pagination helpers.\"\"\"\n\nimport json\n\nfrom flask import current_app as app\n\n\ndef get_pagination_params(request):\n \"\"\"Return pagination params as keyword arguments on the view.\n\n Arguments:\n request -- an instance of flask request\n \"\"\"\n default_per_page = app.config['DEFAULT_PER_PAGE']\n max_per_page = app.config['MAX_PER_PAGE']\n\n page = request.args.get('page')\n per_page = request.args.get('per_page')\n\n page = int(page) if page else 1\n per_page = int(per_page) if per_page else default_per_page\n per_page = min(per_page, max_per_page)\n\n return page, per_page\n\n\ndef paginate(data, page=1, per_page=None):\n \"\"\"Create a paginated response of the given query set.\n\n Arguments:\n data -- A flask_mongoengine.BaseQuerySet instance\n \"\"\"\n per_page = app.config['DEFAULT_PER_PAGE'] if not per_page else per_page\n pagination_obj = data.paginate(page=page, per_page=per_page)\n\n return {\n 'data': build_pagination_data(pagination_obj),\n 'meta': build_pagination_metadata(pagination_obj),\n }\n\n\ndef build_pagination_data(pagination_obj):\n \"\"\"Assemble the pagination data.\"\"\"\n pagination_data = []\n for item in pagination_obj.items:\n pagination_data.append(json.loads(item.to_json()))\n\n return pagination_data\n\n\ndef build_pagination_metadata(pagination_obj):\n \"\"\"Assemble the pagination metadata.\"\"\"\n pagination_metadata = {\n 'current_page': pagination_obj.page,\n 'total_pages': pagination_obj.pages,\n }\n if pagination_obj.has_prev:\n pagination_metadata['previous_page'] = pagination_obj.prev_num\n\n if pagination_obj.has_next:\n pagination_metadata['next_page'] = pagination_obj.next_num\n\n return pagination_metadata\n","repo_name":"italopaiva/goodsongs","sub_path":"goodsongs/pagination.py","file_name":"pagination.py","file_ext":"py","file_size_in_byte":1752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15290819487","text":"'''\r\nProblem statement:\r\nhttps://www.hackerrank.com/challenges/py-set-mutations\r\n'''\r\n\r\n# Enter your code here. Read input from STDIN. Print output to STDOUT\r\nfrom sys import stdin\r\n\r\nn = int(stdin.readline()) #no.of elements\r\n\r\nA = set(map(int,stdin.readline().split())) #set\r\n\r\nn_cmd = int(stdin.readline()) #no.of commands\r\n\r\nfor i in range(n_cmd):\r\n cmd, l = stdin.readline().split()\r\n l = int(l)\r\n temp = set(map(int,stdin.readline().split()))\r\n if(cmd == \"intersection_update\"):\r\n #intersection_update \r\n A.intersection_update(temp)\r\n \r\n elif(cmd == \"update\"):\r\n #update\r\n A.update(temp)\r\n \r\n elif(cmd == \"symmetric_difference_update\"):\r\n #symmetric_difference_update\r\n A.symmetric_difference_update(temp)\r\n\r\n elif(cmd == \"difference_update\"):\r\n #difference_update\r\n A.difference_update(temp)\r\n\r\nprint(sum(A))\r\n","repo_name":"jaikishanEngg/HackerRank_Python_Practice","sub_path":"Set_Mutations.py","file_name":"Set_Mutations.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"9884632340","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Feb 1 13:01:19 2023\n\n@author: Gualandi\n\"\"\"\n\nimport numpy as np\n\ndef GetData():\n X = np.load('X.npy')\n H = np.load('H.npy')\n \n print('X', X.shape)\n # X (15340, 50)\n \n print('H', H.shape)\n # (653, 15340)\n \n for i in range(len(H)):\n C = H[i]/np.min(H[i][np.nonzero(H[i])])\n if C.sum() > 4000:\n print(C.sum())\n \n indices = np.argsort(np.sum(H, axis=0))\n nmax = 4000\n H = H[:,indices[-nmax:]]\n H = np.array(H)\n # Renormalize so that lines sum to 1\n H = H / np.sum(H, axis=1)[:, None]\n # Drop embeddings not used.\n X = X[indices[-nmax:],:]\n \n print(f'{H.shape[0]} texts supported on up to {H.shape[1]} words of dimension {X.shape[1]}')\n \n return H, X\n\nfrom scipy.spatial import distance_matrix\ndef ComputeMatrix(X):\n C = distance_matrix(X, X, 2)\n return C\n \n\nfrom gurobipy import Model, GRB, quicksum, tuplelist\ndef DualOT(A, B, C):\n\n if sum(A) > sum(B):\n A, B = B, A\n \n # Build model\n mod = Model()\n mod.setParam(GRB.Param.OutputFlag, 1)\n # mod.setAttr(GRB.Attr.ModelSense, -1)\n mod.setParam(GRB.Param.Method, 0)\n mod.setParam(GRB.Param.Threads, 1)\n # mod.setParam(GRB.Param.OutputFlag, 1)\n # mod.setParam(GRB.Param.Crossover, 0)\n #mod.setParam(GRB.Param.NumericFocus, 3)\n \n # Create variables\n x = {}\n for i, a in enumerate(A):\n if a > 0:\n for j, b in enumerate(B): \n if b > 0:\n x[i,j] = mod.addVar(obj=C[i,j])\n \n mod.update()\n \n E = tuplelist([(i,j) for (i,j) in x])\n \n # Objective Function\n for i, a in enumerate(A):\n if a > 0:\n mod.addConstr(quicksum(x[i,j] for _,j in E.select(i,'*')) >= a)\n\n for j, b in enumerate(B):\n if b > 0:\n mod.addConstr(quicksum(x[i,j] for i,_ in E.select('*', j)) <= b)\n \n # Train: Solve the model\n mod.optimize()\n\n return mod.getAttr(GRB.Attr.ObjVal), mod.Runtime\n\n#-----------------------------------------------\n# MAIN function\n#-----------------------------------------------\nif __name__ == \"__main__\": \n H, X = GetData()\n \n C = ComputeMatrix(X)\n \n from time import time\n \n start = time()\n \n for i in range(len(H)):\n for j in range(i+1, len(H)):\n print(DualOT(H[0], H[1], C))\n \n end = time()\n\n print(f'It took {end - start} seconds!')\n\n \n \n \n \n ","repo_name":"stegua/dotlib","sub_path":"mpc/python/WordMover_ott.py","file_name":"WordMover_ott.py","file_ext":"py","file_size_in_byte":2514,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"52"} +{"seq_id":"70896817124","text":"# -*- coding: utf-8 -*-\n# @Time : 2019/5/14 6:37 PM\n# @Author : Joli\n# @Email : 99755349@qq.com\n\nimport os\nimport sys\n\n# 添加根目录搜索路径\nsys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))\n# print(sys.path)\n\ndef main():\n import optparse\n parser = optparse.OptionParser(description='make model tool')\n parser.add_option('--src',\n dest='src',\n type='string',\n default=optparse.NO_DEFAULT,\n help='模型路径')\n parser.add_option('--dst',\n dest='dst',\n type='string',\n default=optparse.NO_DEFAULT,\n help='输出路径')\n parser.add_option('--opt',\n dest='opt',\n type='string',\n default=optparse.NO_DEFAULT,\n help='操作类型')\n (options, args) = parser.parse_args(sys.argv[1:])\n\n from scripts import MakeModel\n if options.opt == 'offset':\n offset_x, offset_y = 0, 0\n if args:\n if len(args) > 0:\n if args[0][0] == '0':\n offset_x = -int(args[0][1:])\n else:\n offset_x = int(args[0])\n if len(args) > 1:\n if args[1][0] == '0':\n offset_y = -int(args[1][1:])\n else:\n offset_y = int(args[1])\n MakeModel.offset(options.src, options.dst, offset_x, offset_y)\n else:\n print('unknow opt:', options.opt)\n\nif __name__ == '__main__':\n main()","repo_name":"JoliChen/py-tool","sub_path":"easy2/cl/make_model/CLMakeModel.py","file_name":"CLMakeModel.py","file_ext":"py","file_size_in_byte":1636,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"52"} +{"seq_id":"23157414962","text":"from setuptools import setup, Extension\nfrom torch.utils import cpp_extension\nimport os\n\n##############################################\n#\n# PyTorch bindings to AdaPM\n#\n##############################################\n\n# helpful info on this: https://docs.python.org/3/distutils/setupscript.html\n\npm_dir = '../'\n# we need absolute paths at least for the so-links to protobuf-lite and zmq\npm_dir = os.path.abspath(pm_dir)+'/'\ndeps_dir = pm_dir + 'deps_bindings/'\n\n# include_dirs = cpp_extension.include_paths() # get default include dirs\npm_include_dirs = [pm_dir,\n pm_dir + 'src',\n pm_dir + 'include',\n deps_dir + 'include']\n\nsetup(name='pm',\n version='0.1',\n description='PyTorch bindings to the AdaPM parameter server',\n ext_modules=[cpp_extension.CppExtension(\n name='adapm',\n include_dirs = pm_include_dirs,\n extra_objects = [pm_dir + 'build/libps.a'],\n depends = [pm_dir + 'build/libps.a',\n pm_dir + 'include/ps/addressbook.h',\n pm_dir + 'include/ps/base.h',\n pm_dir + 'include/ps/coloc_kv_server.h',\n pm_dir + 'include/ps/coloc_kv_server_handle.h',\n pm_dir + 'include/ps/coloc_kv_worker.h',\n pm_dir + 'include/ps/kv_app.h',\n pm_dir + 'include/ps/ps.h',\n pm_dir + 'include/ps/sync_manager.h',\n pm_dir + 'include/ps/sampling.h',\n ],\n # The linking we do below in `extra_link_args` would probably be cleaner with\n # `runtime_library_dirs` and `libraries`, but I did not get that to work.\n extra_link_args = ['-Wl,-rpath,'+deps_dir+'lib',\n '-L'+deps_dir+'lib',\n '-lprotobuf-lite',\n '-lzmq'],\n sources=['bindings.cc'],\n extra_compile_args=['-DKEY_TYPE=int64_t'],\n # define_macros=[('NDEBUG', '1')],\n )],\n cmdclass={'build_ext': cpp_extension.BuildExtension})\n\n","repo_name":"anon256/AdaPM","sub_path":"bindings/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":2187,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"1160491501","text":"# Python flask application exposing REST API for system resources\n## Author : Bharath - beeyeas@gmail.com\n\n\nfrom flask import Flask, jsonify, url_for\nimport json\nimport psutil\n\napp = Flask(__name__)\n\n\n@app.route(\"/\", methods=[\"GET\"])\ndef api_landing():\n return jsonify(gaucomole=\"Consume guacomole , stay Happy!!!\")\n\n\n@app.route(\"/v1/cpu\", methods=[\"GET\"])\ndef api_cpu():\n cpu_times = psutil.cpu_times()\n cpu_count = psutil.cpu_count()\n cpu_stats = psutil.cpu_stats()\n # cpu_freq = psutil.cpu_freq(percpu=True)\n cpu_freq = psutil.cpu_freq()\n return jsonify(cpu_freq=cpu_freq._asdict(), cpu_times=cpu_times._asdict(), cpu_stats=cpu_stats._asdict(), cpu_count=cpu_count)\n\n\n@app.route(\"/v1/network\")\ndef api_network():\n net_io_counters = psutil.net_io_counters(pernic=True)\n net_io_value_list = []\n for key, value in net_io_counters.iteritems():\n net_io_value_list.append({key:json.dumps(value._asdict())})\n\n\n net_connections = psutil.net_connections()\n #net_connections_value_list = []\n #for key, value in net_connections.iteritems():\n # net_connections_value_list.append({key:json.dumps(value._asdict())})\n\n return jsonify(net_io_counters=net_io_value_list, net_connections=net_connections)\n\n\n@app.route(\"/v1/memory\")\ndef api_memory():\n virtual_memory = psutil.virtual_memory()\n swap_memory = psutil.swap_memory()\n return jsonify(swap_memory=swap_memory._asdict(), virtual_memory=virtual_memory._asdict())\n\n\n@app.route(\"/v1/disk\")\ndef api_disk():\n disk_partitions = psutil.disk_partitions(all=True)\n disk_usage = psutil.disk_usage('/')\n disk_io_counters = psutil.disk_io_counters(perdisk=True)\n value_list = []\n for key, value in disk_io_counters.iteritems():\n value_list.append({key:json.dumps(value._asdict())})\n\n return jsonify(disk_io_counters=value_list, disk_usage=disk_usage._asdict(), disk_partitions=disk_partitions,)\n\n\ndef processcheck(seekitem):\n plist=psutil.get_process_list()\n str1=\" \".join(str(x) for x in plist)\n if seekitem in str1:\n print (\"Requested process is running\")\n\n\nif __name__ == \"__main__\":\n app.run()\n","repo_name":"beeyeas/guacamole","sub_path":"guacomole.py","file_name":"guacomole.py","file_ext":"py","file_size_in_byte":2137,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"40164547220","text":"\"\"\"migrate_message\n\nRevision ID: 38ffb379f09d\nRevises: c0afbae9a926\nCreate Date: 2021-02-03 22:24:50.993714\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '38ffb379f09d'\ndown_revision = 'c0afbae9a926'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.create_foreign_key(None, 'messages', 'employees', ['sender_id'], ['id'])\n op.create_foreign_key(None, 'messages', 'employees', ['recipient_id'], ['id'])\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'messages', type_='foreignkey')\n op.drop_constraint(None, 'messages', type_='foreignkey')\n # ### end Alembic commands ###\n","repo_name":"RedPowDan/ProjectNIT","sub_path":"db/migrations/versions/38ffb379f09d_migrate_message.py","file_name":"38ffb379f09d_migrate_message.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"42321160660","text":"import os\nfrom os.path import isdir , isfile , join\n\nimport numpy as np\nimport astropy as ap\n\nfrom astropy.io import fits\n\n\n\nif __name__ == '__main__':\n\t\n\t# getting all directories in current working dir\n\twd = './refactor/'\n\tast_names = [wd + f + '/' for f in os.listdir (wd) if isdir(join(wd,f))]\n\n\tstar_params = np.loadtxt ('star_parameters.csv', skiprows=1 , dtype=str, delimiter=',')\n\t# print(star_params[:,0])\n\tcmd_list = []\n\tfor a in ast_names : \n\t\t# if '00_m_16' in d or 'small_asteroid_lightcurve_CFHT_data' in d: continue\n\n\t\tdir_names = [a + f for f in os.listdir(a) if isdir(join(a,f))]\n\t\t\n\n\t\tfor d in dir_names:\n\n\t\t\tfile_names = [join(d,f) for f in os.listdir (d) if isfile(join(d,f))]\n\n\t\t\tfor f in file_names :\n\t\t\t# only working on new files around asteroid chip\n\t\t\t\tif not 'on' in f: continue\n\t\t\t\t# if not ( 'EL157' in f or 'FF14' in f or 'GE1' in f or 'EN156' in f): continue\n\n\t\t\t\ttry:\n\t\t\t\t\tfile = fits.open (f)\n\t\t\t\t\tprint( f'{f} is a fits file')\n\t\t\t\texcept Exception as e:\n\t\t\t\t\tprint( f'{f} is not a fits file' )\n\t\t\t\t\tcontinue\n\n\t\t\t\tL = 0 \n\t\t\t\ta = 0\n\t\t\t\toid = f.split('_')[1]\n\t\t\t\t# print(oid)\n\t\t\t\tfor i in range(len(star_params)):\n\t\t\t\t\tif oid in star_params[i,0]: \n\t\t\t\t\t\tL = star_params[i,1]\n\t\t\t\t\t\ta = star_params[i,2]\n\t\t\t\t\t\tbreak\n\n\t\t\t\tcommand = f'\\n{f[:]}'\n\t\t\t\tprint(command)\n\t\t\t\tcmd_list.append(command)\n\t\t\n\t# for i in cmd_list: print(i)\n\t# output = open('ast_files.txt', 'w+')\n\toutput = open('fits_files_all_chips1.txt', 'w+')\n\toutput.writelines( cmd_list )\n\n\n\n","repo_name":"mehulghosal/lightcurves-refactor","sub_path":"get_fits.py","file_name":"get_fits.py","file_ext":"py","file_size_in_byte":1479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"35756100078","text":"# Solution 1 - (내 풀이)\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\nclass Solution:\n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n \n if not head : \n return head\n \n nodes = deque()\n \n while head is not None :\n nodes.append(head.val)\n head = head.next\n \n \n nodes = sorted(nodes, reverse=True)\n result = node = ListNode(nodes.pop())\n \n while nodes:\n node.next = ListNode(nodes.pop())\n node = node.next \n \n return result \n\n\n# 풀이 : 연결리스트의 노드들을 리스트에 따로 저장하고, 노드들이 담긴 리스트를 정렬하여 연결리스트로 바꾼다.\n# 후기 : 이 방식보다는 병합정렬 방식의 풀이가 더 적절해보인다. 병합 정렬 풀이는 책을 참고하였다. \n\n# Solution 2 (책 풀이)\nclass Solution:\n # 두 정렬 리스트 병합 \n def mergeTwoLists(self, l1 : ListNode, l2 : ListNode) -> ListNode: \n if l1 and l2 :\n if l1.val > l2.val : \n l1, l2 = l2, l1 # 큰 값이 l2로 오도록 swap\n l1.next = self.mergeTwoLists(l1.next, l2)\n\n return l1 or l2 \n \n def sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:\n if not (head and head.next) : \n return head\n \n # 런너 기법 (fast는 next 2개씩, slow는 next 1개씩, half는 slow의 이전 값)\n half, slow, fast = None, head, head\n while fast and fast.next :\n half, slow, fast = slow, slow.next, fast.next.next\n half.next = None # half를 기준으로 연결 리스트를 끊어버린다. \n \n \n\n # 분할 재귀 호출 \n l1 = self.sortList(head)\n l2 = self.sortList(slow)\n\n return self.mergeTwoLists(l1,l2)\n\n# 흐름 : sortlist에서 런너 기법으로 연결리스트를 반으로 자른다. 이때 재귀호출을 통해 분할 재귀 호출 형태를 띄고, \n# 마지막에 mergeTwoLists를 호출하여 쪼갰던 아이템을 크기 비교를 통해 정렬하면서 이어붙인다.\n\n# - 런너 기법 : (fast는 next 2개씩, slow는 next 1개씩, half는 slow의 이전 값)\n# - 구조 : head(시작) -------- half(slow이전) - slow (중앙) ---------fast(끝)\n\n\n","repo_name":"HyeM207/Algorithm","sub_path":"LeetCode/[LeetCode] 148. Sort List.py","file_name":"[LeetCode] 148. Sort List.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"34030257949","text":"import requests\r\n\r\n################ url_web_service\r\n\r\nurl_web_service = \"http://156.35.86.6:8080/shexer\"\r\n# url_web_service = \"http://localhost/shexer\"\r\n\r\n\r\n\r\n################ namespace\r\n\r\n# This ones are inclided by default:\r\n\r\n# default_namespaces = {\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\": \"rdf\",\r\n# \"http://www.w3.org/2000/01/rdf-schema#\": \"rdfs\",\r\n# \"http://www.w3.org/2001/XMLSchema#\": \"xml\",\r\n# \"http://www.w3.org/XML/1998/namespace/\": \"xml\",\r\n# \"http://www.w3.org/2002/07/owl#\": \"owl\",\r\n#\r\n# }\r\n\r\nnew_namespaces = {\r\n \"http://wikiba.se/ontology#\": \"wikibase\",\r\n \"http://www.bigdata.com/rdf#\": \"bd\",\r\n \"http://www.wikidata.org/entity/\": \"wd\",\r\n \"http://www.wikidata.org/prop/direct/\": \"wdt\",\r\n \"http://www.wikidata.org/prop/direct-normalized/\": \"wdtn\",\r\n \"http://www.wikidata.org/entity/statement/\": \"wds\",\r\n \"http://www.wikidata.org/prop/\": \"p\",\r\n \"http://www.wikidata.org/reference/\": \"wdref\",\r\n \"http://www.wikidata.org/value/\": \"wdv\",\r\n \"http://www.wikidata.org/prop/statement/\": \"ps\",\r\n \"http://www.wikidata.org/prop/statement/value/\": \"psv\",\r\n \"http://www.wikidata.org/prop/statement/value-normalized/\": \"psn\",\r\n \"http://www.wikidata.org/prop/qualifier/\": \"pq\",\r\n \"http://www.wikidata.org/prop/qualifier/value/\": \"pqv\",\r\n \"http://www.wikidata.org/prop/qualifier/value-normalized/\": \"pqn\",\r\n \"http://www.wikidata.org/prop/reference/\": \"pr\",\r\n \"http://www.wikidata.org/prop/reference/value/\": \"prv\",\r\n \"http://www.wikidata.org/prop/reference/value-normalized/\": \"prn\",\r\n \"http://www.wikidata.org/prop/novalue/\": \"wdno\"\r\n}\r\n\r\n\r\n\r\n################ PARAM NAMES AND DOC\r\n\r\nTARGET_CLASSES_PARAM = \"target_classes\"\r\n\"\"\"\r\nList of strings: List of target classes to associate a shape with\r\n\"\"\"\r\n\r\nTARGET_GRAPH_PARAM = \"raw_graph\"\r\n\"\"\"\r\nString: RDF content to be analyzed\r\n\"\"\"\r\n\r\nINPUT_FORMAT_PARAM = \"input_format\"\r\n\"\"\"\r\nString: RDF syntax used. Ntriples is used by default Accepted values -->\r\n\r\n\"nt\" (n-triples)\r\n\"turtle\" (turtle)\r\n\"xml\" (RDF/XML)\r\n\"n3\" (n3)\r\n\"json-ld\" (JSON LD)\r\n\"tsv_spo\" (lines with subject predicate and object separated by tab '\\\\t' chars \r\n\"\"\"\r\n\r\n\r\nINSTANTIATION_PROPERTY_PARAM = \"instantiation_prop\"\r\n\"\"\"\r\nString: property used to links an instance with its class. rdf:type by default.\r\n\"\"\"\r\n\r\n\r\nNAMESPACES_TO_IGNORE_PARAM = \"ignore\"\r\n\"\"\"\r\nList of Strings: List of namespaces whose properties should be ignored during the shexing process.\r\n\"\"\"\r\n\r\nINFER_NUMERIC_TYPES_PARAM = \"infer_untyped_nums\"\r\n\"\"\"\r\nBool: default, True. If True, it tries to infer the numeric type (xsd:int, xsd:float..) of \r\nuntyped numeric literals \r\n\"\"\"\r\n\r\nDISCARD_USELESS_CONSTRAINTS_PARAM = \"discard_useless_constraints\"\r\n\"\"\"\r\nBool: default, True. default, True. If True, it keeps just the most possible specific constraint w.r.t. cardinality \r\n\"\"\"\r\n\r\nALL_INSTANCES_COMPLIANT_PARAM = \"all_compliant\"\r\n\"\"\"\r\nBool: default, True. default, True. If False, the shapes produced may not be compliant with all the entities considered\r\nto build them. This is because it won't use Kleene closeres for any constraint. \r\n\"\"\"\r\n\r\nKEEP_LESS_SPECIFIC_PARAM = \"keep_less_specific\"\r\n\"\"\"\r\nBool: default, True. It prefers to use \"+\" closures rather than exact cardinalities in the triple constraints\r\n\"\"\"\r\n\r\nACEPTANCE_THRESHOLD_PARAM = \"threshold\"\r\n\"\"\"\r\nFloat: number in [0,1] that indicates the minimum proportion of entities that should have a given feature for this\r\nto be accepted as a triple constraint in the produced shape.\r\n\"\"\"\r\n\r\nALL_CLASSES_MODE_PARAM = \"all_classes\"\r\n\"\"\"\r\nBool: default, False. If True, it generates a shape for every elements with at least an instance \r\nin the considered graph.\r\n\"\"\"\r\nSHAPE_MAP_PARAM = \"shape_map\"\r\n\"\"\"\r\nString: shape map to associate nodes with shapes. It uses the same syntax of validation shape maps. \r\n\"\"\"\r\n\r\nREMOTE_GRAPH_PARAM = \"graph_url\"\r\n\"\"\"\r\nString: URL to retrieve an online raw graph.\r\n\"\"\"\r\n\r\nENDPOINT_GRAPH_PARAM = \"endpoint\"\r\n\"\"\"\r\nString: URL of an SPARQL endpoint.\r\n\"\"\"\r\n\r\nNAMESPACES_PARAM = \"prefixes\"\r\n\"\"\"\r\nDict. key are namespaces and values are prefixes. The pairs key value provided here will be used \r\nto parse the RDF content and t write the resulting shapes.\r\n\"\"\"\r\n\r\nQUERY_DEPTH_PARAM = \"query_depth\"\r\n\"\"\"\r\nInteger: default, 1. It indicates the depth to generate queries when targeting a SPARQL endpoint.\r\nCurrently it can be 1 or 2.\r\n\"\"\"\r\n\r\nDISABLE_COMMENTS_PARAM = \"disable_comments\"\r\n\"\"\"\r\nBool: default, False. When set to True, the shapes do not include comment \r\nwith ratio of entities compliant with a triple constraint\r\n\"\"\"\r\n\r\nQUALIFIER_NAMESPACES_PARAM = \"namespaces_for_qualifiers\"\r\n\"\"\"\r\nList. Default, None. When a list with elements is provided, the properties in the namespaces specified are considered\r\nto be pointers to qualifier nodes.\r\n\"\"\"\r\n\r\nSHAPE_QUALIFIERS_MODE_PARAM = \"shape_qualifiers_mode\"\r\n\"\"\"\r\nBool: default, False. When set to true, a shape is generated for those nodes detected as qualifiers according to\r\nWikidata data model and the properties pointing to them specified in QUALIFIER_NAMESPACES_PARAM\r\n\"\"\"\r\n\r\n\r\n\r\n############ Param definition for a use case\r\n\r\nshape_map = \"SPARQL'SELECT DISTINCT ?virus WHERE { VALUES ?virus { wd:Q82069695 } }'@ \" # wd:Q16983360 wd:Q16991954 wd:Q8351095 wd:Q16983356 wd:Q4902157 wd:Q278567\r\n\r\n\r\nparams = {NAMESPACES_PARAM: new_namespaces,\r\n SHAPE_MAP_PARAM: shape_map,\r\n ENDPOINT_GRAPH_PARAM: \"https://query.wikidata.org/sparql\",\r\n ALL_CLASSES_MODE_PARAM: False,\r\n QUERY_DEPTH_PARAM: 2,\r\n ACEPTANCE_THRESHOLD_PARAM: 0,\r\n INSTANTIATION_PROPERTY_PARAM: \"http://www.wikidata.org/prop/direct/P31\",\r\n DISABLE_COMMENTS_PARAM: True,\r\n SHAPE_QUALIFIERS_MODE_PARAM: True,\r\n QUALIFIER_NAMESPACES_PARAM: [\"http://www.wikidata.org/prop/\"]\r\n\r\n }\r\n\r\n############ Calling web service\r\n\r\nr = requests.post(url=url_web_service, json=params)\r\n\r\n\r\ndata = r.json()\r\nprint(data[\"result\"])\r\nprint(\"Done!\")","repo_name":"lubianat/complex_bot","sub_path":"complex_venv/lib/python3.7/site-packages/local_code/consume_ws.py","file_name":"consume_ws.py","file_ext":"py","file_size_in_byte":6078,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"52"} +{"seq_id":"42203284770","text":"import sys\ns=input()\nflag=True\nif s==\"0\" or s==\"1\":\n\tprint(0)\n\tsys.exit()\nif s==\"10\" or s==\"11\" or s==\"100\":\n\tprint(1)\n\tsys.exit(0)\n\nif s[0]==\"1\":\n\tc=0\n\tfor i in s[1:]:\n\t\t# print(i)\n\t\tc+=1\n\t\tif i!=\"0\":\n\t\t\tflag=False\n\t\t\tbreak\n\t# print(c)\n\tif c%2!=0 and flag:\n\t\tflag=False\nelse:\n\tflag=False\n# print(flag)\nif flag:\n\tprint((len(s)-1)//2)\nelse:\n\tprint((len(s)-1)//2+1)","repo_name":"vishwesh-D-kumar/codeforces_submissions","sub_path":"1204/a/59158027.py","file_name":"59158027.py","file_ext":"py","file_size_in_byte":363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"11926942116","text":"\"\"\"\nTODO:\n\"\"\"\n\n__author__ = \"James Cook\"\n__copyright__ = \"Copyright (C) 2021 James Cook\"\n__license__ = \"GNU General Public License v3\"\n__version__ = \"1.0.0\"\n__maintainer__ = \"James Cook\"\n__email__ = \"contact@cookjames.uk\"\n\nimport pythoncom\nimport win32com.client\nimport datetime as dt\n\n\nclass Appointment:\n def __init__(self,\n subject,\n date,\n start_time,\n end_time,\n organiser):\n self.subject = subject\n self.date = date\n self.start_time = start_time\n self.end_time = end_time\n self.organiser = organiser\n\n\nclass Calendar:\n\n def __init__(self):\n pass\n\n def get_calendar_appointments(self, start_days=0, days=14):\n \"\"\"\n Get appointment details over the next X days in the future.\n \"\"\"\n assert (days > 0)\n\n # setup outlook connection\n pythoncom.CoInitialize()\n Outlook = win32com.client.Dispatch(\"Outlook.Application\")\n pythoncom.CoInitialize()\n ns = Outlook.GetNamespace(\"MAPI\")\n\n # get appointments\n appts = ns.GetDefaultFolder(9).Items\n appts.Sort(\"[Start]\")\n appts\n appts.IncludeRecurrences = True\n\n # set time restriction\n today = dt.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0) + dt.timedelta(days=start_days)\n last_day = dt.timedelta(days=days) + today\n begin = today.date().strftime(\"%d/%m/%Y\")\n end = last_day.date().strftime(\"%d/%m/%Y\")\n restriction = \"[Start] >= '\" + begin + \"' AND [End] <= '\" + end + \"'\"\n appts = appts.Restrict(restriction)\n\n # put results into custom object\n return self._create_appointment_object(appts)\n\n def create_appointment(self, subject, start, duration_mins):\n pythoncom.CoInitialize()\n Outlook = win32com.client.Dispatch(\"Outlook.Application\")\n pythoncom.CoInitialize()\n appt = Outlook.CreateItem(1) # AppointmentItem\n appt.Start = start #\"10/06/2021 23:50\" # dd/mm/YYYY hh:mm\n appt.Subject = subject\n appt.Duration = duration_mins # In minutes (60 Minutes)\n appt.MeetingStatus = 1 # 1 - olMeeting; Changing the appointment to meeting. Only after changing the meeting status recipients can be added\n #appt.Recipients.Add(\"test@test.com\") # Don't end ; as delimiter\n appt.Save()\n #appt.Send()\n\n def _create_appointment_object(self, appts):\n \"\"\"\n Creates Appointment objects for each appt in a list\n of appts from the Outlook client API.\n \"\"\"\n appointments = []\n for a in appts:\n appointments.append(\n Appointment(\n subject=a.Subject,\n date=dt.datetime.strptime(str(a.Start)[:-6], '%Y-%m-%d %H:%M:%S'),\n start_time=str(a.Start).replace(\"+00:00\", \"\").split(\" \")[1][:-3],\n end_time=str(a.End).replace(\"+00:00\", \"\").split(\" \")[1][:-3],\n organiser=a.Organizer))\n\n return appointments\n\n\nif __name__ == \"__main__\":\n print(\"---- running module test -----\")\n cal = Calendar()\n #cal.create_appointment(subject=\"TESTER\", start=\"10/06/2021 23:50\", duration_mins=5)\n appts = cal.get_calendar_appointments(1)\n\n for a in appts:\n print(a.subject)\n #print(a.date.strftime(\"%d/%m/%Y\"))\n #print(a.start_time)\n #print(a.end_time)\n #print(a.organiser)","repo_name":"dev-chip/heads_up","sub_path":"core/calendar.py","file_name":"calendar.py","file_ext":"py","file_size_in_byte":3492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37012281479","text":"import numpy as np\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom rank_bm25 import BM25Okapi\nimport os\nimport operator\nfrom multiprocessing import Pool,Lock \n#data \nqueries = {}\nwith open('./norm_q.txt') as fin:\n lines = fin.readlines()\n for line in lines:\n line = line[:-1].split('\\t')\n if line[0] == '':\n line.pop(0)\n queries[line[0]] = line[1]\n\n titles= {}\nwith open(\"./norm_tits.txt\" ,'r', encoding='utf-8') as fin:\n for line in fin.readlines():\n line=line.split('\\t')\n titles[line[0]]= line[1][:-1]\n\ntrain=[]\ntrain_titles = []\ntrain_queries = []\ntrq = set()\nwith open(\"./train.marks.tsv/train.marks.tsv\", 'r') as fin:\n for line in fin.readlines():\n line=line[:-1].split('\\t')\n if line[1] in titles.keys():\n train.append([line[0],line[1], line[2]])\n train_titles.append([line[1], titles[line[1]]])\n if line[0] not in trq:\n train_queries.append([line[0], queries[line[0]]])\n trq.add(line[0])\n\n \ntest=[]\ntest_titles = []\ntest_queries = []\nteq = set()\nwith open(\"./sample.csv/sample.csv\", 'r') as fin:\n fin.readline()\n for line in fin.readlines():\n line=line[:-1].split(',')\n if line[1] in titles.keys():\n test.append([line[0],line[1],-1])\n test_titles.append([line[1], titles[line[1]]])\n if line[0] not in teq:\n test_queries.append([line[0], queries[line[0]]])\n teq.add(line[0])\n\nalq = list(train) + list(test)\ndctqs = {}\nfor q, t, n in alq:\n if q not in dctqs.keys():\n dctqs[q] = []\n dctqs[q].append(t)\nalqueries = train_queries + test_queries\nid_q = {}\nfor el in alqueries:\n id_q[el[0]] = el[1] \n\naltits = {}\nfor el in train_titles + test_titles:\n altits[el[0]] = el[1]\ndef cos(sp1,sp2):\n sp1 = sp1.todense()\n sp2 = sp2.todense()\n try:\n res = np.float64(np.dot(sp1,sp2.T)/np.linalg.norm(sp1)/np.linalg.norm(sp2))\n except:\n res = None\n return res\ntry:\n os.mkdir('./ttfsim')\nexcept:\n n = None\ndef ptfidfsim(q):\n global dctqs\n global id_q\n global altits\n tf = TfidfVectorizer(analyzer = 'char', ngram_range=(3,9))\n raw = {}\n for doc in dctqs[q]:\n try:\n raw[doc] = altits[doc]\n except:\n continue\n raw['-1'] = id_q[q]\n vecs = tf.fit_transform(raw.values())\n with open('./ttfsim/{}.txt'.format(q),'w') as fout:\n for i,outdoc in enumerate(raw.keys()):\n if outdoc != '-1':\n fout.write(str(outdoc)+ '\\t'+str(cos(vecs[i],vecs[-1])) + '\\n')\n return\n\ndef pLtfidfsim(q):\n global dctqs\n global id_q\n global altits\n tf = TfidfVectorizer(analyzer = 'char', ngram_range=(1,3))\n raw = {}\n for doc in dctqs[q]:\n try:\n raw[doc] = altits[doc]\n except:\n continue\n raw['-1'] = id_q[q]\n vecs = tf.fit_transform(raw.values())\n with open('./ttfsim/{}.txt'.format(q),'w') as fout:\n for i,outdoc in enumerate(raw.keys()):\n if outdoc != '-1':\n fout.write(str(outdoc)+ '\\t'+str(cos(vecs[i],vecs[-1])) + '\\n')\n return\n\np = Pool(64)\nresults = p.map(ptfidfsim,[q for q,t in alqueries if str(q) + '.txt' not in os.listdir('./ttfsim')])\n\n","repo_name":"eles13/Technosphere-final-ranking-project","sub_path":"scripts/pttfsim_titles.py","file_name":"pttfsim_titles.py","file_ext":"py","file_size_in_byte":3327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"22022017154","text":"from aiogram import Bot, Dispatcher, types\nfrom aiogram.utils.exceptions import MessageNotModified\n\nfrom loader import bot, db\nfrom app import buttons\n\n\nasync def callback_get_group_settings(c: types.CallbackQuery):\n\tuser_id = c.from_user.id\n\tgroup_id = c.data[9:]\n\tgroup_name = db.get_data_from_group_id(group_id)[2]\n\n\tawait c.answer()\n\tawait c.message.edit_text(f\"{group_name} guruxining sozlamalari:\", \n\t\treply_markup = buttons.show_group_settings(\n\t\t\tgroup_id = group_id, \n\t\t\tstatus_remind = db.get_data_from_group_id(group_id)[5]))\n\n\nasync def callback_change_rstatus(c: types.CallbackQuery):\n\tuser_id = c.from_user.id\n\tgroup_id = c.data[15:]\n\tgroup_name = db.get_data_from_group_id(group_id)[2]\n\n\tif db.get_data_from_group_id(group_id)[5] == '🟢':\n\t\tdb.update_rStatus(group_id, '🔴')\n\t\tawait c.answer(\"O'chdi\")\n\telse:\n\t\tdb.update_rStatus(group_id, '🟢')\n\t\tawait c.answer(\"Yondi\")\n\n\tawait c.message.edit_text(f\"{group_name} guruxining sozlamalari:\", \n\t\treply_markup = buttons.show_group_settings(\n\t\t\tgroup_id = group_id, \n\t\t\tstatus_remind = db.get_data_from_group_id(group_id)[5]))\n\n\nasync def callback_show_audios(c: types.CallbackQuery):\n\tawait c.answer()\n\tgroup_id = c.data[12:]\n\tawait c.message.edit_text(\"Azon ovozlarining ro'yhati:\",\n\t\treply_markup = buttons.show_audios(group_id))\n\n\nasync def callback_show_list_of_countries(c: types.CallbackQuery):\n\tawait c.answer()\n\tgroup_id = c.data[15:]\n\tawait c.message.edit_text(\"Mintaqalar ro'yhati:\",\n\t\treply_markup = buttons.show_countries(group_id))\n\n\nasync def callback_set_location(c: types.CallbackQuery):\n\tawait c.answer()\n\tids = c.data[13:].split(',')\n\tgroup_id = ids[1]\n\tcountry_name = ids[0]\n\tdb.set_location(group_id, country_name)\n\n\tawait c.message.edit_text(\"Mintaqalar ro'yhati:\",\n\t\treply_markup = buttons.show_countries(group_id))\n\n\n# Back callbacks\nasync def callback_back_to_settings(c: types.CallbackQuery):\n\tuser_id = c.from_user.id\n\tgroup_id = c.data[17:]\n\tgroup_name = db.get_data_from_group_id(group_id)[2]\n\t\n\tawait c.answer()\n\tawait c.message.edit_text(f\"{group_name} guruxining sozlamalari:\", \n\t\treply_markup = buttons.show_group_settings(\n\t\t\tgroup_id = group_id, \n\t\t\tstatus_remind = db.get_data_from_group_id(group_id)[5]))\n\n\nasync def callback_back_to_dashboard(c: types.CallbackQuery):\n\tuser_id = c.from_user.id\n\n\tawait c.answer()\n\tawait c.message.edit_text(\"Sizning guruxlaringiz ro'yhati\", \n\t\treply_markup = buttons.show_dashboard(user_id))\n\n\ndef register_callback_handlers(dp: Dispatcher):\n\tdp.register_callback_query_handler(callback_get_group_settings, lambda c: c.data.startswith('group_id'), state = '*')\n\tdp.register_callback_query_handler(callback_change_rstatus, lambda c: c.data.startswith('change_rStatus'), state = '*')\n\tdp.register_callback_query_handler(callback_show_audios, lambda c: c.data.startswith('show_audios'), state = '*')\n\tdp.register_callback_query_handler(callback_show_list_of_countries, lambda c: c.data.startswith('show_countries'), state = '*')\n\n\tdp.register_callback_query_handler(callback_set_location, lambda c: c.data.startswith('set_location'), state = '*')\n\t\n\tdp.register_callback_query_handler(callback_back_to_settings, lambda c: c.data.startswith(\"back_to_settings\"), state = '*')\n\tdp.register_callback_query_handler(callback_back_to_dashboard, lambda c: c.data == \"back_to_dashboard\", state = '*')\n","repo_name":"KarimovMurodilla/IslamReminderBot","sub_path":"app/handlers/callbacks.py","file_name":"callbacks.py","file_ext":"py","file_size_in_byte":3347,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"15087482385","text":"# Simple (Selection) Sort v1\r\n\r\n# 1. Initialise an unsorted list\r\naList = [9, 6, 10, 4, 8, 5, 7]\r\n# 2. Initialise a marker\r\nmarker = 0 \r\n\r\n# 3. Traverse through all list items\r\nwhile marker < len(aList):\r\n # 4. Find the minimum element to the right of the marker\r\n index_of_min = marker\r\n for j in range(marker+1, len(aList)): \r\n if aList[index_of_min] > aList[j]: \r\n index_of_min = j\r\n\r\n # 5. Exchange the smallest item with the item at the marker\r\n temp = aList[marker] # save the item at the marker\r\n aList[marker] = aList[index_of_min] # copy 1\r\n aList[index_of_min] = temp # copy 2\r\n \r\n # 6. Advance the marker to the right by 1 position\r\n marker = marker+1\r\n\r\n# 7. Stop\r\n\r\nprint(marker, aList)\r\n\r\n'''\r\n# aList = [9, 8, 7, 6, 5, 4, 3]\r\naList = [3, 4, 5, 6, 7, 8, 9]\r\n'''","repo_name":"pdst-lccs/algorithms","sub_path":"selection1_Pg87.py","file_name":"selection1_Pg87.py","file_ext":"py","file_size_in_byte":823,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"14082059742","text":"import socket\r\nimport sys\r\nimport random\r\nimport threading\r\nimport time\r\nimport struct\r\n\r\nimport os\r\nfrom datetime import datetime\r\n\r\n\r\n\r\nclass RepeatedTimer(object):\r\n def __init__(self, interval, function, *args, **kwargs):\r\n self._timer = None\r\n self.interval = interval\r\n self.function = function\r\n self.args = args\r\n self.kwargs = kwargs\r\n self.is_running = False\r\n self.next_call = time.time()\r\n self.start()\r\n\r\n def _run(self):\r\n self.is_running = False\r\n self.start()\r\n self.function(*self.args, **self.kwargs)\r\n\r\n def start(self):\r\n if not self.is_running:\r\n self.next_call += self.interval\r\n self._timer = threading.Timer(self.next_call - time.time(), self._run)\r\n self._timer.start()\r\n self.is_running = True\r\n\r\n def stop(self):\r\n self._timer.cancel()\r\n self.is_running = False\r\n\r\n#Creacion archivos\r\nfile1 = open(\"hearbeat_server.txt\", \"a\")\r\nfile1.close()\r\nfile2 = open(\"registro_server.txt\", \"a\")\r\nfile2.close()\r\n\r\n# Crear un socket TCP/IP\r\nsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nserver_address = ('headnode', 5000)#Definir una address\r\nprint ('Partiendo en el ip %s puerto %s' % server_address)\r\nsock.bind(server_address)# Unir el socket al puerto 5000\r\n# Escuchar mensajes\r\nsock.listen(1)\r\ndef run_check():\r\n timer = datetime.now()\r\n actual = time.strftime(\"%Y-%m-%d %H:%M:%S\")\r\n multisock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n multisock.settimeout(0.2)\r\n ttl = struct.pack('b', 1)\r\n multisock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl)\r\n multicast = ('224.1.1.1', 5003)\r\n mensaje=\"Operativo?\"\r\n try:\r\n # Envío de mensaje al grupo multicast\r\n sent = multisock.sendto(mensaje.encode('utf-8'), multicast)\r\n x=0\r\n while True:\r\n try:\r\n data, server = multisock.recvfrom(1024)\r\n\r\n except socket.timeout:\r\n break\r\n else:\r\n print(data.decode(\"utf-8\") + \"\\n\")#Heartbeat_register\r\n file1 = open(\"hearbeat_server.txt\", \"a\")\r\n file1.write('[Estado '+actual+' ] '+str(data)+'\\n')\r\n file1.close()\r\n finally:\r\n multisock.close()\r\n\r\nt=RepeatedTimer(5, run_check)\r\n\r\n### Conexion cliente ###\r\nwhile True:\r\n # Esperar una conexion\r\n print ( 'Esperando una conexion')\r\n connection, client_address = sock.accept()\r\n try:\r\n print ('Conexion desde', str(client_address[0]))\r\n connection.sendall(\"Estas conectado con headnode\".encode('utf-8'))\r\n #Recibe mensajes hasta que no hayan mas\r\n data = connection.recv(1024)\r\n print ('recibido %s' % data)\r\n\r\n if data:\r\n r = random.randint(1,3)\r\n datanode_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n datanode_address=('datanode'+str(r),5001)\r\n datanode_sock.connect(datanode_address)\r\n\r\n file = open(\"registro_server.txt\", \"a\")\r\n file.write('El cliente '+str(client_address[0])+' envio el mensaje:\\n '+str(data)+'\\n que fue guardado en el datanode'+str(r)+'\\n \\n')\r\n file.close()\r\n\r\n mensaje = 'El mensaje recibido de '+str(client_address[0])+' fue '+str(data)+'que fue guardado en el datanode'+str(r)+'\\n'\r\n connection.sendall(mensaje.encode('utf-8'))\r\n\r\n data2=datanode_sock.recv(1024)\r\n if data2:\r\n connection.sendall(mensaje.encode('utf-8'))\r\n print('Recibido {!r}'.format(data2))\r\n else:\r\n print ('no hay mas mensajes', client_address)\r\n break\r\n finally:\r\n file1 = open(\"hearbeat_server.txt\", \"a\")\r\n file1.write('\\n')\r\n file1.close()\r\n # Cierra la conexion.\r\n print(\"Cerrando conexion...\\n\\n\")\r\n connection.close()\r\n t.stop()\r\n #break\r\n","repo_name":"Fran-Ramirez/Tarea1-INF343","sub_path":"Actividad2/headnode/headnode.py","file_name":"headnode.py","file_ext":"py","file_size_in_byte":3894,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"31010974869","text":"import numpy as np\nfrom kmeans import pairwise_dist\n\nclass DBSCAN(object):\n \n def __init__(self, eps, minPts, dataset):\n self.eps = eps\n self.minPts = minPts\n self.dataset = dataset\n \n def fit(self):\n \"\"\"Fits DBSCAN to dataset and hyperparameters defined in init().\n Args:\n None\n Return:\n cluster_idx: (N, ) int numpy array of assignment of clusters for each point in dataset\n Hint: Using sets for visitedIndices may be helpful here.\n Iterate through the dataset sequentially and keep track of your points' cluster assignments.\n If a point is unvisited or is a noise point (has fewer than the minimum number of neighbor points), then its cluster assignment should be -1.\n Set the first cluster as C = 0\n \"\"\"\n cluster_idx = np.zeros(len(self.dataset)) - 1\n visited_indices = set()\n C = -1\n #neighbor_indices = [0, 2, 5, 8]\n for Pidx in range(len(self.dataset)):\n if Pidx not in visited_indices:\n visited_indices.add(Pidx)\n neighborPts = self.regionQuery(Pidx)\n if len(neighborPts) < self.minPts:\n cluster_idx[Pidx] = -1\n else:\n C += 1\n self.expandCluster(Pidx, neighborPts, C, cluster_idx, visited_indices)\n\n return np.array(cluster_idx)\n\n # raise NotImplementedError\n\n def expandCluster(self, index, neighborIndices, C, cluster_idx, visitedIndices):\n \"\"\"Expands cluster C using the point P, its neighbors, and any points density-reachable to P and updates indices visited, cluster assignments accordingly\n HINT: regionQuery could be used in your implementation\n Args:\n index: index of point P in dataset (self.dataset)\n neighborIndices: (N, ) int numpy array, indices of all points witin P's eps-neighborhood\n C: current cluster as an int\n cluster_idx: (N, ) int numpy array of current assignment of clusters for each point in dataset\n visitedIndices: set of indices in dataset visited so far\n Return:\n None\n Hints: \n np.concatenate(), np.unique(), np.sort(), and np.take() may be helpful here\n A while loop may be better than a for loop\n \"\"\"\n cluster_idx[index] = C # add P to cluster C\n \n PPrimeIdex = 0\n while PPrimeIdex < len(neighborIndices): # for each P' in neighbor points\n if neighborIndices[PPrimeIdex] not in visitedIndices: # if P' is not visited\n visitedIndices.add(neighborIndices[PPrimeIdex]) # mark P' as visited\n neighborPrimeIndices = self.regionQuery(neighborIndices[PPrimeIdex])\n if len(neighborPrimeIndices) >= self.minPts:\n neighborIndices = np.concatenate((neighborIndices, neighborPrimeIndices), axis = 0)\n _, orderidx = np.unique(neighborIndices, return_index=True)\n neighborIndices = neighborIndices[np.sort(orderidx)]\n if cluster_idx[neighborIndices[PPrimeIdex]] < 0:\n cluster_idx[neighborIndices[PPrimeIdex]] = C\n PPrimeIdex += 1\n # raise NotImplementedError\n \n def regionQuery(self, pointIndex):\n \"\"\"Returns all points within P's eps-neighborhood (including P)\n\n Args:\n pointIndex: index of point P in dataset (self.dataset)\n Return:\n indices: (I, ) int numpy array containing the indices of all points within P's eps-neighborhood\n Hint: pairwise_dist (implemented above) and np.argwhere may be helpful here\n \"\"\"\n return np.argwhere(pairwise_dist(np.array([self.dataset[pointIndex]]), self.dataset)<=self.eps)[:,1]\n\n # raise NotImplementedError","repo_name":"JiayingLi0803/CS7641MachineLearning","sub_path":"HW2/hw2_code/dbscan.py","file_name":"dbscan.py","file_ext":"py","file_size_in_byte":3867,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"12121875575","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\n\n# 图表列表\ndef chart_list(request):\n return render(request,'chart\\chart_list.html')\n\n# 图表 柱状图数据\ndef chart_bar(request):\n legend = [\"张三\",\"李四\"]\n series_list = [\n {\n \"name\": \"张三\",\n \"type\": \"bar\",\n \"data\": [15,20,36,10,10,100]\n },\n {\n \"name\": \"李四\",\n \"type\": \"bar\",\n \"data\": [45,10,66,40,20,10]\n }\n ]\n x_axis = [\"1月\",\"2月\",\"3月\",\"4月\",\"5月\",\"6月\",\"7月\"]\n \n result = {\n \"status\": True,\n \"data\": {\n 'legend': legend,\n 'series_list': series_list,\n 'x_axis': x_axis\n }\n }\n return JsonResponse(result)","repo_name":"houxiaoqiu/django","sub_path":"djsite/app/views/chart.py","file_name":"chart.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"37016130962","text":"n,k = input().split()\nn = int(n)\nk = int(k)\ncount = 0\nwhile n>0:\n t = int(input())\n n = n-1\n if t%k==0:\n count = count +1\nprint(count)\n","repo_name":"luciferChaudhary/CodeChef_beg","sub_path":"Enormous Input Test.py","file_name":"Enormous Input Test.py","file_ext":"py","file_size_in_byte":151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"18617798039","text":"from padding_data import padding_all\n\nfrom unet_model import set_model\nfrom data_generator import trainGenerator, testGenerator\n\nfrom keras.callbacks import TensorBoard, ModelCheckpoint\n\norig_path = \"data/train/original_retinal_images/\"\nnew_orig_path = \"data/train/new_original_retinal_images/\"\n\nhard_path = \"data/train/masks_Hard_Exudates/\"\nnew_hard_path = \"data/train/new_masks_Hard_Exudates/\"\n\n#padding original img\npadding_all(orig_path,new_orig_path)\n# padding hard img\npadding_all(hard_path,new_hard_path)\n\n\nbatch_size =2\ntrain_path = \"data/train\"\nimage_folder =\"new_original_retinal_images\"\nmask_folder = \"new_masks_Hard_Exudates\"\naug_dict = dict(rotation_range=0.2,\n width_shift_range=0.05,\n height_shift_range=0.05,\n shear_range=0.05,\n zoom_range=0.05,\n horizontal_flip=True,\n fill_mode='nearest')\n\ntrain_data = trainGenerator(batch_size,train_path,image_folder,mask_folder,aug_dict)\n\n\n#############################################################\n##### This is the first model\n#############################################################\nmodel = set_model((512,512,1))\nmodel_checkpoint = ModelCheckpoint('vessel_unet.hdf5', monitor='loss', verbose=1, save_best_only=True, mode='min')\nmodel.fit_generator(train_data, steps_per_epoch=500, epochs=5, # shuffle=True,\n callbacks=[TensorBoard(log_dir='./unetres'), model_checkpoint])\n######################################################################################################################\n","repo_name":"ccctyk/Retinal-lesions-and-Blood-vessel-segmentation-","sub_path":"LesionSegmentation/U-Net/train_hard.py","file_name":"train_hard.py","file_ext":"py","file_size_in_byte":1591,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"52"} +{"seq_id":"36574788040","text":"from abc import ABC\n\nfrom infracalc.aws.amazon_rds_storage import AmazonRDSStorage\nfrom infracalc.aws.aws_resource import AWSResource\nfrom infracalc.const import HOURS_IN_A_MONTH\n\n\nclass AmazonRDS(AWSResource, ABC):\n def __init__(self, region):\n super(AmazonRDS, self).__init__(\"AmazonRDS\", \"Database Instance\", \"OnDemand\", region)\n\n def default_attributes(self):\n return [\n {\n 'Type': 'TERM_MATCH',\n 'Field': 'termType',\n 'Value': self.term_type\n }\n ]\n\n def price_info(self, attrs):\n name = attrs.pop(\"name\")\n amount = attrs.pop(\"amount\")\n storage = attrs.pop(\"storage\")\n storage[\"name\"] = name\n attrs.pop(\"service\")\n db = self.get_pricing(attrs, amount, HOURS_IN_A_MONTH, name)\n storage = AmazonRDSStorage(self.region).price_info(storage)\n return [db, storage]\n","repo_name":"cortiz/infra-calc","sub_path":"infracalc/aws/amazon_rds.py","file_name":"amazon_rds.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"3654718683","text":"import random\nimport asyncio\nimport logging\nfrom aiogram.contrib.fsm_storage.memory import MemoryStorage\nfrom aiogram.utils.deep_linking import get_start_link\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.dispatcher.filters.state import State, StatesGroup\nfrom aiogram.types import ReplyKeyboardRemove, \\\n ReplyKeyboardMarkup, KeyboardButton, \\\n InlineKeyboardMarkup, InlineKeyboardButton\nfrom urllib.parse import urlparse, parse_qs\n\nfrom aiogram import Bot, Dispatcher, executor\nfrom aiogram import types\nimport abilities\nimport histories\nimport pandas as pd\nimport os.path\nimport string\nimport csv\nimport re\n\nlogging.basicConfig(level=logging.INFO)\n\nbot = Bot('')\n\n\nstorage = MemoryStorage()\n\ndp = Dispatcher(bot, storage=storage)\ncsv_file = 'bot_members.csv'\ncsv_file_for_text = 'room_text.csv'\ncolumns = ['Full Name', 'Chat ID']\ncolumns_for_text = ['Chat ID', 'Text']\n\nif not os.path.isfile(csv_file):\n df = pd.DataFrame(columns=columns)\n df.to_csv(csv_file, index=False)\n\nif not os.path.isfile(csv_file_for_text):\n df = pd.DataFrame(columns=columns_for_text)\n df.to_csv(csv_file_for_text, index=False)\n@dp.message_handler(commands=\"sta1rt\")\nasync def start(message: types.Message):\n print(message.get_args())\n\n keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\n buttons = [\n \"Cтворити кімнату\",\n \"Приєднатися до кімнати\",\n ]\n keyboard.add(*buttons)\n\n await bot.send_message(\n message.chat.id,\n \"Вітаємо, {0.first_name}!\\nСтвори або долучись до ігрової кімнати, аби почати гру\\n \".format(message.from_user),\n parse_mode='html',\n reply_markup=keyboard\n )\n\n@dp.message_handler(text='Приєднатися до кімнати')\nasync def room(message):\n with open(csv_file, 'r') as file:\n csv_reader = csv.DictReader(file)\n room_ids = set(row['Room ID'] for row in csv_reader)\n\n # Create inline buttons for each unique Room ID\n inline_keyboard = types.InlineKeyboardMarkup(row_width=2)\n for room_id in room_ids:\n inline_keyboard.add(types.InlineKeyboardButton(room_id, callback_data=f\"join_room_{room_id}\"))\n\n await bot.send_message(\n message.chat.id,\n \"Оберіть кімнату для приєднання:\",\n reply_markup=inline_keyboard\n )\n\n@dp.callback_query_handler(lambda query: query.data.startswith('join_room_'))\nasync def join_room_callback(query: types.CallbackQuery):\n room_id = query.data.split('_')[2] # Extract the room ID from the callback data\n user_chat_id = query.message.chat.id\n\n\n df = pd.read_csv(csv_file)\n df.loc[df['Chat ID'] == user_chat_id, 'Room ID'] = room_id\n df.to_csv(csv_file, index=False)\n\n keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\n buttons = [\n \"👤Персона\",\n \"🌋Історія\",\n \"🛖Бункер\",\n \"📖Правила\",\n \"⚙️\"\n ]\n keyboard.add(*buttons)\n\n await bot.send_message(\n query.message.chat.id,\n f\"You have joined room {room_id}.\",\n reply_markup=keyboard\n )\n\n\n\n@dp.message_handler(text='Cтворити кімнату')\nasync def room(message):\n df = pd.read_csv(csv_file)\n user_chat_id = message.chat.id\n user_full_name = message.from_user.full_name\n\n random_room = ''.join(random.choice(string.ascii_uppercase + string.digits) for _ in range(5))\n\n if user_chat_id in df['Chat ID'].values:\n df.loc[df['Chat ID'] == user_chat_id, 'Full Name'] = user_full_name\n else:\n new_row = pd.DataFrame([[user_full_name, user_chat_id]], columns=columns)\n df = pd.concat([df, new_row], ignore_index=True)\n\n df.loc[df['Chat ID'] == user_chat_id, 'Room ID'] = random_room\n df.to_csv(csv_file, index=False)\n await bot.send_message(message.chat.id, random_room)\n keyboard1 = types.ReplyKeyboardMarkup(resize_keyboard=True)\n buttons = [\n \"👤Персона\",\n \"🌋Історія\",\n \"🛖Бункер\",\n \"📖Правила\",\n \"⚙️\"\n ]\n keyboard1.add(*buttons)\n await bot.send_message(\n message.chat.id,\n \"Вітаємо, {0.first_name}!\\nСкоро розпочнеться гра. Сподіваємось у тебе \"\n \"вийде потрапити в бункер\\n Номер твоєї ігрової кімнати: ❇️{1}❇️ \".format(message.from_user, random_room),\n parse_mode='html',\n reply_markup=keyboard1\n )\n\n@dp.message_handler(text='⚙️')\nasync def room(message):\n keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\n buttons = [\n \"Cтворити кімнату\",\n \"Приєднатися до кімнати\",\n ]\n keyboard.add(*buttons)\n\n await bot.send_message(\n message.chat.id,\n \"Вітаємо, {0.first_name}!\\nСтвори або долучись до ігрової кімнати, аби почати гру\\n \".format(message.from_user),\n parse_mode='html',\n reply_markup=keyboard\n )\n\n@dp.message_handler(commands=['send_link'])\nasync def send_link_message(message: types.Message):\n # Create the link\n link_text = \"Click here\"\n link_url = \"https://t.me/Bunker_beta_bot?start=share6\"\n link = f\"[{link_text}]({link_url})\"\n\n # Create the message with the link\n text_message = f\"Please {link} for more information.\"\n\n # Send the message\n await message.answer(text_message, parse_mode=types.ParseMode.MARKDOWN)\n\n@dp.message_handler(text='🛖Бункер')\nasync def bunker(message):\n locate = [\"Анкара, Туреччина\", \"Москва, Росія\", \"Лондон, Британія \", \"Київ, Україна\", \"Жмеринка, Україна\",\n \"Тегусігальпа, Гондурас\", \"Вашингтон, США\", \"Абу-Дабі, ОАЕ\", \"Баку, Азербайджан\",\n \"Брюсель, Бельгія\",\n \"Бухарест, Румунія\", \"Делі, Індія\", \"Мінськ, Білорусія\", \"Самбір, Україна\", \"Париж, Франція\",\n \"Берлін, Німеччина\", \"Варшава, Польща\"]\n\n vorog = [\"Далеко\", \"1 км\", \"5 км\", \"10 км\", \"20 км\", \"50 км\", \"100 км\", \"500 м\", \"Невідомо\"]\n v = \"Бункер №\" + str(random.randint(0, 999)) + \"\\n\" + \"Місцезнаходження: \" + str(random.choice(locate))\\\n + \"\\n\" + \"Розмір: \" + str(random.randint(30, 800)) + \"m²\" + \"\\n\" + \"Їжі достатньо на: \" \\\n + str(random.randint(1, 52)) + \" міс.\" + \"\\n\" + \"До ворожого бункера: \" + str(random.choice(vorog) \\\n + \"\\n\" + \"Час який треба пробути в бункері: \" + str(random.randint(36, 600)) + \" міс.\")\n await bot.send_message(message.chat.id, v)\n@dp.message_handler(text='👤Персона')\n@dp.throttled(lambda message, loop, *args, **kwargs: loop.create_task(bot.send_message(message.from_user.id, \"❌ Ви можете створити персонажа один раз на 10 хвилин\")),rate=10*60)\nasync def person(message):\n df = pd.read_csv(csv_file)\n\n loading = [\"👫Обираємо стать\", \"🗄Готуємо професію\", \"💊Лікуємо здоров'я\", \"🧳Набираємо багаж\", \"📝Навчаємо освіти\", \"🃏Роздаємо картки дії\"]\n upload_message = await bot.send_message(chat_id=message.chat.id, text=\"🫀Cтворюємо персонажа\")\n await asyncio.sleep(1)\n for i in loading:\n await upload_message.edit_text(text=f\"{i}\")\n await asyncio.sleep(0.5)\n await asyncio.sleep(0.5)\n await bot.delete_message(chat_id=message.chat.id, message_id=upload_message.message_id)\n age = random.randint(16, 95)\n childweights = (0, 0)\n if age < 30:\n childweights = (8, 1)\n elif age < 35:\n childweights = (5, 1)\n elif age < 40:\n childweights = (2, 1)\n elif age < 50:\n childweights = (1, 1)\n elif age < 60:\n childweights = (1, 3)\n elif age < 70:\n childweights = (1, 5)\n elif age < 100:\n childweights = (1, 8)\n global stat\n global ages\n random_sex = str(\"Стать: \") + str(random.choice(abilities.sex))\n random_age = str(\"Вік: \") + str(age) + str(\" р.\")\n random_profession = str(\"Професія: \") + str(random.choice(abilities.profesion))\n random_childability = str(\"Здатність мати дітей: \") + str(*random.choices(abilities.childability, weights=childweights))\n random_childdesire = str(\"Бажання мати дітей: \") + str(*random.choices(abilities.childfree, weights=(3, 1)))\n random_health = str(\"Здоров'я: \") + str(*random.choices(abilities.health, weights=abilities.healthweights))\n random_disability = str(\"Інвалідність: \") + str(*random.choices(abilities.disability, weights=abilities.disabilityweights))\n random_phobia = str(\"Фобія: \") + str(random.choice(abilities.phobia))\n random_hobby = str(\"Гобі: \") + str(random.choice(abilities.hobby))\n random_education = str(\"Друга освіта: \") + str(*random.choices(abilities.education, weights=abilities.educationweights))\n random_inventory = str(\"Багаж: \") + str(random.choice(abilities.inventory))\n random_nature = str(\"Характер: \") + str(random.choice(abilities.nature))\n random_religion = str(\"Релігія: \") + str(*random.choices(abilities.religion, weights=abilities.religionweights))\n random_addinfo = str(\"Дод. інфо: \") + str(random.choice(abilities.addinfo))\n random_mom = str(\"Мати: \") + str(random.choice(abilities.profesion))\n random_dad = str(\"Батько: \") + str(random.choice(abilities.profesion))\n random_action1 = str(\"🃏Карта дії №1:\\n \") + str(random.choice(abilities.actioncard))\n random_action2 = str(\"🃏Карта дії №2:\\n \") + str(random.choice(abilities.actioncard))\n a = \"👫⏳👷🫃👼🦠👨‍🦽🕷🎨🎓🎒🗣🕍📝👵👨‍🦳\"\n await bot.send_message(message.chat.id, \"[👫](https://t.me/Bunker_beta_bot?start=share3)\" + random_sex, parse_mode=types.ParseMode.MARKDOWN)\n await bot.send_message(message.chat.id, random_age)\n await bot.send_message(message.chat.id, random_profession)\n await bot.send_message(message.chat.id, random_childability)\n await bot.send_message(message.chat.id, random_childdesire)\n await bot.send_message(message.chat.id, random_health)\n await bot.send_message(message.chat.id,random_disability)\n await bot.send_message(message.chat.id, random_phobia)\n await bot.send_message(message.chat.id, random_hobby)\n await bot.send_message(message.chat.id, random_education)\n await bot.send_message(message.chat.id, random_inventory)\n await bot.send_message(message.chat.id, random_nature)\n await bot.send_message(message.chat.id, random_religion)\n await bot.send_message(message.chat.id, random_addinfo)\n await bot.send_message(message.chat.id, random_mom)\n await bot.send_message(message.chat.id, random_dad)\n await bot.send_message(message.chat.id, random_action1)\n await bot.send_message(message.chat.id, random_action2)\n\n\n # Update the DataFrame with the 'stat' and 'ages' variables\n user_chat_id = message.chat.id\n user_full_name = message.from_user.full_name\n\n room_broadcast_text = f\"Характеристики гравця {message.from_user.full_name}\"\n\n df1 = pd.read_csv(csv_file_for_text)\n if user_chat_id in df1['Chat ID'].values:\n df1.loc[df['Chat ID'] == user_chat_id, 'Text'] = room_broadcast_text\n else:\n new_row = pd.DataFrame([[user_chat_id, room_broadcast_text]], columns=columns_for_text)\n df1 = pd.concat([df1, new_row], ignore_index=True)\n room_broadcast_text = \"\"\n texts = df1['Text']\n for text in texts:\n room_broadcast_text += text + \"\\n\\n\"\n specific_room_id = df.loc[df['Chat ID'] == user_chat_id]['Room ID'].iloc[0]\n\n global upload_room_message\n upload_room_message = []\n for index, member in df.iterrows():\n room_id = member['Room ID']\n chat_id = member['Chat ID']\n if room_id == specific_room_id:\n upload_room_message.append(await bot.send_message(chat_id, room_broadcast_text))\n df1.to_csv(csv_file_for_text, index=False)\n\n\n df.loc[df['Chat ID'] == user_chat_id, 'Sex'] = random_sex\n df.loc[df['Chat ID'] == user_chat_id, 'Age'] = random_age\n df.loc[df['Chat ID'] == user_chat_id, 'Profession'] = random_profession\n df.loc[df['Chat ID'] == user_chat_id, 'Child Ability'] = random_childability\n df.loc[df['Chat ID'] == user_chat_id, 'Child Desire'] = random_childdesire\n df.loc[df['Chat ID'] == user_chat_id, 'Health'] = random_health\n df.loc[df['Chat ID'] == user_chat_id, 'Disability'] = random_disability\n df.loc[df['Chat ID'] == user_chat_id, 'Phobia'] = random_phobia\n df.loc[df['Chat ID'] == user_chat_id, 'Hobby'] = random_hobby\n df.loc[df['Chat ID'] == user_chat_id, 'Education'] = random_education\n df.loc[df['Chat ID'] == user_chat_id, 'Inventory'] = random_inventory\n df.loc[df['Chat ID'] == user_chat_id, 'Nature'] = random_nature\n df.loc[df['Chat ID'] == user_chat_id, 'Religion'] = random_religion\n df.loc[df['Chat ID'] == user_chat_id, 'Additional Info'] = random_addinfo\n df.loc[df['Chat ID'] == user_chat_id, 'Mother'] = random_mom\n df.loc[df['Chat ID'] == user_chat_id, 'Father'] = random_dad\n df.loc[df['Chat ID'] == user_chat_id, 'Action 1'] = random_action1\n df.loc[df['Chat ID'] == user_chat_id, 'Action 2'] = random_action2\n\n df.to_csv(csv_file, index=False)\n@dp.message_handler(text='🌋Історія')\nasync def story(message):\n stories = [histories.story1, histories.story2, histories.story3, histories.story4,\n histories.story5, histories.story6, histories.story7, histories.story8]\n await bot.send_message(message.chat.id, str(random.choice(stories)))\n@dp.message_handler(text='📖Правила')\nasync def story(message):\n rules = \"\"\"Правила\\n \n• Кожен гравець створює свого персонажа за допомогою ключового слова \"Персона\" \\n\\\n• Колективним рішенням обирається людина, яка перед початком гри зачитає \\\nінформацію, яку отримає через кодові слова: \"Історія\" та \"Бункер\". \\n\\\n• Людина, яка оголошувала цю інформацію починає коло та обирає його напрям. \\n\\\n• Гравці по черзі повинні відкривати по 2 пункти на вибір свого персонажа кожного кола(Окрім \\\nпершого кола, під час нього усі відкривають свою стать, професію та одну х-ку на вибір) \\\nна це їм \\\nвідведено по 2 хвилини, за цей час вони повинні довести свою важливість для бункера \\\nвідносно тих характеристик, які вони відкрили щойно або раніше. \\n\\\n• У кінці кола гравці голосують за людину, яку буде вигнано з кола. \\n\\\n• Карти дій характеристиками не є і можуть бути застосовані в будь-який час гри(за виключенням моменту \\\nколи гравець, що використовує карту вигнаний з кола чи мертвий :) \\n\\\n• Ваша задача - протриматись у грі якомога довше \\n\\\n• Гра завершується, коли у колі залишається певна кількість людей, скільки саме - вирішувати вам \\n\\\nЩасти тобі потрапити в бункер \\n\\\n \"\"\"\n await bot.send_message(message.chat.id, str(rules))\n\n\n@dp.message_handler(commands=\"broadcast\")\nasync def broadcast(message: types.Message):\n bot_members_file = 'bot_members.csv'\n df_members = pd.read_csv(bot_members_file)\n if message.from_user.id == 275068212: # Replace YOUR_ADMIN_USER_ID with the actual user ID of the admin\n text = message.text[10:] # Extract the text after \"/broadcast \"\n if text:\n\n for index, member in df_members.iterrows():\n chat_id = member['Chat ID']\n await bot.send_message(chat_id, text)\n else:\n await message.reply(\"Please provide a message to broadcast.\")\n\n\n@dp.message_handler(commands=\"start\")\nasync def echo_message(message: types.Message):\n\n numbers = re.findall(r'\\d+', message.get_args())\n arg = 0\n for number in numbers:\n arg = number\n arg = int(arg)\n if message.get_args() == f\"share{arg}\":\n await message.delete()\n user_chat_id = message.chat.id\n df = pd.read_csv(csv_file_for_text)\n room_broadcast_text = df.loc[df['Chat ID'] == user_chat_id]['Text'].iloc[0]\n print(message.text)\n with open('bot_members.csv', 'r') as file:\n reader = csv.reader(file)\n next(reader)\n for row in reader:\n print(row[1])\n if row[1] == str(message.from_user.id):\n room_broadcast_text += \"\\n\"\n room_broadcast_text += row[arg]\n df.loc[df['Chat ID'] == user_chat_id, 'Text'] = room_broadcast_text\n df.to_csv(csv_file_for_text, index=False)\n texts = df['Text']\n room_broadcast_text = \"\"\n for text in texts:\n room_broadcast_text += text + \"\\n\\n\"\n for i in upload_room_message:\n await i.edit_text(text=room_broadcast_text)\n\n else:\n keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\n buttons = [\n \"Cтворити кімнату\",\n \"Приєднатися до кімнати\",\n ]\n keyboard.add(*buttons)\n\n await bot.send_message(\n message.chat.id,\n \"Вітаємо, {0.first_name}!\\nСтвори або долучись до ігрової кімнати, аби почати гру\\n \".format(\n message.from_user),\n parse_mode='html',\n reply_markup=keyboard\n )\n\n\n # You can perform further actions here if the condition is met\n # else:\n # await bot.send_message(message.from_user.id, str(\"Схоже щось пішло не так...\\nНатисни сюди — \\\"/start\\\"\"))\n\n\nif __name__ == \"__main__\":\n executor.start_polling(dp, skip_updates=True)\n","repo_name":"petrobubka/Bunker_bot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":19073,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"52"} +{"seq_id":"656834726","text":"# -*- coding: utf-8 -*-\nimport time\nimport pandas as pd\n\n\ndef max_volume_cluster(time_candle):\n \"\"\"\n Функция подсчитывает объемы по всем кластерам свечи и возвращает цену с макс объемом и этот макс объем в кластере\n :param time_candle: Время начала свечи\n :return: Цена кластера с макс объемом, макс объем из всех кластеров\n \"\"\"\n # Формирование df под одну свечу\n df_candle = df_ticks[df_ticks['